├── Palindrome_number.class ├── Palindrome_string.class ├── .vscode ├── c_cpp_properties.json ├── launch.json └── settings.json ├── Algorithms ├── SieveofEratosthenes.cpp ├── InsertionSort.java ├── CountSetBits.java ├── Dutch-National-Flag-Algo.cpp ├── CountSort.java ├── Linearsearch.java ├── smallestchair.java ├── Line-Sweep-Algorithm.cpp ├── Binary_Search.java ├── Pigeonhole Sort.java ├── LongestHappyString.java ├── Tree Set.java ├── BinarySearch.java ├── BubbleSort.java ├── Bubble_sort.java ├── FastPointerSlowPointer.java ├── Binary Search.java ├── quicksort.cpp ├── src │ └── test │ │ └── java │ │ └── com │ │ └── thealgorithms │ │ └── divideandconquer │ │ └── MedianOfTwoSortedArraysTest.java ├── Quick Sort.java ├── HeapSort.java ├── bubbleSort.py ├── Knapsack_Algo.cpp ├── Hare and Tortoise Algorithm ├── Spiral Matrix.java ├── Bellman-Ford algorithm ├── RangeMinimumQuery.java ├── N Queens Problem └── Range Minimum Query.java │ └── code ├── Palindrome_string.java ├── Data Structures ├── Trees │ ├── BinaryTree.java │ ├── preOrder.java │ └── postOrder.java ├── DFS for graph.java ├── BFS for graph.java ├── Topological Sorting.java ├── Bellman-Ford algorithm in C++ └── singlelinkedlist.java ├── Trapping_Rainwater_problem ├── Palindrome_number.java ├── Radix Sort.java ├── .github └── workflows │ └── gradle-publish.yml └── README.md /Palindrome_number.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayush7-BIT/turbo-robot/HEAD/Palindrome_number.class -------------------------------------------------------------------------------- /Palindrome_string.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ayush7-BIT/turbo-robot/HEAD/Palindrome_string.class -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x86", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "C:/MinGW/bin/gcc.exe", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x86", 12 | "compilerArgs": [ 13 | "" 14 | ] 15 | } 16 | ], 17 | "version": 4 18 | } -------------------------------------------------------------------------------- /Algorithms/SieveofEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define ll long long 4 | using namespace std; 5 | 6 | int Sieve(int n){ 7 | int count=0; 8 | vector prime(n+1,true); 9 | prime[0]=prime[1]=false; 10 | for(int i=2;i<=n;i++){ 11 | if(prime[i]){ 12 | count+=1; 13 | for(int j=i*i;j<=n;j+=i){ 14 | prime[j]=false;}}} 15 | return count;} 16 | int main(){ 17 | ll a; cin>>a; 18 | cout<=0 && val < arr[j]){ 9 | arr[j+1] = arr[j]; 10 | j--; 11 | } 12 | arr[j+1] = val; 13 | } 14 | System.out.println(Arrays.toString(args)); 15 | } 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /Algorithms/CountSetBits.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class CountSetBits { 4 | public static int countSetBits(int n) { 5 | int count = 0; 6 | 7 | while (n > 0) { 8 | n = n & (n - 1); 9 | count++; 10 | } 11 | 12 | return count; 13 | } 14 | 15 | public static void main(String[] args) { 16 | Scanner sc = new Scanner(System.in); 17 | int n = sc.nextInt(); 18 | System.out.println(countSetBits(n)); 19 | sc.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/Dutch-National-Flag-Algo.cpp: -------------------------------------------------------------------------------- 1 | void sortColors(vector& arr) { 2 | int low = 0, mid = 0, high = arr.size() - 1; 3 | 4 | while (mid <= high) { 5 | if (arr[mid] == 0) { 6 | swap(arr[low], arr[mid]); 7 | low++; 8 | mid++; 9 | } 10 | else if (arr[mid] == 1) { 11 | mid++; // 1 is already in its correct place 12 | } 13 | else { // arr[mid] == 2 14 | swap(arr[mid], arr[high]); 15 | high--; // Decrement high to place the 2 at the end 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "externalConsole": true, 11 | "cwd": "d:/turbo-robot/Algorithms", 12 | "program": "d:/turbo-robot/Algorithms/build/Debug/outDebug", 13 | "MIMode": "gdb", 14 | "miDebuggerPath": "gdb", 15 | "setupCommands": [ 16 | { 17 | "description": "Enable pretty-printing for gdb", 18 | "text": "-enable-pretty-printing", 19 | "ignoreFailures": true 20 | } 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /Algorithms/CountSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class CountSort { 4 | public static void main(String[] args) { 5 | int[] arr ={-3,2,1,0,4,5,7}; 6 | int max = Arrays.stream(arr).max().getAsInt(); 7 | int min = Arrays.stream(arr).min().getAsInt(); 8 | int[] freq = new int[max-min+1]; 9 | for (int i = 0; i < arr.length; i++) { 10 | freq[arr[i]-min]++; 11 | } 12 | int k=0; 13 | for (int i = min; i <=max ; i++) { 14 | for (int j = 1; j <=freq[i-min] ; j++) { 15 | arr[k] = i; 16 | k++; 17 | } 18 | } 19 | System.out.println(Arrays.toString(arr)); 20 | } 21 | } -------------------------------------------------------------------------------- /Algorithms/Linearsearch.java: -------------------------------------------------------------------------------- 1 | // Java code for linearly searching x in arr[]. 2 | 3 | import java.io.*; 4 | 5 | class GFG { 6 | public static int search(int arr[], int N, int x) 7 | { 8 | for (int i = 0; i < N; i++) { 9 | if (arr[i] == x) 10 | return i; 11 | } 12 | return -1; 13 | } 14 | 15 | // Driver code 16 | public static void main(String args[]) 17 | { 18 | int arr[] = { 2, 3, 4, 10, 40 }; 19 | int x = 10; 20 | 21 | // Function call 22 | int result = search(arr, arr.length, x); 23 | if (result == -1) 24 | System.out.print( 25 | "Element is not present in array"); 26 | else 27 | System.out.print("Element is present at index " 28 | + result); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/smallestchair.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestChair(int[][] times, int targetFriend) { 3 | int target = times[targetFriend][0]; 4 | Arrays.sort(times, (a, b) -> a[0] - b[0]); 5 | 6 | PriorityQueue pq = new PriorityQueue<>(); 7 | for (int i = 0; i < times.length; i++) { 8 | pq.offer(i); 9 | } 10 | 11 | PriorityQueue pq_ = new PriorityQueue<>((a, b) -> a[0] - b[0]); 12 | for (int i = 0; i < times.length; i++) { 13 | while (!pq_.isEmpty() && pq_.peek()[0] <= times[i][0]) { 14 | pq.offer(pq_.poll()[1]); 15 | } 16 | 17 | if (times[i][0] == target) { 18 | break; 19 | } 20 | pq_.offer(new int[] { times[i][1], pq.poll() }); 21 | } 22 | return pq.peek(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/Line-Sweep-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // Added function for solving time interval problem using Line Sweep Algorithm 2 | int minGroups(vector>& intervals) { 3 | map pointToCount; 4 | // Mark the starting and ending points in the map 5 | for (vector interval : intervals) { 6 | pointToCount[interval[0]]++; 7 | pointToCount[interval[1] + 1]--; 8 | } 9 | 10 | int concurrentIntervals = 0; 11 | int maxConcurrentIntervals = 0; 12 | // Iterate over the numbers in ascending order 13 | for (pair p : pointToCount) { 14 | // Add the currently active intervals 15 | concurrentIntervals += p.second; 16 | 17 | // Update the maximum active intervals at any time 18 | maxConcurrentIntervals = 19 | max(maxConcurrentIntervals, concurrentIntervals); 20 | } 21 | 22 | return maxConcurrentIntervals; 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/Binary_Search.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | private static int binarySearch(int numArray[], int number_to_search_for) { 3 | int low = 0; 4 | int high = numArray.length - 1; 5 | 6 | while (low <= high){ 7 | int middleIndex = (low + high) / 2; 8 | int middleIndexNumber = numArray[middleIndex]; 9 | 10 | if (number_to_search_for == middleIndexNumber){ 11 | return middleIndex; 12 | } 13 | if (number_to_search_for < middleIndexNumber){ 14 | high = middleIndex - 1; 15 | } 16 | if (number_to_search_for > middleIndexNumber){ 17 | low = middleIndex + 1; 18 | } 19 | } 20 | 21 | return -1; 22 | } 23 | public static void main(String args[]) { 24 | 25 | int[] arrayofnums = {2,3,6,8,9,13,20}; 26 | 27 | System.out.println(binarySearch(arrayofnums, 13)); 28 | // 5 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Palindrome_string.java: -------------------------------------------------------------------------------- 1 | public class Palindrome_string { 2 | public static void main(String[] args) { 3 | Palindrome_string obj = new Palindrome_string(); 4 | boolean ans = obj.Palindrome_string("manad"); 5 | System.out.println(ans); 6 | } 7 | 8 | public boolean Palindrome_string(String str) { 9 | int left=0; 10 | int right =str.length()-1; // last character of string . 11 | 12 | while(left[] pigeonholes = new ArrayList[range]; 10 | for (int i = 0; i < range; i++) { 11 | pigeonholes[i] = new ArrayList<>(); 12 | } 13 | 14 | for (int num : arr) { 15 | pigeonholes[num - min].add(num); 16 | } 17 | 18 | int index = 0; 19 | for (List hole : pigeonholes) { 20 | for (int num : hole) { 21 | arr[index++] = num; 22 | } 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] arr = {8, 3, 2, 7, 4, 6, 8}; 28 | System.out.println("Given Array: " + Arrays.toString(arr)); 29 | 30 | pigeonholeSort(arr); 31 | 32 | System.out.println("Sorted Array: " + Arrays.toString(arr)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/LongestHappyString.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestDiverseString(int a, int b, int c) { 3 | StringBuilder sb = new StringBuilder(); 4 | 5 | int contA = 0, contB = 0, contC = 0; 6 | int total = a + b + c; 7 | for (int i = 0; i < total; i++) { 8 | if ((a >= b && a >= c && contA != 2) || ((contB == 2 || contC == 2) && a > 0)) { 9 | sb.append("a"); 10 | a--; 11 | contA++; 12 | contB = 0; 13 | contC = 0; 14 | } else if ((b >= a && b >= c && contB != 2) || ((contA == 2 || contC == 2) && b > 0)) { 15 | sb.append("b"); 16 | b--; 17 | contB++; 18 | contA = 0; 19 | contC = 0; 20 | } else if ((c >= a && c >= b && contC != 2) || ((contA == 2 || contB == 2) && c > 0)) { 21 | sb.append("c"); 22 | c--; 23 | contC++; 24 | contA = 0; 25 | contB = 0; 26 | } 27 | } 28 | return sb.toString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Tree Set.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeSet; 2 | import java.util.Comparator; 3 | 4 | public class TreeSetExample { 5 | public static void main(String[] args) { 6 | // Creating a TreeSet with natural ordering 7 | TreeSet treeSet = new TreeSet<>(); 8 | treeSet.add("Apple"); 9 | treeSet.add("Banana"); 10 | treeSet.add("Cherry"); 11 | 12 | // Iterating over the TreeSet 13 | System.out.println("TreeSet with natural ordering:"); 14 | for (String fruit : treeSet) { 15 | System.out.println(fruit); 16 | } 17 | 18 | // Creating a TreeSet with custom comparator (reverse order) 19 | TreeSet customTreeSet = new TreeSet<>(Comparator.reverseOrder()); 20 | customTreeSet.add("Apple"); 21 | customTreeSet.add("Banana"); 22 | customTreeSet.add("Cherry"); 23 | 24 | // Iterating over the TreeSet with custom comparator 25 | System.out.println("\nTreeSet with custom comparator (reverse order):"); 26 | for (String fruit : customTreeSet) { 27 | System.out.println(fruit); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | 3 | // Binary Search using iterative method 4 | public static int binarySearch(int[] arr, int target) { 5 | if (arr == null || arr.length == 0) { 6 | return -1; 7 | } 8 | 9 | int left = 0; 10 | int right = arr.length - 1; 11 | 12 | while (left <= right) { 13 | int mid = left + (right - left) / 2; 14 | 15 | if (arr[mid] == target) { 16 | return mid; 17 | } 18 | 19 | if (arr[mid] < target) { 20 | left = mid + 1; 21 | } else { 22 | right = mid - 1; 23 | } 24 | } 25 | 26 | return -1; 27 | } 28 | 29 | public static void main(String[] args) { 30 | int[] Array = {2, 5, 7, 10, 14, 20, 25}; 31 | int target = 14; 32 | 33 | int result = binarySearch(Array, target); 34 | 35 | if (result != -1) { 36 | System.out.println("Target element found at index: " + result); 37 | } else { 38 | System.out.println("Target element not found! "); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Trapping_Rainwater_problem: -------------------------------------------------------------------------------- 1 | public class TrappingRainWater { 2 | 3 | public static int trap(int[] height) { 4 | if (height == null || height.length == 0) { 5 | return 0; 6 | } 7 | 8 | int n = height.length; 9 | int left = 0, right = n - 1; 10 | int leftMax = 0, rightMax = 0; 11 | int waterTrapped = 0; 12 | 13 | while (left < right) { 14 | if (height[left] < height[right]) { 15 | if (height[left] >= leftMax) { 16 | leftMax = height[left]; 17 | } else { 18 | waterTrapped += leftMax - height[left]; 19 | } 20 | left++; 21 | } else { 22 | if (height[right] >= rightMax) { 23 | rightMax = height[right]; 24 | } else { 25 | waterTrapped += rightMax - height[right]; 26 | } 27 | right--; 28 | } 29 | } 30 | 31 | return waterTrapped; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}; 36 | System.out.println("Water trapped: " + trap(height)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSort { 2 | public static void sort(int[] elements) { 3 | for (int max = elements.length - 1; max > 0; max--) { 4 | boolean swapped = false; 5 | for (int i = 0; i < max; i++) { 6 | int left = elements[i]; 7 | int right = elements[i + 1]; 8 | if (left > right) { 9 | elements[i + 1] = left; 10 | elements[i] = right; 11 | swapped = true; 12 | } 13 | } 14 | if (!swapped) break; 15 | } 16 | } 17 | 18 | 19 | // Prints the array 20 | public static void printArray(int[] elements) { 21 | for (int element : elements) { 22 | System.out.print(element + " "); 23 | } 24 | System.out.println(); 25 | } 26 | 27 | // main method to test above 28 | public static void main(String[] args) { 29 | int[] elements = {64, 34, 25, 12, 22, 11, 90}; // Sample array to sort 30 | 31 | System.out.println("Array before sorting:"); 32 | printArray(elements); 33 | 34 | // Calling the bubble sort function 35 | BubbleSort.sort(elements); 36 | 37 | System.out.println("Array after sorting:"); 38 | printArray(elements); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Palindrome_number.java: -------------------------------------------------------------------------------- 1 | 2 | public class Palindrome_number { 3 | public static void main(String[] args) { 4 | Palindrome_number obj = new Palindrome_number(); 5 | boolean ans = obj.palindrome(121); 6 | System.out.println(ans); 7 | } 8 | 9 | public boolean palindrome(int num) { 10 | if(num<0){ //if number is less than zero then return false; 11 | return false; 12 | } 13 | int rev=0; //define a varible rev. for reveses number. 14 | int original=num; //redefined the value of num. 15 | while(num>0){ //while loop upto the num greater than 0 16 | rev=rev*10+num%10; //this is logic for reverse the number. 17 | num=num/10; //last digit deleted. 18 | } 19 | return rev==original; // check 20 | } 21 | } 22 | 23 | 24 | //👉🏻👉🏻👉🏻 time complexity=constant. O(1) 25 | //👉🏻👉🏻👉🏻spacd complexity=constant. O(1); 26 | 27 | //👉🏻👉🏻👉🏻 logic.- (rev = rev * 10 + x % 10; and x = x / 10;) 28 | //Modulo operator (%) is used to extract the last digit of the number. 29 | // division (/) is used to remove the last digit of the number. 30 | //Palindrome property: A number is a palindrome if it reads the same forward and backward. 31 | 32 | -------------------------------------------------------------------------------- /Data Structures/Trees/preOrder.java: -------------------------------------------------------------------------------- 1 | // preOrder.java 2 | class Node { 3 | int data; 4 | Node left, right; 5 | 6 | public Node(int item) { 7 | data = item; 8 | left = right = null; 9 | } 10 | } 11 | 12 | public class preOrder { 13 | class BinaryTree { 14 | Node root; 15 | 16 | void preOrderTraversal(Node node) { 17 | if (node == null) { 18 | return; 19 | } 20 | 21 | // Visit the root node 22 | System.out.print(node.data + " "); 23 | 24 | // Traverse the left subtree 25 | preOrderTraversal(node.left); 26 | 27 | // Traverse the right subtree 28 | preOrderTraversal(node.right); 29 | } 30 | } 31 | 32 | public static void main(String[] args) { 33 | preOrder outer = new preOrder(); 34 | BinaryTree tree = outer.new BinaryTree(); 35 | tree.root = new Node(1); 36 | tree.root.left = new Node(2); 37 | tree.root.right = new Node(3); 38 | tree.root.left.left = new Node(4); 39 | tree.root.left.right = new Node(5); 40 | 41 | System.out.println("Preorder traversal of binary tree is:"); 42 | tree.preOrderTraversal(tree.root); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Radix Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class RadixSort { 4 | public static void radixSort(int[] arr) { 5 | int max = Arrays.stream(arr).max().orElse(Integer.MIN_VALUE); 6 | for (int exp = 1; max / exp > 0; exp *= 10) { 7 | countingSort(arr, exp); 8 | } 9 | } 10 | 11 | private static void countingSort(int[] arr, int exp) { 12 | int n = arr.length; 13 | int[] output = new int[n]; 14 | int[] count = new int[10]; 15 | Arrays.fill(count, 0); 16 | 17 | for (int i = 0; i < n; i++) { 18 | count[(arr[i] / exp) % 10]++; 19 | } 20 | 21 | for (int i = 1; i < 10; i++) { 22 | count[i] += count[i - 1]; 23 | } 24 | 25 | for (int i = n - 1; i >= 0; i--) { 26 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 27 | count[(arr[i] / exp) % 10]--; 28 | } 29 | 30 | System.arraycopy(output, 0, arr, 0, n); 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; 35 | System.out.println("Given Array: " + Arrays.toString(arr)); 36 | 37 | radixSort(arr); 38 | 39 | System.out.println("Sorted Array: " + Arrays.toString(arr)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Bubble_sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class BubbleSort { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | 8 | //input for size 9 | System.out.print("Enter the number of elements: "); 10 | int size = scanner.nextInt(); 11 | int[] nums = new int[size]; 12 | 13 | System.out.println("Enter the elements of the array:"); 14 | for (int i = 0; i < size; i++) { 15 | nums[i] = scanner.nextInt(); 16 | } 17 | 18 | int temp; 19 | 20 | System.out.println("Before sorting:"); 21 | for (int num : nums) { 22 | System.out.println(num); 23 | } 24 | 25 | // Bubble sort logic 26 | for (int i = 0; i < size; i++) { 27 | for (int j = 0; j < size - i - 1; j++) { 28 | if (nums[j] > nums[j + 1]) { 29 | temp = nums[j]; 30 | nums[j] = nums[j + 1]; 31 | nums[j + 1] = temp; 32 | } 33 | } 34 | } 35 | 36 | //Output 37 | System.out.println("After sorting:"); 38 | for (int num : nums) { 39 | System.out.println(num); 40 | } 41 | 42 | scanner.close(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Data Structures/Trees/postOrder.java: -------------------------------------------------------------------------------- 1 | public class postOrder { 2 | class Node { 3 | int data; 4 | Node left, right; 5 | 6 | public Node(int item) { 7 | data = item; 8 | left = right = null; 9 | } 10 | } 11 | 12 | class BinaryTree { 13 | Node root; 14 | 15 | void postOrderTraversal(Node node) { 16 | if (node == null) { 17 | return; 18 | } 19 | 20 | // Traverse the left subtree 21 | postOrderTraversal(node.left); 22 | 23 | // Traverse the right subtree 24 | postOrderTraversal(node.right); 25 | 26 | // Visit the root node 27 | System.out.print(node.data + " "); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | postOrder outer = new postOrder(); 33 | BinaryTree tree = outer.new BinaryTree(); 34 | tree.root = outer.new Node(1); 35 | tree.root.left = outer.new Node(2); 36 | tree.root.right = outer.new Node(3); 37 | tree.root.left.left = outer.new Node(4); 38 | tree.root.left.right = outer.new Node(5); 39 | 40 | System.out.println("Postorder traversal of binary tree is:"); 41 | tree.postOrderTraversal(tree.root); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/FastPointerSlowPointer.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | 5 | ListNode(int val) { 6 | this.val = val; 7 | this.next = null; 8 | } 9 | } 10 | 11 | public class FastPointerSlowPointer { 12 | public boolean hasCycle(ListNode head) { 13 | if (head == null || head.next == null) { 14 | return false; 15 | } 16 | 17 | 18 | ListNode slow = head; 19 | ListNode fast = head; 20 | 21 | // Traverse the list with both pointers 22 | while (fast != null && fast.next != null) { 23 | slow = slow.next; 24 | fast = fast.next.next; 25 | 26 | if (slow == fast) { 27 | return true; 28 | } 29 | } 30 | 31 | return false; 32 | } 33 | 34 | public static void main(String[] args) { 35 | 36 | FastPointerSlowPointer solution = new FastPointerSlowPointer(); 37 | 38 | 39 | ListNode node1 = new ListNode(1); 40 | ListNode node2 = new ListNode(2); 41 | ListNode node3 = new ListNode(3); 42 | ListNode node4 = new ListNode(4); 43 | 44 | node1.next = node2; 45 | node2.next = node3; 46 | node3.next = node4; 47 | node4.next = node2; 48 | 49 | 50 | boolean result = solution.hasCycle(node1); 51 | System.out.println("Cycle detected: " + result); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Data Structures/DFS for graph.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Graph { 4 | private int V; // Nu. of vertices 5 | private LinkedList adj[]; 6 | 7 | @SuppressWarnings("unchecked") 8 | Graph(int v) { 9 | V = v; 10 | adj = new LinkedList[v]; 11 | for (int i = 0; i < v; ++i) 12 | adj[i] = new LinkedList(); 13 | } 14 | 15 | // add an edge to the graph 16 | void addEdge(int v, int w) { 17 | adj[v].add(w); 18 | } 19 | 20 | // A function used by DFS 21 | void DFSUtil(int v, boolean visited[]) { 22 | visited[v] = true; 23 | System.out.print(v + " "); 24 | 25 | Iterator i = adj[v].listIterator(); 26 | while (i.hasNext()) { 27 | int n = i.next(); 28 | if (!visited[n]) 29 | DFSUtil(n, visited); 30 | } 31 | } 32 | 33 | // function to DFS traversal 34 | void DFS(int v) { 35 | boolean visited[] = new boolean[V]; 36 | 37 | // Call the recursive helper function to print DFS traversal 38 | DFSUtil(v, visited); 39 | } 40 | 41 | public static void main(String args[]) { 42 | Graph g = new Graph(4); 43 | 44 | g.addEdge(0, 1); 45 | g.addEdge(0, 2); 46 | g.addEdge(1, 2); 47 | g.addEdge(2, 0); 48 | g.addEdge(2, 3); 49 | g.addEdge(3, 3); 50 | 51 | System.out.println("Following is Depth First Traversal (starting from vertex 2)"); 52 | 53 | g.DFS(2); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Algorithms/Binary Search.java: -------------------------------------------------------------------------------- 1 | // Java implementation of iterative Binary Search 2 | 3 | import java.io.*; 4 | 5 | class BinarySearch { 6 | 7 | // Returns index of x if it is present in arr[]. 8 | int binarySearch(int arr[], int x) 9 | { 10 | // Check if the array is null or empty 11 | if (arr == null || arr.length == 0) { 12 | return -1; 13 | } 14 | 15 | int low = 0, high = arr.length - 1; 16 | while (low <= high) { 17 | int mid = low + (high - low) / 2; 18 | 19 | // Check if x is present at mid 20 | if (arr[mid] == x) 21 | return mid; 22 | 23 | // If x greater, ignore left half 24 | if (arr[mid] < x) 25 | low = mid + 1; 26 | 27 | // If x is smaller, ignore right half 28 | else 29 | high = mid - 1; 30 | } 31 | 32 | // If we reach here, then element was 33 | // not present 34 | return -1; 35 | } 36 | 37 | // Driver code 38 | public static void main(String args[]) 39 | { 40 | BinarySearch ob = new BinarySearch(); 41 | int arr[] = { 2, 3, 4, 10, 40 }; 42 | int x = 10; 43 | int result = ob.binarySearch(arr, x); 44 | if (result == -1) 45 | System.out.println( 46 | "Element is not present in array"); 47 | else 48 | System.out.println("Element is present at " 49 | + "index " + result); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /.github/workflows/gradle-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created 6 | # For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle 7 | 8 | name: Gradle Package 9 | 10 | on: 11 | release: 12 | types: [created] 13 | 14 | jobs: 15 | build: 16 | 17 | runs-on: ubuntu-latest 18 | permissions: 19 | contents: read 20 | packages: write 21 | 22 | steps: 23 | - uses: actions/checkout@v4 24 | - name: Set up JDK 17 25 | uses: actions/setup-java@v4 26 | with: 27 | java-version: '17' 28 | distribution: 'temurin' 29 | server-id: github # Value of the distributionManagement/repository/id field of the pom.xml 30 | settings-path: ${{ github.workspace }} # location for the settings.xml file 31 | 32 | - name: Setup Gradle 33 | uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 34 | 35 | - name: Build with Gradle 36 | run: ./gradlew build 37 | 38 | # The USERNAME and TOKEN need to correspond to the credentials environment variables used in 39 | # the publishing section of your build.gradle 40 | - name: Publish to GitHub Packages 41 | run: ./gradlew publish 42 | env: 43 | USERNAME: ${{ github.actor }} 44 | TOKEN: ${{ secrets.GITHUB_TOKEN }} 45 | -------------------------------------------------------------------------------- /Algorithms/quicksort.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to demonstrate how to implement the quick 2 | // sort algorithm 3 | #include 4 | using namespace std; 5 | 6 | int partition(vector &vec, int low, int high) { 7 | 8 | // Selecting last element as the pivot 9 | int pivot = vec[high]; 10 | 11 | // Index of elemment just before the last element 12 | // It is used for swapping 13 | int i = (low - 1); 14 | 15 | for (int j = low; j <= high - 1; j++) { 16 | 17 | // If current element is smaller than or 18 | // equal to pivot 19 | if (vec[j] <= pivot) { 20 | i++; 21 | swap(vec[i], vec[j]); 22 | } 23 | } 24 | 25 | // Put pivot to its position 26 | swap(vec[i + 1], vec[high]); 27 | 28 | // Return the point of partition 29 | return (i + 1); 30 | } 31 | 32 | void quickSort(vector &vec, int low, int high) { 33 | 34 | // Base case: This part will be executed till the starting 35 | // index low is lesser than the ending index high 36 | if (low < high) { 37 | 38 | // pi is Partitioning Index, arr[p] is now at 39 | // right place 40 | int pi = partition(vec, low, high); 41 | 42 | // Separately sort elements before and after the 43 | // Partition Index pi 44 | quickSort(vec, low, pi - 1); 45 | quickSort(vec, pi + 1, high); 46 | } 47 | } 48 | 49 | int main() { 50 | vector vec = {10, 7, 8, 9, 1, 5}; 51 | int n = vec.size(); 52 | 53 | // Calling quicksort for the vector vec 54 | quickSort(vec, 0, n - 1); 55 | 56 | for (auto i : vec) { 57 | cout << i << " "; 58 | } 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "gcc", 3 | "C_Cpp_Runner.cppCompilerPath": "g++", 4 | "C_Cpp_Runner.debuggerPath": "gdb", 5 | "C_Cpp_Runner.cStandard": "", 6 | "C_Cpp_Runner.cppStandard": "", 7 | "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat", 8 | "C_Cpp_Runner.useMsvc": false, 9 | "C_Cpp_Runner.warnings": [ 10 | "-Wall", 11 | "-Wextra", 12 | "-Wpedantic", 13 | "-Wshadow", 14 | "-Wformat=2", 15 | "-Wcast-align", 16 | "-Wconversion", 17 | "-Wsign-conversion", 18 | "-Wnull-dereference" 19 | ], 20 | "C_Cpp_Runner.msvcWarnings": [ 21 | "/W4", 22 | "/permissive-", 23 | "/w14242", 24 | "/w14287", 25 | "/w14296", 26 | "/w14311", 27 | "/w14826", 28 | "/w44062", 29 | "/w44242", 30 | "/w14905", 31 | "/w14906", 32 | "/w14263", 33 | "/w44265", 34 | "/w14928" 35 | ], 36 | "C_Cpp_Runner.enableWarnings": true, 37 | "C_Cpp_Runner.warningsAsError": false, 38 | "C_Cpp_Runner.compilerArgs": [], 39 | "C_Cpp_Runner.linkerArgs": [], 40 | "C_Cpp_Runner.includePaths": [], 41 | "C_Cpp_Runner.includeSearch": [ 42 | "*", 43 | "**/*" 44 | ], 45 | "C_Cpp_Runner.excludeSearch": [ 46 | "**/build", 47 | "**/build/**", 48 | "**/.*", 49 | "**/.*/**", 50 | "**/.vscode", 51 | "**/.vscode/**" 52 | ], 53 | "C_Cpp_Runner.useAddressSanitizer": false, 54 | "C_Cpp_Runner.useUndefinedSanitizer": false, 55 | "C_Cpp_Runner.useLeakSanitizer": false, 56 | "C_Cpp_Runner.showCompilationTime": false, 57 | "C_Cpp_Runner.useLinkTimeOptimization": false, 58 | "C_Cpp_Runner.msvcSecureNoWarnings": false 59 | } -------------------------------------------------------------------------------- /Algorithms/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.divideandconquer; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.Arguments; 8 | import org.junit.jupiter.params.provider.MethodSource; 9 | 10 | public class MedianOfTwoSortedArraysTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCases") 14 | void testFindMedianSortedArrays(int[] nums1, int[] nums2, double expectedMedian) { 15 | assertEquals(expectedMedian, MedianOfTwoSortedArrays.findMedianSortedArrays(nums1, nums2)); 16 | } 17 | 18 | private static Stream provideTestCases() { 19 | return Stream.of( 20 | // Test case 1: Arrays of equal length 21 | Arguments.of(new int[] {1, 3}, new int[] {2, 4}, 2.5), 22 | 23 | // Test case 2: Arrays of different lengths 24 | Arguments.of(new int[] {1, 3}, new int[] {2}, 2.0), 25 | 26 | // Test case 3: Arrays with even total length 27 | Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5, 6, 7}, 4.5), 28 | 29 | // Test case 4: Arrays with odd total length 30 | Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5}, 3.5), 31 | 32 | // Test case 5: Single element arrays 33 | Arguments.of(new int[] {1}, new int[] {3}, 2.0), 34 | 35 | // Test case 6: Empty arrays 36 | Arguments.of(new int[] {}, new int[] {0}, 0.0), 37 | 38 | // Test case 7: Same element arrays 39 | Arguments.of(new int[] {2, 2, 2}, new int[] {2, 2, 2}, 2.0)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Quick Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class GfG { 4 | 5 | // Partition function 6 | static int partition(int[] arr, int low, int high) { 7 | 8 | // Choose the pivot 9 | int pivot = arr[high]; 10 | 11 | // Index of smaller element and indicates 12 | // the right position of pivot found so far 13 | int i = low - 1; 14 | 15 | // Traverse arr[low..high] and move all smaller 16 | // elements to the left side. Elements from low to 17 | // i are smaller after every iteration 18 | for (int j = low; j <= high - 1; j++) { 19 | if (arr[j] < pivot) { 20 | i++; 21 | swap(arr, i, j); 22 | } 23 | } 24 | 25 | // Move pivot after smaller elements and 26 | // return its position 27 | swap(arr, i + 1, high); 28 | return i + 1; 29 | } 30 | 31 | // Swap function 32 | static void swap(int[] arr, int i, int j) { 33 | int temp = arr[i]; 34 | arr[i] = arr[j]; 35 | arr[j] = temp; 36 | } 37 | 38 | // The QuickSort function implementation 39 | static void quickSort(int[] arr, int low, int high) { 40 | if (low < high) { 41 | 42 | // pi is the partition return index of pivot 43 | int pi = partition(arr, low, high); 44 | 45 | // Recursion calls for smaller elements 46 | // and greater or equals elements 47 | quickSort(arr, low, pi - 1); 48 | quickSort(arr, pi + 1, high); 49 | } 50 | } 51 | 52 | public static void main(String[] args) { 53 | int[] arr = {10, 7, 8, 9, 1, 5}; 54 | int n = arr.length; 55 | 56 | quickSort(arr, 0, n - 1); 57 | 58 | for (int val : arr) { 59 | System.out.print(val + " "); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Algorithms/HeapSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class HeapSort { 4 | 5 | // Main function to sort an array using heap sort 6 | public static void heapSort(int[] array) { 7 | int n = array.length; 8 | 9 | // Build a max heap 10 | for (int i = n / 2 - 1; i >= 0; i--) { 11 | heapify(array, n, i); 12 | } 13 | 14 | // One by one extract elements from heap 15 | for (int i = n - 1; i >= 0; i--) { 16 | // Move the current root (maximum) to the end 17 | int temp = array[0]; 18 | array[0] = array[i]; 19 | array[i] = temp; 20 | 21 | // Call max heapify on the reduced heap 22 | heapify(array, i, 0); 23 | } 24 | } 25 | 26 | // To heapify a subtree rooted with node i, which is an index in array[]. 27 | // n is the size of the heap 28 | private static void heapify(int[] array, int n, int i) { 29 | int largest = i; 30 | int left = 2 * i + 1; 31 | int right = 2 * i + 2; 32 | // If left child is larger than root 33 | if (left < n && array[left] > array[largest]) { 34 | largest = left; 35 | } 36 | 37 | // If right child is larger than largest so far 38 | if (right < n && array[right] > array[largest]) { 39 | largest = right; 40 | } 41 | 42 | // If largest is not root 43 | if (largest != i) { 44 | int swap = array[i]; 45 | array[i] = array[largest]; 46 | array[largest] = swap; 47 | 48 | // Recursively heapify the affected subtree 49 | heapify(array, n, largest); 50 | } 51 | } 52 | 53 | // Main method to test the heap sort implementation 54 | public static void main(String[] args) { 55 | int[] arr = {12, 11, 13, 5, 6, 7}; 56 | System.out.println("Original array: " + Arrays.toString(arr)); 57 | 58 | heapSort(arr); 59 | 60 | System.out.println("Sorted array: " + Arrays.toString(arr)); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Algorithms/bubbleSort.py: -------------------------------------------------------------------------------- 1 | def dynamic_bubble_sort(arr): 2 | n = len(arr) 3 | swapped = True 4 | passes = 0 5 | 6 | while swapped: 7 | swapped = False 8 | passes += 1 9 | 10 | # Forward pass 11 | for i in range(n - passes): 12 | if arr[i] > arr[i + 1]: 13 | arr[i], arr[i + 1] = arr[i + 1], arr[i] 14 | swapped = True 15 | 16 | if not swapped: 17 | break 18 | 19 | swapped = False 20 | 21 | # Backward pass 22 | for i in range(n - passes - 1, passes - 1, -1): 23 | if arr[i] < arr[i - 1]: 24 | arr[i], arr[i - 1] = arr[i - 1], arr[i] 25 | swapped = True 26 | 27 | return arr 28 | 29 | # Test function 30 | def test_sort(arr, name): 31 | print(f"\nTesting {name}:") 32 | print("Original:", arr) 33 | sorted_arr = dynamic_bubble_sort(arr.copy()) 34 | print("Sorted: ", sorted_arr) 35 | print("Correct: ", sorted_arr == sorted(arr)) 36 | 37 | # Test cases 38 | test_sort([64, 34, 25, 12, 22, 11, 90], "Random array") 39 | test_sort([1, 2, 3, 4, 5], "Already sorted array") 40 | test_sort([5, 4, 3, 2, 1], "Reverse sorted array") 41 | test_sort([1, 1, 1, 1, 1], "Array with all equal elements") 42 | test_sort([1], "Single element array") 43 | test_sort([], "Empty array") 44 | test_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], "Array with repeated elements") 45 | test_sort([10, -1, 3, 9, -13, 5, 7], "Array with negative numbers") 46 | test_sort([10**9, 10**5, 10**2, 10**7], "Array with large numbers") 47 | test_sort([1.5, 2.3, 0.7, 1.9, 1.1], "Array with floating-point numbers") 48 | 49 | # Performance test 50 | import time 51 | import random 52 | 53 | def performance_test(size): 54 | arr = [random.randint(1, 1000) for _ in range(size)] 55 | start_time = time.time() 56 | dynamic_bubble_sort(arr) 57 | end_time = time.time() 58 | print(f"\nTime taken to sort {size} elements: {end_time - start_time:.6f} seconds") 59 | 60 | performance_test(100) 61 | performance_test(1000) -------------------------------------------------------------------------------- /Algorithms/Knapsack_Algo.cpp: -------------------------------------------------------------------------------- 1 | //*PROBLEM-STATEMENT*// 2 | // We have ( N ) items, each with a specific weight and profit.Additionally, we have a bag with a maximum capacity of ( W ) weight units. 3 | // The goal is to select items to place in the bag so that the total profit is maximized. 4 | 5 | 6 | #include 7 | using namespace std; 8 | 9 | int knapsack_Algo(int W, int weights[], int profits[], int n) 10 | { 11 | int w , i; 12 | vector > dp(n + 1, vector(W + 1)); 13 | 14 | // Tabulation Approach 15 | for (i = 0; i <= n; i++) { 16 | for (w = 0; w <= W; w++) { 17 | if (i == 0 || w == 0) dp[i][w] = 0; 18 | else if (weights[i - 1] <= w) dp[i][w] = max(profits[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]); 19 | else dp[i][w] = dp[i - 1][w]; 20 | } 21 | } 22 | return dp[n][W]; 23 | } 24 | 25 | int main() 26 | { 27 | int W = 70; //maximum weight capacity of bag 28 | int profit[] = { 40, 120, 80, 200, 50 }; // profit array 29 | int weight[] = { 5, 40, 30, 80, 20 }; //coresponding weight array 30 | int N = sizeof(profit) / sizeof(profit[0]); 31 | 32 | int maximum_profit = knapsack_Algo(W, weight, profit, N); 33 | cout <<"Maximum Profit that can be obtained is : "< If either the item count i or the capacity w is zero, the profit is zero. 49 | // -> If the weight of the current item is less than or equal to the current capacity, the algorithm decides whether to include the item or not by comparing the profit of including the item with the profit of excluding it. 50 | // -> If the weight of the current item exceeds the current capacity, the item is excluded. -------------------------------------------------------------------------------- /Algorithms/Hare and Tortoise Algorithm: -------------------------------------------------------------------------------- 1 | class LinkedList { 2 | Node head; // Head of the list 3 | 4 | // Node class for linked list 5 | static class Node { 6 | int data; 7 | Node next; 8 | 9 | Node(int data) { 10 | this.data = data; 11 | next = null; 12 | } 13 | } 14 | 15 | // Function to detect cycle in the linked list using Hare and Tortoise algorithm 16 | public boolean hasCycle() { 17 | Node slow = head; 18 | Node fast = head; 19 | 20 | // Traverse the list with two pointers 21 | while (fast != null && fast.next != null) { 22 | slow = slow.next; // Moves one step 23 | fast = fast.next.next; // Moves two steps 24 | 25 | // If slow and fast meet, there's a cycle 26 | if (slow == fast) { 27 | return true; 28 | } 29 | } 30 | 31 | // If fast reaches the end, there's no cycle 32 | return false; 33 | } 34 | 35 | // Function to create a cycle in the linked list (for testing) 36 | public void createCycle() { 37 | Node temp = head; 38 | while (temp.next != null) { 39 | temp = temp.next; 40 | } 41 | // Creating a cycle by pointing the last node to the second node 42 | temp.next = head.next; 43 | } 44 | 45 | public static void main(String[] args) { 46 | LinkedList list = new LinkedList(); 47 | 48 | // Creating a linked list 49 | list.head = new Node(1); 50 | list.head.next = new Node(2); 51 | list.head.next.next = new Node(3); 52 | list.head.next.next.next = new Node(4); 53 | list.head.next.next.next.next = new Node(5); 54 | 55 | // Uncomment the next line to create a cycle in the list 56 | // list.createCycle(); 57 | 58 | // Check if the linked list has a cycle 59 | if (list.hasCycle()) { 60 | System.out.println("Cycle detected in the linked list."); 61 | } else { 62 | System.out.println("No cycle in the linked list."); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Data Structures/BFS for graph.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class GfG { 4 | 5 | // BFS from given source s 6 | static void bfs(List> adj, int s) { 7 | 8 | // Create a queue for BFS 9 | Queue q = new LinkedList<>(); 10 | 11 | // Initially mark all the vertices as not visited 12 | // When we push a vertex into the q, we mark it as 13 | // visited 14 | boolean[] visited = new boolean[adj.size()]; 15 | 16 | // Mark the source node as visited and enqueue it 17 | visited[s] = true; 18 | q.add(s); 19 | 20 | // Iterate over the queue 21 | while (!q.isEmpty()) { 22 | 23 | // Dequeue a vertex and print it 24 | int curr = q.poll(); 25 | System.out.print(curr + " "); 26 | 27 | // Get all adjacent vertices of the dequeued vertex 28 | // If an adjacent has not been visited, mark it 29 | // visited and enqueue it 30 | for (int x : adj.get(curr)) { 31 | if (!visited[x]) { 32 | visited[x] = true; 33 | q.add(x); 34 | } 35 | } 36 | } 37 | } 38 | 39 | // Function to add an edge to the graph 40 | static void addEdge(List> adj, int u, int v) { 41 | adj.get(u).add(v); 42 | adj.get(v).add(u); // Undirected graph 43 | } 44 | 45 | public static void main(String[] args) { 46 | 47 | // Number of vertices in the graph 48 | int V = 5; 49 | 50 | // Adjacency list representation of the graph 51 | List> adj = new ArrayList<>(V); 52 | for (int i = 0; i < V; i++) { 53 | adj.add(new ArrayList<>()); 54 | } 55 | 56 | // Add edges to the graph 57 | addEdge(adj, 0, 1); 58 | addEdge(adj, 0, 2); 59 | addEdge(adj, 1, 3); 60 | addEdge(adj, 1, 4); 61 | addEdge(adj, 2, 4); 62 | 63 | // Perform BFS traversal starting from vertex 0 64 | System.out.println("BFS starting from 0:"); 65 | bfs(adj, 0); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Algorithms/Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | //your code 2 | class Solution { 3 | public List spiralOrder(int[][] matrix) { 4 | ArrayList list = new ArrayList<>(); 5 | int dir = 0, top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1; 6 | 7 | while (top <= bottom && left <= right) { 8 | // Moving left to right 9 | if (dir == 0) { 10 | for (int i = left; i <= right; i++) { 11 | list.add(matrix[top][i]); 12 | } 13 | top++; // move the top boundary down 14 | dir = 1; 15 | } 16 | // Moving top to bottom 17 | else if (dir == 1) { 18 | for (int i = top; i <= bottom; i++) { 19 | list.add(matrix[i][right]); 20 | } 21 | right--; // move the right boundary left 22 | dir = 2; 23 | } 24 | // Moving right to left 25 | else if (dir == 2) { 26 | for (int i = right; i >= left; i--) { 27 | list.add(matrix[bottom][i]); 28 | } 29 | bottom--; // move the bottom boundary up 30 | dir = 3; 31 | } 32 | // Moving bottom to top 33 | else if (dir == 3) { 34 | for (int i = bottom; i >= top; i--) { 35 | list.add(matrix[i][left]); 36 | } 37 | left++; // move the left boundary right 38 | dir = 0; // reset the direction to start again 39 | } 40 | } 41 | 42 | return list; 43 | } 44 | } 45 | 46 | //driver code 47 | import java.util.List; 48 | 49 | public class Main { 50 | public static void main(String[] args) { 51 | Solution solution = new Solution(); 52 | 53 | // Example matrix input 54 | int[][] matrix = { 55 | {1, 2, 3}, 56 | {4, 5, 6}, 57 | {7, 8, 9} 58 | }; 59 | 60 | // Call the spiralOrder function and store the result 61 | List result = solution.spiralOrder(matrix); 62 | 63 | // Print the result 64 | System.out.println("Spiral Order: " + result); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Data Structures/Topological Sorting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class TopologicalSort { 4 | 5 | // Function to perform DFS and topological sorting 6 | static void 7 | topologicalSortUtil(int v, List > adj, 8 | boolean[] visited, 9 | Stack stack) 10 | { 11 | // Mark the current node as visited 12 | visited[v] = true; 13 | 14 | // Recur for all adjacent vertices 15 | for (int i : adj.get(v)) { 16 | if (!visited[i]) 17 | topologicalSortUtil(i, adj, visited, stack); 18 | } 19 | 20 | // Push current vertex to stack which stores the 21 | // result 22 | stack.push(v); 23 | } 24 | 25 | // Function to perform Topological Sort 26 | static void topologicalSort(List > adj, 27 | int V) 28 | { 29 | // Stack to store the result 30 | Stack stack = new Stack<>(); 31 | boolean[] visited = new boolean[V]; 32 | 33 | // Call the recursive helper function to store 34 | // Topological Sort starting from all vertices one 35 | // by one 36 | for (int i = 0; i < V; i++) { 37 | if (!visited[i]) 38 | topologicalSortUtil(i, adj, visited, stack); 39 | } 40 | 41 | // Print contents of stack 42 | System.out.print( 43 | "Topological sorting of the graph: "); 44 | while (!stack.empty()) { 45 | System.out.print(stack.pop() + " "); 46 | } 47 | } 48 | 49 | // Driver code 50 | public static void main(String[] args) 51 | { 52 | // Number of nodes 53 | int V = 4; 54 | 55 | // Edges 56 | List > edges = new ArrayList<>(); 57 | edges.add(Arrays.asList(0, 1)); 58 | edges.add(Arrays.asList(1, 2)); 59 | edges.add(Arrays.asList(3, 1)); 60 | edges.add(Arrays.asList(3, 2)); 61 | 62 | // Graph represented as an adjacency list 63 | List > adj = new ArrayList<>(V); 64 | for (int i = 0; i < V; i++) { 65 | adj.add(new ArrayList<>()); 66 | } 67 | 68 | for (List i : edges) { 69 | adj.get(i.get(0)).add(i.get(1)); 70 | } 71 | 72 | topologicalSort(adj, V); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Algorithms/Bellman-Ford algorithm: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Edge { 8 | public: 9 | int src, dest, weight; 10 | 11 | Edge(int s, int d, int w) : src(s), dest(d), weight(w) {} 12 | }; 13 | 14 | class Graph { 15 | public: 16 | int V; // Number of vertices 17 | vector edges; // List of edges 18 | 19 | Graph(int v) : V(v) {} 20 | 21 | void addEdge(int src, int dest, int weight) { 22 | edges.push_back(Edge(src, dest, weight)); 23 | } 24 | 25 | void bellmanFord(int src) { 26 | vector distance(V, numeric_limits::max()); 27 | distance[src] = 0; // Distance from source to itself is always 0 28 | 29 | // Relax all edges |V| - 1 times 30 | for (int i = 1; i <= V - 1; i++) { 31 | for (const auto& edge : edges) { 32 | if (distance[edge.src] != numeric_limits::max() && 33 | distance[edge.src] + edge.weight < distance[edge.dest]) { 34 | distance[edge.dest] = distance[edge.src] + edge.weight; 35 | } 36 | } 37 | } 38 | 39 | // Check for negative-weight cycles 40 | for (const auto& edge : edges) { 41 | if (distance[edge.src] != numeric_limits::max() && 42 | distance[edge.src] + edge.weight < distance[edge.dest]) { 43 | cout << "Graph contains negative weight cycle" << endl; 44 | return; 45 | } 46 | } 47 | 48 | // Print the distance array 49 | printSolution(distance); 50 | } 51 | 52 | void printSolution(const vector& distance) { 53 | cout << "Vertex Distance from Source" << endl; 54 | for (int i = 0; i < V; i++) { 55 | cout << i << "\t\t" << distance[i] << endl; 56 | } 57 | } 58 | }; 59 | 60 | int main() { 61 | int V = 5; // Number of vertices in the graph 62 | Graph g(V); 63 | 64 | // Adding edges to the graph (source, destination, weight) 65 | g.addEdge(0, 1, -1); 66 | g.addEdge(0, 2, 4); 67 | g.addEdge(1, 2, 3); 68 | g.addEdge(1, 3, 2); 69 | g.addEdge(1, 4, 2); 70 | g.addEdge(3, 1, 1); 71 | g.addEdge(3, 4, 5); 72 | g.addEdge(4, 3, -3); 73 | 74 | g.bellmanFord(0); // Calculate shortest paths from source vertex 0 75 | 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /Algorithms/RangeMinimumQuery.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class BTC { 4 | 5 | static int MAX =500; 6 | 7 | // lookup[i][j] is going to store minimum 8 | // value in arr[i..j]. Ideally lookup table 9 | // size should not be fixed and should be 10 | // determined using n Log n. It is kept 11 | // constant to keep code simple. 12 | static int [][]lookup = new int[MAX][MAX]; 13 | 14 | // Fills lookup array lookup[][] in bottom up manner. 15 | static void buildSparseTable(int arr[], int n) 16 | { 17 | 18 | // Initialize M for the intervals with length 1 19 | for (int i = 0; i < n; i++) 20 | lookup[i][0] = arr[i]; 21 | 22 | // Compute values from smaller to bigger intervals 23 | for (int j = 1; (1 << j) <= n; j++) { 24 | 25 | // Compute minimum value for all intervals with 26 | // size 2^j 27 | for (int i = 0; (i + (1 << j) - 1) < n; i++) { 28 | 29 | // For arr[2][10], we compare arr[lookup[0][7]] 30 | // and arr[lookup[3][10]] 31 | if (lookup[i][j - 1] < 32 | lookup[i + (1 << (j - 1))][j - 1]) 33 | lookup[i][j] = lookup[i][j - 1]; 34 | else 35 | lookup[i][j] = 36 | lookup[i + (1 << (j - 1))][j - 1]; 37 | } 38 | } 39 | } 40 | 41 | // Returns minimum of arr[L..R] 42 | static int query(int L, int R) 43 | { 44 | 45 | // Find highest power of 2 that is smaller 46 | // than or equal to count of elements in given 47 | // range. For [2, 10], j = 3 48 | int j = (int)Math.log(R - L + 1); 49 | 50 | // Compute minimum of last 2^j elements with first 51 | // 2^j elements in range. 52 | // For [2, 10], we compare arr[lookup[0][3]] and 53 | // arr[lookup[3][3]], 54 | if (lookup[L][j] <= lookup[R - (1 << j) + 1][j]) 55 | return lookup[L][j]; 56 | 57 | else 58 | return lookup[R - (1 << j) + 1][j]; 59 | } 60 | 61 | // Driver program 62 | public static void main (String[] args) 63 | { 64 | int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; 65 | int n = a.length; 66 | 67 | buildSparseTable(a, n); 68 | 69 | System.out.println(query(0, 4)); 70 | System.out.println(query(4, 7)); 71 | System.out.println(query(7, 8)); 72 | 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Data Structures/Bellman-Ford algorithm in C++: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // For INT_MAX 4 | 5 | using namespace std; 6 | 7 | // Structure to represent a directed edge in the graph 8 | struct Edge { 9 | int src, dest, weight; // Source, destination, and weight of the edge 10 | }; 11 | 12 | // Function to implement the Bellman-Ford algorithm 13 | void bellmanFord(int vertices, int edgesCount, vector &edges, int source) { 14 | // Step 1: Initialize distances from the source to all vertices as infinite 15 | vector distance(vertices, INT_MAX); 16 | distance[source] = 0; // Distance from source to itself is always 0 17 | 18 | // Step 2: Relax all edges (vertices - 1) times 19 | for (int i = 1; i <= vertices - 1; i++) { 20 | for (int j = 0; j < edgesCount; j++) { 21 | int u = edges[j].src; // Source vertex of edge 22 | int v = edges[j].dest; // Destination vertex of edge 23 | int weight = edges[j].weight; // Weight of the edge 24 | 25 | // If the distance to the source vertex is not infinite 26 | // and we can improve the distance to the destination vertex 27 | if (distance[u] != INT_MAX && distance[u] + weight < distance[v]) { 28 | distance[v] = distance[u] + weight; // Update distance 29 | } 30 | } 31 | } 32 | 33 | // Step 3: Check for negative weight cycles 34 | for (int j = 0; j < edgesCount; j++) { 35 | int u = edges[j].src; 36 | int v = edges[j].dest; 37 | int weight = edges[j].weight; 38 | 39 | // If we can still reduce the distance, a negative weight cycle exists 40 | if (distance[u] != INT_MAX && distance[u] + weight < distance[v]) { 41 | cout << "Graph contains a negative weight cycle\n"; 42 | return; // Exit if a negative weight cycle is detected 43 | } 44 | } 45 | 46 | // Print the computed shortest distances 47 | cout << "Vertex\tDistance from Source\n"; 48 | for (int i = 0; i < vertices; i++) { 49 | if (distance[i] == INT_MAX) { 50 | cout << i << "\t\t" << "Infinity" << "\n"; // Unreachable vertex 51 | } else { 52 | cout << i << "\t\t" << distance[i] << "\n"; // Distance from source 53 | } 54 | } 55 | } 56 | 57 | int main() { 58 | int V = 5; // Total number of vertices in the graph 59 | int E = 8; // Total number of edges 60 | vector edges(E); // Create a vector to store edges 61 | 62 | // Adding edges to the graph 63 | edges[0] = {0, 1, -1}; // Edge from vertex 0 to 1 with weight -1 64 | edges[1] = {0, 2, 4}; // Edge from vertex 0 to 2 with weight 4 65 | edges[2] = {1, 2, 3}; // Edge from vertex 1 to 2 with weight 3 66 | edges[3] = {1, 3, 2}; // Edge from vertex 1 to 3 with weight 2 67 | edges[4] = {1, 4, 2}; // Edge from vertex 1 to 4 with weight 2 68 | edges[5] = {3, 2, 5}; // Edge from vertex 3 to 2 with weight 5 69 | edges[6] = {3, 1, 1}; // Edge from vertex 3 to 1 with weight 1 70 | edges[7] = {4, 3, -3}; // Edge from vertex 4 to 3 with weight -3 71 | 72 | int source = 0; // Setting the starting vertex 73 | bellmanFord(V, E, edges, source); // Calling the Bellman-Ford function 74 | 75 | return 0; // End of program 76 | } 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Contributing to turbo-robot 2 | 3 | Welcome to the turbo-robot! We’re glad you’re here to contribute to a growing collection of essential coding algorithms and famous code solutions. Whether you’re here for Hacktoberfest or to enhance this repository, we appreciate your efforts! 4 | 5 | Getting Started 6 | 7 | How to Contribute: 8 | 9 | 1. Fork the repository: Click the ‘Fork’ button at the top-right corner of this page to create a copy of this repository on your GitHub account. 10 | 11 | 2. Clone the repository: Use the command below to clone the forked repository to your local machine: 12 | 13 | git clone https://github.com/your-username/repository-name.git 14 | 15 | 3. Create a new branch: It’s recommended to work in a new branch for each contribution. 16 | 17 | git checkout -b feature-branch 18 | 19 | 4. Make your changes: Add new algorithms or enhance the existing ones. Be sure to write clean and well-documented code. 20 | 21 | 5. Commit your changes: Write meaningful commit messages that describe your changes clearly. 22 | 23 | git commit -m "Added [algorithm name] or Improved [functionality]" 24 | 25 | 6. Push your branch: Push your branch to your forked GitHub repository. 26 | 27 | git push origin feature-branch 28 | 29 | 7. Create a Pull Request: Navigate to this repository on GitHub, click “New Pull Request,” and follow the prompts. 30 | 31 | What We Expect: 32 | 33 | • Clarity: Make sure your code is well-documented with comments and follows consistent formatting. 34 | • Efficiency: Algorithms should be optimized for performance, with explanations if needed. 35 | • Readability: Ensure your code is easy to understand for other contributors or learners. 36 | • Tested Code: Please test your contributions before submitting a Pull Request (PR). 37 | 38 | Contribution Guidelines 39 | 40 | • Ensure that your code or improvements are not already present in the repository. Check existing contributions before adding your own. 41 | • Each algorithm should have a brief description of its purpose, time complexity, and use cases in the code comments or as a markdown file (if necessary). 42 | • No plagiarized content. Always provide credit if you use or adapt existing solutions. 43 | • Contributions should focus on common algorithms (e.g., sorting, searching, dynamic programming) or well-known problems (e.g., Fibonacci series, factorial) that can help others prepare for interviews or coding challenges. 44 | 45 | Hacktoberfest Participation 46 | 47 | This repository is part of Hacktoberfest 2024 🎉! Feel free to contribute as part of your Hacktoberfest journey by: 48 | 49 | • Adding new algorithms or improving existing ones. 50 | • Fixing bugs or optimizing the current code. 51 | • Enhancing documentation or examples. 52 | 53 | Note: Make sure your contributions follow the Hacktoberfest guidelines to be counted towards your total. Contributions will only be accepted if they meet the quality standards set by the Hacktoberfest rules. 54 | 55 | 56 | Need Help? 57 | 58 | If you have any questions, feel free to create an issue on GitHub, and we’ll be happy to assist you. 59 | 60 | Happy coding! 🚀 61 | 62 | This will guide contributors in understanding your repository’s requirements and encourage them to participate in Hacktoberfest. Let me know if you’d like any adjustments! 63 | -------------------------------------------------------------------------------- /Algorithms/N Queens Problem: -------------------------------------------------------------------------------- 1 | #include 2 | #define N 4 3 | using namespace std; 4 | 5 | // A utility function to print solution 6 | void printSolution(int board[N][N]) 7 | { 8 | for (int i = 0; i < N; i++) 9 | { 10 | for (int j = 0; j < N; j++) 11 | if (board[i][j]) 12 | cout << "Q "; 13 | else 14 | cout << ". "; 15 | cout << "\n"; 16 | } 17 | } 18 | 19 | // A utility function to check if a queen can 20 | // be placed on board[row][col]. Note that this 21 | // function is called when "col" queens are 22 | // already placed in columns from 0 to col -1. 23 | // So we need to check only left side for 24 | // attacking queens 25 | bool isSafe(int board[N][N], int row, int col) 26 | { 27 | int i, j; 28 | 29 | // Check this row on left side 30 | for (i = 0; i < col; i++) 31 | if (board[row][i]) 32 | return false; 33 | 34 | // Check upper diagonal on left side 35 | for (i = row, j = col; i >= 0 && j >= 0; i--, j--) 36 | if (board[i][j]) 37 | return false; 38 | 39 | // Check lower diagonal on left side 40 | for (i = row, j = col; j >= 0 && i < N; i++, j--) 41 | if (board[i][j]) 42 | return false; 43 | 44 | return true; 45 | } 46 | 47 | // A recursive utility function to solve N 48 | // Queen problem 49 | bool solveNQUtil(int board[N][N], int col) 50 | { 51 | // base case: If all queens are placed 52 | // then return true 53 | if (col >= N) 54 | return true; 55 | 56 | // Consider this column and try placing 57 | // this queen in all rows one by one 58 | for (int i = 0; i < N; i++) 59 | { 60 | 61 | // Check if the queen can be placed on 62 | // board[i][col] 63 | if (isSafe(board, i, col)) 64 | { 65 | 66 | // Place this queen in board[i][col] 67 | board[i][col] = 1; 68 | 69 | // recur to place rest of the queens 70 | if (solveNQUtil(board, col + 1)) 71 | return true; 72 | 73 | // If placing queen in board[i][col] 74 | // doesn't lead to a solution, then 75 | // remove queen from board[i][col] 76 | board[i][col] = 0; // BACKTRACK 77 | } 78 | } 79 | 80 | // If the queen cannot be placed in any row in 81 | // this column col then return false 82 | return false; 83 | } 84 | 85 | // This function solves the N Queen problem using 86 | // Backtracking. It mainly uses solveNQUtil() to 87 | // solve the problem. It returns false if queens 88 | // cannot be placed, otherwise, return true and 89 | // prints placement of queens in the form of 1s. 90 | // Please note that there may be more than one 91 | // solutions, this function prints one of the 92 | // feasible solutions. 93 | bool solveNQ() 94 | { 95 | int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; 96 | 97 | if (solveNQUtil(board, 0) == false) 98 | { 99 | cout << "Solution does not exist"; 100 | return false; 101 | } 102 | 103 | printSolution(board); 104 | return true; 105 | } 106 | 107 | // Driver program to test above function 108 | int main() 109 | { 110 | solveNQ(); 111 | return 0; 112 | } 113 | -------------------------------------------------------------------------------- /Algorithms/Range Minimum Query.java/code: -------------------------------------------------------------------------------- 1 | // Square Root Decomposition 2 | 3 | import java.util.Arrays; 4 | 5 | public class RangeMinimumQuerySqrtDecomposition { 6 | private int[] arr; 7 | private int[] blockMins; 8 | private int blockSize; 9 | 10 | public RangeMinimumQuerySqrtDecomposition(int[] arr) { 11 | this.arr = arr; 12 | this.blockSize = (int) Math.sqrt(arr.length); 13 | this.blockMins = new int[(arr.length + blockSize - 1) / blockSize]; 14 | preprocess(); 15 | } 16 | 17 | private void preprocess() { 18 | for (int i = 0; i < arr.length; i++) { 19 | if (i % blockSize == 0) { 20 | blockMins[i / blockSize] = arr[i]; 21 | } else { 22 | blockMins[i / blockSize] = Math.min(blockMins[i / blockSize], arr[i]); 23 | } 24 | } 25 | } 26 | 27 | public int query(int left, int right) { 28 | int min = Integer.MAX_VALUE; 29 | 30 | // Left block 31 | int startBlock = left / blockSize; 32 | int endBlock = right / blockSize; 33 | 34 | if (startBlock == endBlock) { 35 | for (int i = left; i <= right; i++) { 36 | min = Math.min(min, arr[i]); 37 | } 38 | } else { 39 | // Left block 40 | for (int i = left; i < (startBlock + 1) * blockSize && i < arr.length; i++) { 41 | min = Math.min(min, arr[i]); 42 | } 43 | // Complete blocks 44 | for (int i = startBlock + 1; i < endBlock; i++) { 45 | min = Math.min(min, blockMins[i]); 46 | } 47 | // Right block 48 | for (int i = endBlock * blockSize; i <= right && i < arr.length; i++) { 49 | min = Math.min(min, arr[i]); 50 | } 51 | } 52 | 53 | return min; 54 | } 55 | 56 | public static void main(String[] args) { 57 | int[] array = {1, 3, 2, 7, 9, 11, 2, 6}; 58 | RangeMinimumQuerySqrtDecomposition rmq = new RangeMinimumQuerySqrtDecomposition(array); 59 | 60 | System.out.println(rmq.query(1, 5)); // Output: 2 61 | System.out.println(rmq.query(0, 3)); // Output: 1 62 | System.out.println(rmq.query(3, 7)); // Output: 2 63 | } 64 | } 65 | 66 | 67 | // Sparse Table 68 | 69 | import java.util.Arrays; 70 | 71 | public class RangeMinimumQuerySparseTable { 72 | private int[][] st; 73 | private int[] log; 74 | private int n; 75 | 76 | public RangeMinimumQuerySparseTable(int[] arr) { 77 | n = arr.length; 78 | int maxLog = Integer.highestOneBit(n) * 2; // Maximum power of 2 less than or equal to n 79 | st = new int[n][maxLog]; 80 | log = new int[n + 1]; 81 | 82 | // Precompute logs 83 | for (int i = 2; i <= n; i++) { 84 | log[i] = log[i / 2] + 1; 85 | } 86 | 87 | // Build Sparse Table 88 | for (int i = 0; i < n; i++) { 89 | st[i][0] = arr[i]; 90 | } 91 | 92 | for (int j = 1; (1 << j) <= n; j++) { 93 | for (int i = 0; i + (1 << j) - 1 < n; i++) { 94 | st[i][j] = Math.min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]); 95 | } 96 | } 97 | } 98 | 99 | public int query(int left, int right) { 100 | int j = log[right - left + 1]; 101 | return Math.min(st[left][j], st[right - (1 << j) + 1][j]); 102 | } 103 | 104 | public static void main(String[] args) { 105 | int[] array = {1, 3, 2, 7, 9, 11, 2, 6}; 106 | RangeMinimumQuerySparseTable rmq = new RangeMinimumQuerySparseTable(array); 107 | 108 | System.out.println(rmq.query(1, 5)); // Output: 2 109 | System.out.println(rmq.query(0, 3)); // Output: 1 110 | System.out.println(rmq.query(3, 7)); // Output: 2 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /Data Structures/singlelinkedlist.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | int data; 3 | Node next; 4 | 5 | Node(int data1, Node next1) { 6 | this.data = data1; 7 | this.next = next1; 8 | } 9 | Node(int data1) { 10 | this.data = data1; 11 | this.next = null; 12 | } 13 | } 14 | 15 | // array/list to linkedlist -- CREATING LINKEDLIST -- a2ll() 16 | // print linkedlist -- TRAVERSAL -- traversalandlength() 17 | // LENGTH of linkedlist -- traversalandlength() 18 | // SEARCH an element in linkedlist -- search() 19 | 20 | public class linkedlist { 21 | public static Node a2ll(int[] arr){ 22 | Node head = new Node(arr[0]); 23 | Node mover=head; 24 | for(int i=1;i length of linked list)"); 149 | return head; 150 | } 151 | else if(head==null){ 152 | if(k==1) return insertathead(head, val); 153 | else{ System.out.println("INVALID INSERTION"); return head; } 154 | } 155 | else if(k==1) return insertathead(head, val); 156 | else{ 157 | Node temp=head; 158 | int c=0; 159 | while(temp!=null){ 160 | c++; 161 | if(c==k-1){ 162 | Node a=new Node(val); 163 | a.next=temp.next; 164 | temp.next=a; 165 | break; 166 | } 167 | temp=temp.next; 168 | } 169 | return head; 170 | 171 | } 172 | } 173 | 174 | public static Node reverse(Node head) { 175 | Node temp=head; 176 | Node prev=null; 177 | while(temp!=null){ 178 | Node front =temp.next; 179 | temp.next = prev; 180 | prev = temp; 181 | temp = front; 182 | } 183 | return prev; 184 | } 185 | 186 | // Tortoise and Hare Algorithm or Floyd’s Cycle Approach 187 | public static Node middle(Node head){ 188 | Node slow=head; 189 | Node fast=head; 190 | while(fast!=null && fast.next!=null){ 191 | slow=slow.next; 192 | fast=fast.next.next; 193 | } 194 | return slow; 195 | } 196 | 197 | public static Node checkloop(Node head){ 198 | Node slow=head; 199 | Node fast=head; 200 | while(fast!=null && fast.next!=null){ 201 | slow=slow.next; 202 | fast=fast.next.next; 203 | 204 | if(slow==fast){ 205 | return slow; 206 | } 207 | } 208 | return null; 209 | } 210 | 211 | public static int loopatindex(Node head){ 212 | Node temp = head; 213 | int pos = 0; 214 | Node ans=checkloop(head); 215 | if(ans == null) return pos; 216 | while(temp!=ans) { 217 | ++pos; 218 | temp = temp.next; 219 | } 220 | return pos; 221 | } 222 | 223 | 224 | 225 | public static void main(String[] args) { 226 | int[] arr = {2, 5, 8, 7, 0, 11, 69}; 227 | 228 | Node head=a2ll(arr); 229 | traversal(head); 230 | 231 | System.out.println("length of LINkEDLIST is: " +length(head)); 232 | 233 | System.out.println(search(head,8)); 234 | System.out.println(); 235 | 236 | // DELETE OPERATIONS 237 | System.out.println("_______DELETE OPERATIONS_______"); 238 | System.out.print("deleting head: "); 239 | head=deletehead(head); 240 | traversal(head); 241 | 242 | System.out.print("deleting tail: "); 243 | head=deletetail(head); 244 | traversal(head); 245 | 246 | 247 | System.out.print("deleting 2nd elmt: "); 248 | head=deletenodebyk(head,2); 249 | traversal(head); 250 | 251 | System.out.print("deleting elmt '0' :"); 252 | head=deletenodebyelmt(head,0); 253 | traversal(head); 254 | System.out.println(); 255 | 256 | 257 | // INSERT OPERATIONS 258 | System.out.println("_______INSERT OPERATIONS_______"); 259 | System.out.print("inserting at head: "); 260 | head=insertathead(head,69); 261 | traversal(head); 262 | 263 | System.out.print("inserting at tail: "); 264 | head=insertattail(head,100); 265 | traversal(head); 266 | 267 | System.out.print("inserting at 4th position: "); 268 | head=insertatk(head,4,82); 269 | traversal(head); 270 | 271 | System.out.println(); 272 | System.out.print("REVERSING LL: "); 273 | head=reverse(head); 274 | traversal(head); 275 | 276 | 277 | // get middle node 278 | System.out.println(); 279 | System.out.println("MIDDLE NODE of LL is: "+middle(head).data); 280 | 281 | // detecting loop 282 | System.out.println(); 283 | if(checkloop(head)==null) System.out.println("NO CYCLE/LOOP"); 284 | else System.out.println("HAS CYCLE/LOOP"); 285 | 286 | //loop at index 287 | System.out.println(); 288 | int in=loopatindex(head); 289 | if(in==0) System.out.println("no cycle in LL"); 290 | else System.out.println(in); 291 | 292 | } 293 | } 294 | --------------------------------------------------------------------------------