├── Arrays ├── 217. Contains Duplicate.md ├── 3-sum-closest.java ├── 3sum.java ├── 4sum.java ├── 53. Maximum Subarray.md ├── Fibonacci.java ├── Find-first-last-pos-in-sorted-array.java ├── Insertion_Sort_jayant.cpp ├── Jump-game-2.java ├── Longest_Substring_Without_Repeating_Characters.md ├── Max-subArray.java ├── Median-of-2-sorted-arrays.java ├── Merge-sorted-array.java ├── Next-permutations.java ├── Permutation.java ├── Problem Statement.txt ├── Problem_1266.java ├── Problem_165.txt ├── Problem_835.txt ├── Remove-duplicate-from-sorted-array.java ├── Reverse array in groups.CPP ├── Rotate-image.java ├── Search an element in sorted and rotated array.CPP ├── Search-2d-matrix.java ├── Solution_165.java ├── Solution_835.java ├── String_to_Integer_(atoi).md ├── Subarray_with_given_sum.java ├── Trapping-rain-water.java ├── Two-sum.java ├── Valid-sudoku.java ├── count-negative-numbers-in-a-sorted-matrix.java ├── remove-elements.java ├── right-arrayrotation.java ├── search-insert-position.java ├── search-insert.java ├── secondLargestElement.java ├── solution.java └── sudoku-solver.java ├── Binary Search Tree ├── BinarySearchTree$Node.class ├── BinarySearchTree.class └── BinarySearchTree.java ├── C++ ├── Factorial.cpp ├── lcs.cpp ├── maximumexpression.cpp └── warshall.cpp ├── C └── bubblesort.c ├── CONTRIBUTING.md ├── Dsa ├── Binary_Search.java ├── C++ │ └── median_row_matrix.cpp ├── Check for BST . CPP └── noOfNodes.java ├── LICENSE ├── Permutation.java ├── Permutations2.java ├── Plus-one.java ├── README.md ├── basic ├── RedOrGreen.java └── lastIndex ├── dsa ├── InsertionSort.java ├── Kruskal_algo.cpp ├── Linearsearch.java ├── Selection_Sort.cpp ├── Selection_Sort.java ├── SetMismatch.java ├── doubly_linkedlist.cpp ├── mergesort.java ├── reverse_string.java ├── shortest_common_supersequence.java └── tictactoe.java ├── easy ├── countBuildings └── sumElement ├── information_DSA.md └── java └── Search-in-rotated-sorted-array.java /Arrays/217. Contains Duplicate.md: -------------------------------------------------------------------------------- 1 | ## 217. Contains Duplicate 2 | 3 | --- 4 | **Easy** 5 | 6 | Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 7 | 8 | 9 | 10 | Example 1: 11 | Input: nums = [1,2,3,1] 12 | Output: true 13 | 14 | Example 2: 15 | Input: nums = [1,2,3,4] 16 | Output: false 17 | 18 | Example 3: 19 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 20 | Output: true 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 105 25 | -109 <= nums[i] <= 109 26 | 27 | ## Solution 28 | 29 | --- 30 | 31 | ``` 32 | import java.util.Arrays; 33 | class Solution { 34 | public boolean containsDuplicate(int[] nums) { 35 | Arrays.sort(nums); 36 | int c = 1; 37 | for(int i = 1; i ht = new HashSet<>(); 59 | for(int i : nums){ 60 | if(!ht.add(i)){ 61 | return true; 62 | } 63 | } 64 | 65 | return false; 66 | 67 | } 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /Arrays/3-sum-closest.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int threeSumClosest(int[] nums, int target) { 3 | Arrays.sort(nums); 4 | 5 | 6 | int minDiff = Integer.MAX_VALUE; 7 | int res = 0; 8 | int n = nums.length; 9 | for (int i=0;i target) k--; 31 | // if sum is lesser than target then j++ mean[move to right side] : -->> 32 | else if (sum < target) j++; 33 | 34 | 35 | 36 | } 37 | 38 | } 39 | return res; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Arrays/3sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> threeSum(int[] nums) { 3 | Arrays.sort(nums); 4 | int left_pointer = 0; 5 | int right_pointer = 0; 6 | int sub_sum = 0; 7 | 8 | List> result = new ArrayList>(); 9 | for(int i = 0; i < nums.length; i++) { 10 | if( i > 0 && nums[i] == nums[i - 1]) { 11 | continue; 12 | } 13 | 14 | left_pointer = i + 1; 15 | right_pointer = nums.length - 1; 16 | sub_sum = -nums[i]; 17 | while(left_pointer < right_pointer) { 18 | if((left_pointer > i + 1 && nums[left_pointer] == nums[left_pointer - 1]) && (right_pointer < nums.length - 1 && nums[right_pointer] == nums[right_pointer + 1])){ 19 | left_pointer++; 20 | right_pointer--; 21 | continue; 22 | } 23 | 24 | if(nums[left_pointer] + nums[right_pointer] == sub_sum) { 25 | List triplet = Arrays.asList(new Integer[]{-sub_sum, nums[left_pointer], nums[right_pointer]}); 26 | result.add(triplet); 27 | left_pointer++; 28 | right_pointer--; 29 | } 30 | else if(nums[left_pointer] + nums[right_pointer] < sub_sum) { 31 | left_pointer++; 32 | }else { 33 | right_pointer--; 34 | } 35 | } 36 | } 37 | return result; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Arrays/4sum.java: -------------------------------------------------------------------------------- 1 | public List> fourSum(int[] nums, int target) { 2 | Arrays.sort(nums); 3 | List> res = new ArrayList<>(); 4 | for (int i = 0; i < nums.length; i++) { 5 | for (int j = i + 1; j < nums.length; j++) { 6 | int left = j + 1; 7 | int right = nums.length - 1; 8 | while (left < right) { 9 | long sum = (long) nums[i] + (long) nums[j] + (long) nums[left] + (long) nums[right]; 10 | if (sum > target) { 11 | right--; 12 | } else if (sum < target) { 13 | left++; 14 | } else { 15 | res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); 16 | int l = nums[left]; 17 | while (l == nums[left] && left < right) { 18 | left++; 19 | } 20 | } 21 | } 22 | } 23 | } 24 | Set> set = new HashSet<>(); 25 | for (List l : res) { 26 | Collections.sort(l); 27 | set.add(l); 28 | } 29 | return new ArrayList<>(set); 30 | } 31 | ksum: 32 | 33 | public List> fourSum(int[] nums, int target) { 34 | Arrays.sort(nums); 35 | return kSum(0, 4, nums, target); 36 | } 37 | // note: long type for target to prevent integer overflow 38 | private List> kSum(int start, int k, int[] nums, long target) { 39 | List> res = new ArrayList<>(); 40 | /** 41 | * skip searching if: 42 | * 1. there are less than k elements in nums 43 | * 2. first_element * k already bigger than target 44 | * 3. last_element * k already smaller than target 45 | */ 46 | if (start + k > nums.length || nums[start] > target / k || nums[nums.length - 1] < target / k) { 47 | return res; 48 | } 49 | if (k == 2) { 50 | return twoSum(start, nums, target); 51 | } 52 | for (int i = start; i < nums.length; i++) { 53 | // skip duplicates 54 | if (i > start && nums[i - 1] == nums[i]) { 55 | continue; 56 | } 57 | for (List integers : kSum(i + 1, k - 1, nums, target - (long) nums[i])) { 58 | List list = new ArrayList<>(integers); 59 | list.add(nums[i]); 60 | res.add(list); 61 | } 62 | } 63 | return res; 64 | } 65 | 66 | private List> twoSum(int start, int[] nums, long target) { 67 | List> result = new ArrayList<>(); 68 | int left = start; 69 | int right = nums.length - 1; 70 | while (left < right) { 71 | long sum = (long) nums[left] + (long) nums[right]; 72 | if (sum > target) { 73 | right--; 74 | } else if (sum < target) { 75 | left++; 76 | } else { 77 | result.add(Arrays.asList(nums[left], nums[right])); 78 | int l = nums[left]; 79 | while (left < right && l == nums[left]) { 80 | left++; 81 | } 82 | } 83 | } 84 | return result; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Arrays/53. Maximum Subarray.md: -------------------------------------------------------------------------------- 1 | ## 53. Maximum Subarray 2 | 3 | --- 4 | 5 | **Medium** 6 | 7 | 8 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 9 | 10 | A subarray is a contiguous part of an array. 11 | 12 | 13 | 14 | Example 1: 15 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 16 | Output: 6 17 | Explanation: [4,-1,2,1] has the largest sum = 6. 18 | 19 | 20 | Example 2: 21 | Input: nums = [1] 22 | Output: 1 23 | 24 | Example 3: 25 | Input: nums = [5,4,-1,7,8] 26 | Output: 23 27 | 28 | Constraints: 29 | 30 | 1 <= nums.length <= 105 31 | -104 <= nums[i] <= 104 32 | 33 | 34 | Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 35 | 36 | ## Solution 37 | 38 | --- 39 | 40 | ``` 41 | class Solution { 42 | public int maxSubArray(int[] nums) { 43 | int maxsum = nums[0]; 44 | int cursum = 0; 45 | for(int i : nums){ 46 | if(cursum<0){ 47 | cursum = 0; 48 | } 49 | cursum = cursum+i; 50 | maxsum = Math.max(maxsum,cursum); 51 | 52 | } 53 | return maxsum; 54 | } 55 | } 56 | ``` 57 | Runtime: 2 ms, faster than 74.56% of Java online submissions for Maximum Subarray. 58 | Memory Usage: 73.5 MB, less than 61.61% of Java online submissions for Maximum Subarray. -------------------------------------------------------------------------------- /Arrays/Fibonacci.java: -------------------------------------------------------------------------------- 1 | class Main { 2 | public static void main(String[] args) { 3 | 4 | int n = 10, firstTerm = 0, secondTerm = 1; 5 | System.out.println("Fibonacci Series till " + n + " terms:"); 6 | 7 | for (int i = 1; i <= n; ++i) { 8 | System.out.print(firstTerm + ", "); 9 | 10 | // compute the next term 11 | int nextTerm = firstTerm + secondTerm; 12 | firstTerm = secondTerm; 13 | secondTerm = nextTerm; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Arrays/Find-first-last-pos-in-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int start=0,end=nums.length-1,fi=-1; 4 | while(start<=end){ 5 | int mid=start+(end-start)/2; 6 | if(nums[mid]==target){ 7 | fi=mid; 8 | end=mid-1; 9 | } 10 | else if(nums[mid]>target){ 11 | end=mid-1; 12 | } 13 | else{ 14 | start=mid+1; 15 | } 16 | } 17 | start=0;end=nums.length-1; 18 | int ei=-1; 19 | while(start<=end){ 20 | int mid=start+(end-start)/2; 21 | if(nums[mid]==target){ 22 | ei=mid; 23 | start=mid+1; 24 | } 25 | else if(nums[mid]>target){ 26 | end=mid-1; 27 | } 28 | else{ 29 | start=mid+1; 30 | } 31 | } 32 | return new int[]{fi,ei}; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Arrays/Insertion_Sort_jayant.cpp: -------------------------------------------------------------------------------- 1 | //inserting a element into a sorted array 2 | 3 | #include 4 | using namespace std; 5 | 6 | void InsertionSorting(int arr[], int size){ 7 | for(int i = 0; i < size; i++){ 8 | int j = i; 9 | while(j > 0 && arr[j] < arr[j-1]){ 10 | swap(arr[j], arr[j-1]); 11 | j--; 12 | } 13 | } 14 | for(int i = 0; i < size; i++){ 15 | cout<>size; 22 | 23 | int arr[size]; 24 | 25 | for(int i=0; i>arr[i]; 27 | } 28 | InsertionSorting(arr,size); 29 | return 0; 30 | } 31 | 32 | //It is efficient when number of element are small 33 | //Stable sorting algorithm 34 | -------------------------------------------------------------------------------- /Arrays/Jump-game-2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int jump(int[] nums) { 3 | int jumps = 0, currEnd = 0, currFarthest = 0; 4 | for(int i = 0; i < nums.length - 1; i ++) { 5 | currFarthest = Math.max(currFarthest, i + nums[i]); 6 | if(i == currEnd) { 7 | currEnd = currFarthest; 8 | jumps ++; 9 | } 10 | } 11 | return jumps; 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Arrays/Longest_Substring_Without_Repeating_Characters.md: -------------------------------------------------------------------------------- 1 | # Longest Substring Without Repeating Characters 2 | 3 | Given a string s, find the length of the longest substring without repeating characters. 4 | 5 | 6 | ``` 7 | Example 1: 8 | 9 | Input: s = "abcabcbb" 10 | Output: 3 11 | Explanation: The answer is "abc", with the length of 3. 12 | 13 | ``` 14 | ``` 15 | Example 2: 16 | 17 | Input: s = "bbbbb" 18 | Output: 1 19 | Explanation: The answer is "b", with the length of 1. 20 | ``` 21 | ``` 22 | Example 3: 23 | 24 | Input: s = "pwwkew" 25 | Output: 3 26 | Explanation: The answer is "wke", with the length of 3. 27 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 28 | ``` 29 | 30 | ``` 31 | 32 | Constraints: 33 | 34 | 0 <= s.length <= 5 * 104 35 | s consists of English letters, digits, symbols and spaces. 36 | ``` 37 | 38 | --- 39 | 40 | # Solution 41 | An optimized approach. We start traversing the string from left to right and maintain track of: 42 | 43 | - the current substring with non-repeating characters with the help of a start and end index 44 | - the longest non-repeating substring output 45 | - a lookup table of already visited characters 46 | ``` 47 | class Solution { 48 | public int lengthOfLongestSubstring(String s) { 49 | HashMapmymap = new HashMap<>(); 50 | int left =0,right = 0; 51 | int n = s.length(); 52 | int len = 0; 53 | while(right maxsum) 8 | maxsum=currsum; 9 | if(currsum<0) 10 | currsum=0; 11 | } 12 | return maxsum; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Arrays/Median-of-2-sorted-arrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 | int ans; 4 | double med; 5 | int[] nums = new int[(nums1.length + nums2.length)]; 6 | for(int i=0; i< nums1.length; i++){ 7 | nums[i] = nums1[i]; 8 | } 9 | for(int i=nums1.length; i<(nums1.length + nums2.length); i++){ 10 | nums[i] = nums2[i-nums1.length]; 11 | } 12 | Arrays.sort(nums); 13 | ans = (nums1.length + nums2.length)/2; 14 | if((nums1.length + nums2.length)%2==0){ 15 | med = (nums[ans-1] + nums[ans])/2.0; 16 | } 17 | else{ 18 | med = nums[ans]; 19 | } 20 | return med; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Arrays/Merge-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | for(int i=m;i= 1; x--){ 9 | if(nums[x]>nums[x-1]){ 10 | pivot = x-1; 11 | break; 12 | } 13 | } 14 | //Find the next greatest number from the pivot to the end of the array 15 | int nextGreatest = Integer.MAX_VALUE; 16 | int nextGreatestPos = 0; 17 | for(int x = pivot+1; x < nums.length;x++){ 18 | if(nums[x]<=nextGreatest && nums[x]>nums[pivot]){ 19 | nextGreatest = nums[x]; 20 | nextGreatestPos= x; 21 | 22 | } 23 | } 24 | if(nextGreatest == Integer.MAX_VALUE){ 25 | nextGreatest = nums[0]; 26 | } 27 | 28 | int holder = nums[pivot]; 29 | //Handles edge case where no increasing sequence from the end is found 30 | if(pivot == nums.length-1){ 31 | int temp = nums[0]; 32 | nums[0] = nums[nums.length-1]; 33 | nums[nums.length-1] = temp; 34 | reverseSublist(nums,1,nums.length-2); 35 | return; 36 | 37 | } 38 | 39 | nums[pivot] = nextGreatest; 40 | nums[nextGreatestPos] = holder; 41 | 42 | reverseSublist(nums,pivot+1,nums.length-1); 43 | 44 | 45 | 46 | } 47 | /** 48 | Reverses a sublist of an array from a particular given range. 49 | @param arr - array 50 | @param start - beginning index of the sublist 51 | @param finish - ending index of the sublist 52 | */ 53 | public static void reverseSublist(int[] arr, int start, int finish){ 54 | while(start> permute(int[] nums) { 3 | //initalizing one data structure which store the value duricng recursive call in it 4 | List ds = new ArrayList<>(); 5 | 6 | // initalizing array of array which print output the permutation of array 7 | List> ans = new ArrayList<>(); 8 | 9 | // intializing another array of length final array nums of type boolean which mark the value true when we visited that particular index during recursive call because we don't want duplicate value in array (* not considering duplicate value which already present in intial array) 10 | boolean[] freq = new boolean[nums.length]; 11 | // calling the function 12 | permutation(ds,ans,nums,freq); 13 | return ans; 14 | 15 | } 16 | 17 | public void permutation(Listds, List> ans, int[] nums, boolean[] freq) 18 | { 19 | 20 | this is base condition whe size of declared data structure became equal to intial array then that time ds contain one cycle of permutation and we add it to ans. 21 | if(ds.size() == nums.length) 22 | { 23 | ans.add(new ArrayList<>(ds)); 24 | return; 25 | } 26 | // running loop till n and marking visited not visited during recursive call 27 | for(int i = 0; i < nums.length; i++) 28 | { 29 | if(!freq[i]) 30 | { 31 | // if not visited then mark true 32 | freq[i] = true; 33 | //add it to ds 34 | ds.add(nums[i]); 35 | //call the function again because it recursion calling back to back 36 | permutation(ds,ans,nums,freq); 37 | // when recursin reaches equal to size of intial array then remove tha last element of ds and unmarked the visited array 38 | ds.remove(ds.size()-1); 39 | freq[i] = false; 40 | } 41 | } 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Arrays/Problem Statement.txt: -------------------------------------------------------------------------------- 1 | Problem 1252 Leetcode: Cells with Odd Values in a Matrix 2 | 3 | Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. 4 | For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1. 5 | Return the number of cells with odd values in the matrix after applying the increment to all indices. 6 | -------------------------------------------------------------------------------- /Arrays/Problem_1266.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | 1266. Minimum Time Visiting All Points 4 | 5 | 6 | On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. 7 | 8 | You can move according to the next rules: 9 | 10 | In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). 11 | You have to visit the points in the same order as they appear in the array. 12 | 13 | */ 14 | 15 | import java.lang.Math; 16 | 17 | class Solution { 18 | public int minTimeToVisitAllPoints(int[][] points) { 19 | int n = points.length; 20 | if(n == 1) 21 | return 0; 22 | int dist = 0; 23 | for(int i = 0; i < n-1; i++) { 24 | int xDiff = Math.abs(points[i][0]-points[i+1][0]); 25 | int yDiff = Math.abs(points[i][1]-points[i+1][1]); 26 | dist += Math.max(xDiff, yDiff); 27 | } 28 | return dist; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Arrays/Problem_165.txt: -------------------------------------------------------------------------------- 1 | 165. Compare Version Numbers 2 | 3 | Given two version numbers, version1 and version2, compare them. 4 | 5 | Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. 6 | Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, 7 | the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.To compare version numbers, 8 | compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. 9 | This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. 10 | For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. 11 | 12 | Return the following: 13 | 14 | If version1 < version2, return -1. 15 | If version1 > version2, return 1. 16 | Otherwise, return 0. 17 | -------------------------------------------------------------------------------- /Arrays/Problem_835.txt: -------------------------------------------------------------------------------- 1 | 835. Image Overlap 2 | 3 | You are given two images img1 and img2 both of size n x n, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) 4 | 5 | We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images. 6 | 7 | (Note also that a translation does not include any kind of rotation.) 8 | 9 | What is the largest possible overlap? 10 | 11 | -------------------------------------------------------------------------------- /Arrays/Remove-duplicate-from-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums.length == 0) return 0; 4 | int i = 0; 5 | for (int j = 1; j < nums.length; j++) { 6 | if (nums[j] != nums[i]) { 7 | i++; 8 | nums[i] = nums[j]; 9 | } 10 | } 11 | return i + 1; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Arrays/Reverse array in groups.CPP: -------------------------------------------------------------------------------- 1 | reverseInGroups(ArrayList arr, int n, int k) { 2 | // code here 3 | for(int i=0;i list=new ArrayList<>(); 4 | int index=0; 5 | for(int i=0;i 5 | using namespace std; 6 | 7 | // Standard Binary Search function 8 | int binarySearch(int arr[], int low, int high, int key) 9 | { 10 | if (high < low) 11 | return -1; 12 | 13 | int mid = (low + high) / 2; 14 | if (key == arr[mid]) 15 | return mid; 16 | 17 | if (key > arr[mid]) 18 | return binarySearch(arr, (mid + 1), high, key); 19 | 20 | return binarySearch(arr, low, (mid - 1), key); 21 | } 22 | 23 | // Function to get pivot. For array 3, 4, 5, 6, 1, 2 24 | // it returns 3 (index of 6) 25 | int findPivot(int arr[], int low, int high) 26 | { 27 | // Base cases 28 | if (high < low) 29 | return -1; 30 | if (high == low) 31 | return low; 32 | 33 | // low + (high - low)/2; 34 | int mid = (low + high) / 2; 35 | if (mid < high && arr[mid] > arr[mid + 1]) 36 | return mid; 37 | 38 | if (mid > low && arr[mid] < arr[mid - 1]) 39 | return (mid - 1); 40 | 41 | if (arr[low] >= arr[mid]) 42 | return findPivot(arr, low, mid - 1); 43 | 44 | return findPivot(arr, mid + 1, high); 45 | } 46 | 47 | // Searches an element key in a pivoted 48 | // sorted array arr[] of size n 49 | int pivotedBinarySearch(int arr[], int n, int key) 50 | { 51 | int pivot = findPivot(arr, 0, n - 1); 52 | 53 | // If we didn't find a pivot, 54 | // then array is not rotated at all 55 | if (pivot == -1) 56 | return binarySearch(arr, 0, n - 1, key); 57 | 58 | // If we found a pivot, then first compare with pivot 59 | // and then search in two subarrays around pivot 60 | if (arr[pivot] == key) 61 | return pivot; 62 | 63 | if (arr[0] <= key) 64 | return binarySearch(arr, 0, pivot - 1, key); 65 | 66 | return binarySearch(arr, pivot + 1, n - 1, key); 67 | } 68 | 69 | // Driver program to check above functions 70 | int main() 71 | { 72 | // Let us search 3 in below array 73 | int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; 74 | int n = sizeof(arr1) / sizeof(arr1[0]); 75 | int key = 3; 76 | 77 | // Function calling 78 | cout << "Index of the element is : " 79 | << pivotedBinarySearch(arr1, n, key); 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /Arrays/Search-2d-matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | int row=0; 4 | for(int i=0; i b) 21 | return 1; 22 | } 23 | 24 | // Version 2 is big 25 | if(isVersion1Small) { 26 | int j = i; 27 | while(j < len2) { 28 | if(Integer.valueOf(arr2[j++]) > 0) 29 | return -1; 30 | } 31 | } 32 | 33 | // Version 1 is big 34 | if(!isVersion1Small) { 35 | int j = i; 36 | while(j < len1) { 37 | if(Integer.valueOf(arr1[j++]) > 0) 38 | return 1; 39 | } 40 | 41 | } 42 | 43 | return 0; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Arrays/Solution_835.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | protected int shiftAndCount(int xShift, int yShift, int[][] M, int[][] R) { 4 | int count = 0; 5 | int rRow = 0; 6 | // count the cells of ones in the overlapping zone. 7 | for (int mRow = yShift; mRow < M.length; ++mRow) { 8 | int rCol = 0; 9 | for (int mCol = xShift; mCol < M.length; ++mCol) { 10 | if (M[mRow][mCol] == 1 && M[mRow][mCol] == R[rRow][rCol]) 11 | count += 1; 12 | rCol += 1; 13 | } 14 | rRow += 1; 15 | } 16 | return count; 17 | } 18 | 19 | public int largestOverlap(int[][] A, int[][] B) { 20 | int maxOverlaps = 0; 21 | 22 | for (int yShift = 0; yShift < A.length; ++yShift) 23 | for (int xShift = 0; xShift < A.length; ++xShift) { 24 | // move one of the matrice up and left and vice versa. 25 | // (equivalent to move the other matrix down and right) 26 | maxOverlaps = Math.max(maxOverlaps, shiftAndCount(xShift, yShift, A, B)); 27 | maxOverlaps = Math.max(maxOverlaps, shiftAndCount(xShift, yShift, B, A)); 28 | } 29 | 30 | return maxOverlaps; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Arrays/String_to_Integer_(atoi).md: -------------------------------------------------------------------------------- 1 | # String to Integer (atoi) 2 | --- 3 | Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). 4 | 5 | The algorithm for myAtoi(string s) is as follows: 6 | 7 | Read in and ignore any leading whitespace. 8 | Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 9 | Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 10 | Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). 11 | If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. 12 | Return the integer as the final result. 13 | Note: 14 | 15 | Only the space character ' ' is considered a whitespace character. 16 | Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. 17 | 18 | ``` 19 | Example 1: 20 | 21 | Input: s = "42" 22 | Output: 42 23 | Explanation: The underlined characters are what is read in, the caret is the current reader position. 24 | Step 1: "42" (no characters read because there is no leading whitespace) 25 | ^ 26 | Step 2: "42" (no characters read because there is neither a '-' nor '+') 27 | ^ 28 | Step 3: "42" ("42" is read in) 29 | ^ 30 | The parsed integer is 42. 31 | Since 42 is in the range [-231, 231 - 1], the final result is 42. 32 | ``` 33 | ``` 34 | Example 2: 35 | 36 | Input: s = " -42" 37 | Output: -42 38 | Explanation: 39 | Step 1: " -42" (leading whitespace is read and ignored) 40 | ^ 41 | Step 2: " -42" ('-' is read, so the result should be negative) 42 | ^ 43 | Step 3: " -42" ("42" is read in) 44 | ^ 45 | The parsed integer is -42. 46 | Since -42 is in the range [-231, 231 - 1], the final result is -42. 47 | ``` 48 | ``` 49 | Example 3: 50 | 51 | Input: s = "4193 with words" 52 | Output: 4193 53 | Explanation: 54 | Step 1: "4193 with words" (no characters read because there is no leading whitespace) 55 | ^ 56 | Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') 57 | ^ 58 | Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) 59 | ^ 60 | The parsed integer is 4193. 61 | Since 4193 is in the range [-231, 231 - 1], the final result is 4193. 62 | ``` 63 | 64 | ``` 65 | Constraints: 66 | 67 | 0 <= s.length <= 200 68 | s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. 69 | ``` 70 | 71 | # Solution 72 | ``` 73 | class Solution { 74 | public int myAtoi(String s) { 75 | int sign = 1; 76 | int result = 0; 77 | int index = 0; 78 | int n = s.length(); 79 | while(indexInteger.MAX_VALUE/10)||(result==Integer.MAX_VALUE/10 && digit > Integer.MAX_VALUE%10)){ 95 | return sign ==1?Integer.MAX_VALUE:Integer.MIN_VALUE; 96 | } 97 | 98 | 99 | result = 10*result+digit; 100 | index++; 101 | 102 | } 103 | return sign * result; 104 | } 105 | } 106 | ``` 107 | 108 | # Algorithm 109 | ``` 110 | 1. Initialize two variables: 111 | - sign (to store the sign of the final result) as 1. 112 | - result (to store the 32-bit integer result) as 0. 113 | 114 | 2. Skip all leading whitespaces in the input string. 115 | 116 | 3. Check if the current character is a '+' or '-' sign: 117 | 118 | - If there is no symbol or the current character is '+', keep sign equal to 1. 119 | - Otherwise, if the current character is '-', change sign to -1. 120 | 121 | 4. Iterate over the characters in the string as long as the current character represents a digit or until we reach the end of the input string. 122 | 123 | - Before appending the currently selected digit, check if the 32-bit signed integer range is violated. If it is violated, then return INT_MAX or INT_MIN as appropriate. 124 | 125 | - Otherwise, if appending the digit does not result in overflow/underflow, append the current digit to the result. 126 | Return the final result with its respective sign, sign * result. 127 | ``` -------------------------------------------------------------------------------- /Arrays/Subarray_with_given_sum.java: -------------------------------------------------------------------------------- 1 | public class SubarraySum { 2 | 3 | int subArraySum(int arr[], int n, int sum) 4 | { 5 | int currentSum = arr[0], start = 0, i; 6 | 7 | for (i = 1; i <= n; i++) { 8 | 9 | while (currentSum > sum && start < i - 1) { 10 | currentSum = currentSum - arr[start]; 11 | start++; 12 | } 13 | 14 | if (currentSum == sum) { 15 | int p = i - 1; 16 | System.out.println( 17 | "Sum found between indexes " + start 18 | + " and " + p); 19 | return 1; 20 | } 21 | 22 | if (i < n) 23 | currentSum = currentSum + arr[i]; 24 | } 25 | 26 | System.out.println("No subarray found"); 27 | return 0; 28 | } 29 | 30 | public static void main(String[] args) 31 | { 32 | SubarraySum arraysum = new SubarraySum(); 33 | int arr[] = { 20, 15, 2, 9, 8, 4, 7, 20 }; 34 | int n = arr.length; 35 | int sum = 23; 36 | arraysum.subArraySum(arr, n, sum); 37 | } 38 | } -------------------------------------------------------------------------------- /Arrays/Trapping-rain-water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int left = 0, right = height.length - 1, max = 0, totalWater = 0; 4 | while(left < right) { 5 | if(height[left] < height[right]){ 6 | if(max < height[left]) max = height[left++]; 7 | else totalWater += max - height[left++]; 8 | } 9 | else { 10 | if(max < height[right]) max = height[right--]; 11 | else totalWater += max - height[right--]; 12 | } 13 | } 14 | 15 | return totalWater; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Arrays/Two-sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map map= new HashMap<>(); 4 | int[] resp = new int[2]; 5 | int i=0; 6 | for(int num : nums){ 7 | map.put(num, i); 8 | i++; 9 | } 10 | 11 | 12 | for(int j=0; j seen = new HashSet<>(); 4 | 5 | for(int i=0; i<9; i++){ 6 | for(int j=0; j<9; j++){ 7 | if(board[i][j] != '.'){ 8 | char currentVal = board[i][j]; 9 | if(!(seen.add(currentVal + "found in row "+ i)) || 10 | !(seen.add(currentVal + "found in column "+ j) ) || 11 | !(seen.add(currentVal + "found in sub box "+ i/3 + "-"+ j/3))) 12 | return false; 13 | } 14 | 15 | } 16 | 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Arrays/count-negative-numbers-in-a-sorted-matrix.java: -------------------------------------------------------------------------------- 1 | // problem link : https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ 2 | class Solution { 3 | public int countNegatives(int[][] grid) { 4 | int res = 0; 5 | for(int i = 0; i < grid.length; ++i) { 6 | 7 | res += negativeEachRow(grid[i]); 8 | } 9 | return res; 10 | } 11 | 12 | private int negativeEachRow(int[] row) { 13 | int res = 0; 14 | int l = 0, r = row.length - 1; 15 | while (l <= r) { 16 | int mid = l + (r - l) / 2; 17 | 18 | if (row[mid] >= 0) { 19 | l = mid + 1; 20 | } else if (row[mid] < 0) { 21 | res += r - mid + 1; 22 | r = mid - 1; 23 | } 24 | } 25 | return res; 26 | } 27 | } -------------------------------------------------------------------------------- /Arrays/remove-elements.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int i = 0; 4 | for (int j = 0; j < nums.length; j++) { 5 | if (nums[j] != val) { 6 | nums[i] = nums[j]; 7 | i++; 8 | } 9 | } 10 | return i; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Arrays/right-arrayrotation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.util.Arrays; 4 | 5 | class Main { 6 | public static void main(String[] args) { 7 | 8 | int[] array = {1,2,3,4,5}; 9 | 10 | int k = 2; 11 | 12 | System.out.println(Arrays.toString(array)); 13 | 14 | rightRotation(array,k); 15 | 16 | System.out.println("After right rotation Array"); 17 | System.out.println(Arrays.toString(array)); 18 | } 19 | 20 | public static void rightRotation(int[] arr, int k) { 21 | k = k % arr.length; 22 | for(int i = 0; i < k; i++) { 23 | int j, last; 24 | 25 | last = arr[arr.length-1]; 26 | for(j = arr.length-1; j > 0; j--) { 27 | 28 | arr[j] = arr[j-1]; 29 | } 30 | 31 | arr[0] = last; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Arrays/search-insert-position.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | for(int i=0; itarget)) 5 | return i; 6 | } 7 | return nums.length; 8 | } 9 | 10 | -------------------------------------------------------------------------------- /Arrays/search-insert.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | for(int i=0; itarget)) 5 | return i; 6 | } 7 | return nums.length; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Arrays/secondLargestElement.java: -------------------------------------------------------------------------------- 1 | package language.Java.Array; 2 | 3 | public class secondlargest { 4 | public static void main(String[] args) { 5 | int a[] = { 0,-1,3,5,2}; 6 | int max =Integer.MIN_VALUE; 7 | int secondMax = max; 8 | int min = a[0] ; 9 | for (int i = 0; i < a.length; i++) { 10 | if (maxa[i]) min = a[i]; 17 | 18 | 19 | 20 | } 21 | System.out.println("max :"+max); 22 | System.out.println("Second Max :"+secondMax); 23 | System.out.println("min :"+min); 24 | 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Arrays/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int oddCells(int n, int m, int[][] indices) { 3 | int count = 0; 4 | int row[] = new int[n]; 5 | int col[] = new int[m]; 6 | for(int i = 0; i < indices.length; i++) { 7 | row[indices[i][0]]++; 8 | col[indices[i][1]]++; 9 | } 10 | 11 | for(int i = 0; i < n; i++) { 12 | for(int j = 0; j < m; j++) { 13 | if((row[i]+col[j])%2 != 0) 14 | count++; 15 | } 16 | } 17 | 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Arrays/sudoku-solver.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void solveSudoku(char[][] board) { 3 | 4 | solve(board,0,0); 5 | } 6 | public static boolean solve(char[][] board, int row, int col) 7 | { 8 | 9 | if(row==board.length) 10 | return true; 11 | 12 | int new_row=0; 13 | int new_col=0; 14 | 15 | if(col==8) 16 | { 17 | new_row=row+1; 18 | new_col=0; 19 | } 20 | else 21 | { 22 | new_row=row; 23 | new_col=col+1; 24 | } 25 | 26 | if(board[row][col]!='.') 27 | { 28 | if(solve(board,new_row,new_col)) 29 | return true; 30 | } 31 | else{ 32 | for(int i=1;i<=9;i++) 33 | { 34 | if(isValid(board,row,col,i)) 35 | { 36 | 37 | board[row][col]=(char)(i+ '0'); 38 | if(solve(board,new_row,new_col)) 39 | return true; 40 | board[row][col]='.'; 41 | } 42 | } 43 | } 44 | 45 | return false; 46 | } 47 | public static boolean isValid(char[][] board, int row, int col, int num) 48 | { 49 | for(int i=0;i root.key) 47 | root.right = insertRec(root.right, key); 48 | 49 | /* return the (unchanged) node pointer */ 50 | return root; 51 | } 52 | 53 | // This method mainly calls InorderRec() 54 | void inorder() { inorderRec(root); } 55 | 56 | // A utility function to 57 | // do inorder traversal of BST 58 | void inorderRec(Node root) 59 | { 60 | if (root != null) { 61 | inorderRec(root.left); 62 | System.out.println(root.key); 63 | inorderRec(root.right); 64 | } 65 | } 66 | 67 | // Driver Code 68 | public static void main(String[] args) 69 | { 70 | BinarySearchTree tree = new BinarySearchTree(); 71 | 72 | /* Let us create following BST 73 | 50 74 | / \ 75 | 30 70 76 | / \ / \ 77 | 20 40 60 80 */ 78 | tree.insert(50); 79 | tree.insert(30); 80 | tree.insert(20); 81 | tree.insert(40); 82 | tree.insert(70); 83 | tree.insert(60); 84 | tree.insert(80); 85 | 86 | // print inorder traversal of the BST 87 | tree.inorder(); 88 | } 89 | } 90 | // This code is contributed by Ankur Narain Verma 91 | -------------------------------------------------------------------------------- /C++/Factorial.cpp: -------------------------------------------------------------------------------- 1 | // Factorial of n = 1*2*3*...*n 2 | 3 | #include 4 | using namespace std; 5 | 6 | int factorial(int); 7 | 8 | int main() { 9 | int n, result; 10 | 11 | cout << "Enter a non-negative number: "; 12 | cin >> n; 13 | 14 | result = factorial(n); 15 | cout << "Factorial of " << n << " = " << result; 16 | return 0; 17 | } 18 | 19 | int factorial(int n) { 20 | if (n > 1) { 21 | return n * factorial(n - 1); 22 | } else { 23 | return 1; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /C++/lcs.cpp: -------------------------------------------------------------------------------- 1 | // The longest common subsequence in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | void lcsAlgo(char *S1, char *S2, int m, int n) { 7 | int LCS_table[m + 1][n + 1]; 8 | 9 | 10 | // Building the mtrix in bottom-up way 11 | for (int i = 0; i <= m; i++) { 12 | for (int j = 0; j <= n; j++) { 13 | if (i == 0 || j == 0) 14 | LCS_table[i][j] = 0; 15 | else if (S1[i - 1] == S2[j - 1]) 16 | LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1; 17 | else 18 | LCS_table[i][j] = max(LCS_table[i - 1][j], LCS_table[i][j - 1]); 19 | } 20 | } 21 | 22 | int index = LCS_table[m][n]; 23 | char lcsAlgo[index + 1]; 24 | lcsAlgo[index] = '\0'; 25 | 26 | int i = m, j = n; 27 | while (i > 0 && j > 0) { 28 | if (S1[i - 1] == S2[j - 1]) { 29 | lcsAlgo[index - 1] = S1[i - 1]; 30 | i--; 31 | j--; 32 | index--; 33 | } 34 | 35 | else if (LCS_table[i - 1][j] > LCS_table[i][j - 1]) 36 | i--; 37 | else 38 | j--; 39 | } 40 | 41 | // Printing the sub sequences 42 | cout << "S1 : " << S1 << "\nS2 : " << S2 << "\nLCS: " << lcsAlgo << "\n"; 43 | } 44 | 45 | int main() { 46 | char S1[] = "ACADB"; 47 | char S2[] = "CBDA"; 48 | int m = strlen(S1); 49 | int n = strlen(S2); 50 | 51 | lcsAlgo(S1, S2, m, n); 52 | } 53 | -------------------------------------------------------------------------------- /C++/maximumexpression.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | 7 | int t; 8 | cin >> t; 9 | while (t--) 10 | { 11 | int n; 12 | cin >> n; 13 | string str; 14 | cin >> str; 15 | int p = 0; 16 | int m = 0; 17 | vector num; 18 | 19 | for (int i = 0; i < n; i++) 20 | { 21 | if (str[i] == '+') 22 | { 23 | p++; 24 | } 25 | else if (str[i] == '-') 26 | { 27 | m++; 28 | } 29 | else 30 | { 31 | num.push_back(str[i]); 32 | } 33 | } 34 | 35 | sort(num.begin(), num.end()); 36 | 37 | string a = ""; 38 | 39 | for (int j = 0; j < num.size(); j++) 40 | { 41 | if (m != 0) 42 | { 43 | a = a + num[j]; 44 | a = a + '-'; 45 | m--; 46 | } 47 | else if (p != 0) 48 | { 49 | a = a + num[j]; 50 | a = a + '+'; 51 | p--; 52 | } 53 | 54 | else 55 | { 56 | a = a + num[j]; 57 | } 58 | } 59 | reverse(a.begin(), a.end()); 60 | 61 | cout << a << endl; 62 | } 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /C++/warshall.cpp: -------------------------------------------------------------------------------- 1 | // Floyd-Warshall Algorithm in C++ 2 | 3 | #include 4 | using namespace std; 5 | 6 | // defining the number of vertices 7 | #define nV 4 8 | 9 | #define INF 999 10 | 11 | void printMatrix(int matrix[][nV]); 12 | 13 | // Implementing floyd warshall algorithm 14 | void floydWarshall(int graph[][nV]) { 15 | int matrix[nV][nV], i, j, k; 16 | 17 | for (i = 0; i < nV; i++) 18 | for (j = 0; j < nV; j++) 19 | matrix[i][j] = graph[i][j]; 20 | 21 | // Adding vertices individually 22 | for (k = 0; k < nV; k++) { 23 | for (i = 0; i < nV; i++) { 24 | for (j = 0; j < nV; j++) { 25 | if (matrix[i][k] + matrix[k][j] < matrix[i][j]) 26 | matrix[i][j] = matrix[i][k] + matrix[k][j]; 27 | } 28 | } 29 | } 30 | printMatrix(matrix); 31 | } 32 | 33 | void printMatrix(int matrix[][nV]) { 34 | for (int i = 0; i < nV; i++) { 35 | for (int j = 0; j < nV; j++) { 36 | if (matrix[i][j] == INF) 37 | printf("%4s", "INF"); 38 | else 39 | printf("%4d", matrix[i][j]); 40 | } 41 | printf("\n"); 42 | } 43 | } 44 | 45 | int main() { 46 | int graph[nV][nV] = {{0, 3, INF, 5}, 47 | {2, 0, INF, 4}, 48 | {INF, 1, 0, INF}, 49 | {INF, INF, 2, 0}}; 50 | floydWarshall(graph); 51 | } 52 | -------------------------------------------------------------------------------- /C/bubblesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void input(int a[5],int n) 4 | { 5 | int i; 6 | for(i=0; ia[j+1])// for swap 28 | { 29 | temp=a[j]; 30 | a[j]=a[j+1]; 31 | a[j+1]=temp; 32 | } 33 | } 34 | } 35 | } 36 | int main() 37 | { 38 | int a[5],n; 39 | printf("size of array element\n"); 40 | scanf("%d",&n); 41 | printf("enter array's element\n"); 42 | input(a,n); 43 | bubble_sort(a,n); 44 | output(a,n); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | Hi there! 3 | 4 | We're thrilled that you'd like to contribute to Hacktoberfest. Your help is essential for keeping it great. 5 | 6 | To kickstart this journey, hop on to https://hacktoberfest.digitalocean.com and sign in with your GitHub account and follow the steps to start contributing. 7 | Happy coding !! 8 | 9 | 10 | make sure your repositories are related to this... 11 | like if your repo is related to dsa then make sure upload your repo in dsa folder if not available then make folder by "\" symbol. 12 | ex:-i made a hello world program in c++ language then , 13 | if C++ folder didnt made then i have to submit repo like this:-C/hello_World.cpp 14 | like this....hope you will understand 15 | -------------------------------------------------------------------------------- /Dsa/Binary_Search.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | int binarySearch(int arr[], int x) 3 | { 4 | int l = 0, r = arr.length - 1; 5 | while (l <= r) { 6 | int m = l + (r - l) / 2; 7 | 8 | if (arr[m] == x) 9 | return m; 10 | 11 | if (arr[m] < x) 12 | l = m + 1; 13 | 14 | else 15 | r = m - 1; 16 | } 17 | 18 | return -1; 19 | } 20 | 21 | public static void main(String args[]) 22 | { 23 | BinarySearch ob = new BinarySearch(); 24 | int arr[] = { 2, 3, 4, 10, 40 }; 25 | int n = arr.length; 26 | int x = 10; 27 | int result = ob.binarySearch(arr, x); 28 | if (result == -1) 29 | System.out.println("Element not present"); 30 | else 31 | System.out.println("Element found at " 32 | + "index " + result); 33 | } 34 | } -------------------------------------------------------------------------------- /Dsa/C++/median_row_matrix.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find median of a matrix 2 | // sorted row wise 3 | #include 4 | using namespace std; 5 | 6 | const int MAX = 100; 7 | 8 | // function to find median in the matrix 9 | int binaryMedian(int m[][MAX], int r ,int c) 10 | { 11 | int min = INT_MAX, max = INT_MIN; 12 | for (int i=0; i max) 20 | max = m[i][c-1]; 21 | } 22 | 23 | int desired = (r * c + 1) / 2; 24 | while (min < max) 25 | { 26 | int mid = min + (max - min) / 2; 27 | int place = 0; 28 | 29 | // Find count of elements smaller than or equal to mid 30 | for (int i = 0; i < r; ++i) 31 | place += upper_bound(m[i], m[i]+c, mid) - m[i]; 32 | if (place < desired) 33 | min = mid + 1; 34 | else 35 | max = mid; 36 | } 37 | return min; 38 | } 39 | 40 | // driver program to check above functions 41 | int main() 42 | { 43 | int r = 3, c = 3; 44 | int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; 45 | cout << "Median is " << binaryMedian(m, r, c) << endl; 46 | return 0; 47 | } 48 | 49 | 50 | //This code is contributed by Jayant Verma 51 | -------------------------------------------------------------------------------- /Dsa/Check for BST . CPP: -------------------------------------------------------------------------------- 1 | bool isValidBST(Node*root , long min , long max) 2 | { 3 | 4 | if(root==NULL) return true; 5 | if (root->data>= max || root->data<=min) return false; 6 | return isValidBST(root->left , min , root->data) && 7 | isValidBST(root->right , root->data , max); 8 | 9 | } 10 | 11 | //Function to check whether a Binary Tree is BST or not. 12 | bool isBST(Node* root) 13 | { 14 | 15 | return isValidBST(root , LONG_MIN , LONG_MAX ); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Dsa/noOfNodes.java: -------------------------------------------------------------------------------- 1 | package treeBinary; 2 | 3 | 4 | 5 | public class noOfNodes { 6 | public static class Node{ 7 | int data; 8 | Node left; 9 | Node right; 10 | Node(int data) 11 | { 12 | this.data=data; 13 | this.left=null; 14 | this.right=null; 15 | } 16 | } 17 | 18 | public static class binaryTree 19 | { 20 | static int idx=-1; 21 | public static Node builtree(int nodes[]) 22 | { 23 | idx++; 24 | if(nodes[idx]==-1) 25 | { 26 | return null; 27 | } 28 | Node newNode=new Node(nodes[idx]); 29 | newNode.left=builtree(nodes); 30 | newNode.right=builtree(nodes); 31 | return newNode; 32 | } 33 | } 34 | 35 | public static int count(Node root) 36 | { 37 | if(root==null) 38 | { 39 | return 0; 40 | } 41 | int left=count(root.left); 42 | int right=count(root.right); 43 | 44 | return left+right+1; 45 | 46 | } 47 | 48 | public static void main(String args[]) 49 | { 50 | int nodes[]= {1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1}; 51 | binaryTree tree=new binaryTree(); 52 | Node root=tree.builtree(nodes); 53 | System.out.println("No of Nodes is:"+ count(root)); 54 | 55 | 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Rahul 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Permutation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> permute(int[] nums) { 3 | //initalizing one data structure which store the value duricng recursive call in it 4 | List ds = new ArrayList<>(); 5 | 6 | // initalizing array of array which print output the permutation of array 7 | List> ans = new ArrayList<>(); 8 | 9 | // intializing another array of length final array nums of type boolean which mark the value true when we visited that particular index during recursive call because we don't want duplicate value in array (* not considering duplicate value which already present in intial array) 10 | boolean[] freq = new boolean[nums.length]; 11 | // calling the function 12 | permutation(ds,ans,nums,freq); 13 | return ans; 14 | 15 | } 16 | 17 | public void permutation(Listds, List> ans, int[] nums, boolean[] freq) 18 | { 19 | 20 | this is base condition whe size of declared data structure became equal to intial array then that time ds contain one cycle of permutation and we add it to ans. 21 | if(ds.size() == nums.length) 22 | { 23 | ans.add(new ArrayList<>(ds)); 24 | return; 25 | } 26 | // running loop till n and marking visited not visited during recursive call 27 | for(int i = 0; i < nums.length; i++) 28 | { 29 | if(!freq[i]) 30 | { 31 | // if not visited then mark true 32 | freq[i] = true; 33 | //add it to ds 34 | ds.add(nums[i]); 35 | //call the function again because it recursion calling back to back 36 | permutation(ds,ans,nums,freq); 37 | // when recursin reaches equal to size of intial array then remove tha last element of ds and unmarked the visited array 38 | ds.remove(ds.size()-1); 39 | freq[i] = false; 40 | } 41 | } 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Permutations2.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashSet; 3 | import java.util.List; 4 | 5 | class Solution { 6 | public List> permuteUnique(int[] nums) { 7 | List> res = new ArrayList<>(); 8 | HashSet> set = new HashSet<>(); 9 | 10 | backtrack(res, nums, 0, set); 11 | return res; 12 | } 13 | 14 | public void backtrack(List> res, int[] nums, int index, HashSet> set) { 15 | if (index == nums.length) { 16 | List current = toList(nums); 17 | if (!set.contains(current)) { 18 | res.add(current); 19 | set.add(current); 20 | } 21 | } else { 22 | for (int i = index; i < nums.length; i++) { 23 | swap(index, i, nums); 24 | backtrack(res, nums, index + 1, set); 25 | swap(index, i, nums); 26 | } 27 | } 28 | } 29 | 30 | public void swap(int m, int n, int[] nums) { 31 | int temp = nums[m]; 32 | nums[m] = nums[n]; 33 | nums[n] = temp; 34 | } 35 | 36 | public List toList(int[] nums) { 37 | ArrayList l = new ArrayList<>(); 38 | for (int n : nums) { 39 | l.add(n); 40 | } 41 | return l; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Plus-one.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] plusOne(int[] digits) { 3 | int n = digits.length; 4 | for (int i = n - 1; i >= 0; i--) { 5 | digits[i]++; 6 | if (digits[i] < 10) { 7 | return digits; 8 | } 9 | digits[i] = 0; 10 | } 11 | 12 | int[] result = new int[n + 1]; 13 | result[0] = 1; 14 | return result; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ds_and_algo 2 | Hacktoberfest 2023 3 | -------------------------------------------------------------------------------- /basic/RedOrGreen.java: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // initial template for Java 3 | //https://practice.geeksforgeeks.org/problems/red-or-green5711/1 4 | 5 | import java.io.*; 6 | import java.util.*; 7 | 8 | class GFG { 9 | // Position this line where user code will be pasted. 10 | public static void main(String args[]) throws IOException { 11 | BufferedReader read = 12 | new BufferedReader(new InputStreamReader(System.in)); 13 | int t = Integer.parseInt(read.readLine()); 14 | while (t-- > 0) { 15 | int N = Integer.parseInt(read.readLine()); 16 | String S = read.readLine(); 17 | Solution ob = new Solution(); 18 | System.out.println(ob.RedOrGreen(N, S)); 19 | } 20 | } 21 | }// } Driver Code Ends 22 | 23 | 24 | //User function template for Java 25 | 26 | class Solution { 27 | static int RedOrGreen(int N, String S) { 28 | int g=0; 29 | for( int i=0;i0) 16 | { 17 | String s = br.readLine(); 18 | 19 | Solution obj = new Solution(); 20 | System.out.println(obj.lastIndex( s)); 21 | 22 | } 23 | } 24 | } 25 | // } Driver Code Ends 26 | 27 | 28 | //User function Template for Java 29 | 30 | 31 | class Solution { 32 | public int lastIndex( String s) { 33 | for(int i=s.length()-1;i>=0;i--){ 34 | if (s.charAt(i)=='1'){ 35 | return i; 36 | } 37 | } 38 | return -1; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /dsa/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class insertionsort { 2 | public static void main(String args[]) { 3 | int arr[] = { 9, 5, 23, 8, 10, 2 }; 4 | for (int i = 1; i < 6; i++) { 5 | int temp = arr[i]; 6 | int j = i - 1; 7 | while (j >= 0 && arr[j] > temp) { 8 | arr[j + 1] = arr[j]; 9 | j--; 10 | } 11 | arr[j + 1] = temp; 12 | } 13 | for (int i = 0; i < 6; i++) { 14 | System.out.print(arr[i] + " "); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /dsa/Kruskal_algo.cpp: -------------------------------------------------------------------------------- 1 | #Kruskal’s Minimum Spanning Tree Algorithm 2 | // C++ program for the above approach 3 | 4 | #include 5 | using namespace std; 6 | 7 | // DSU data structure 8 | // path compression + rank by union 9 | 10 | class DSU { 11 | int* parent; 12 | int* rank; 13 | 14 | public: 15 | DSU(int n) 16 | { 17 | parent = new int[n]; 18 | rank = new int[n]; 19 | 20 | for (int i = 0; i < n; i++) { 21 | parent[i] = -1; 22 | rank[i] = 1; 23 | } 24 | } 25 | 26 | // Find function 27 | int find(int i) 28 | { 29 | if (parent[i] == -1) 30 | return i; 31 | 32 | return parent[i] = find(parent[i]); 33 | } 34 | 35 | // Union function 36 | void unite(int x, int y) 37 | { 38 | int s1 = find(x); 39 | int s2 = find(y); 40 | 41 | if (s1 != s2) { 42 | if (rank[s1] < rank[s2]) { 43 | parent[s1] = s2; 44 | rank[s2] += rank[s1]; 45 | } 46 | else { 47 | parent[s2] = s1; 48 | rank[s1] += rank[s2]; 49 | } 50 | } 51 | } 52 | }; 53 | 54 | class Graph { 55 | vector > edgelist; 56 | int V; 57 | 58 | public: 59 | Graph(int V) { this->V = V; } 60 | 61 | void addEdge(int x, int y, int w) 62 | { 63 | edgelist.push_back({ w, x, y }); 64 | } 65 | 66 | void kruskals_mst() 67 | { 68 | // 1. Sort all edges 69 | sort(edgelist.begin(), edgelist.end()); 70 | 71 | // Initialize the DSU 72 | DSU s(V); 73 | int ans = 0; 74 | cout << "Following are the edges in the " 75 | "constructed MST" 76 | << endl; 77 | for (auto edge : edgelist) { 78 | int w = edge[0]; 79 | int x = edge[1]; 80 | int y = edge[2]; 81 | 82 | // Take this edge in MST if it does 83 | // not forms a cycle 84 | if (s.find(x) != s.find(y)) { 85 | s.unite(x, y); 86 | ans += w; 87 | cout << x << " -- " << y << " == " << w 88 | << endl; 89 | } 90 | } 91 | 92 | cout << "Minimum Cost Spanning Tree: " << ans; 93 | } 94 | }; 95 | 96 | // Driver's code 97 | int main() 98 | { 99 | /* Let us create following weighted graph 100 | 10 101 | 0--------1 102 | | \ | 103 | 6| 5\ |15 104 | | \ | 105 | 2--------3 106 | 4 */ 107 | Graph g(4); 108 | g.addEdge(0, 1, 10); 109 | g.addEdge(1, 3, 15); 110 | g.addEdge(2, 3, 4); 111 | g.addEdge(2, 0, 6); 112 | g.addEdge(0, 3, 5); 113 | 114 | // Function call 115 | g.kruskals_mst(); 116 | return 0; 117 | } 118 | -------------------------------------------------------------------------------- /dsa/Linearsearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class LinearSearchExample2 4 | { 5 | public static void main(String args[]) 6 | { 7 | int c, n, search, array[]; 8 | 9 | Scanner in = new Scanner(System.in); 10 | System.out.println("Enter number of elements"); 11 | n = in.nextInt(); 12 | array = new int[n]; 13 | 14 | System.out.println("Enter those " + n + " elements"); 15 | 16 | for (c = 0; c < n; c++) 17 | array[c] = in.nextInt(); 18 | 19 | System.out.println("Enter value to find"); 20 | search = in.nextInt(); 21 | 22 | for (c = 0; c < n; c++) 23 | { 24 | if (array[c] == search) /* Searching element is present */ 25 | { 26 | System.out.println(search + " is present at location " + (c + 1) + "."); 27 | break; 28 | } 29 | } 30 | if (c == n) /* Element to search isn't present */ 31 | System.out.println(search + " isn't present in array."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dsa/Selection_Sort.cpp: -------------------------------------------------------------------------------- 1 | "Data Structure and Algorithms-Selection Sort" 2 | Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right. This algorithm is not suitable for large data sets as its average and worst case complexities are of Ο(n2), where n is the number of items. 3 | 4 | Algorithm- 5 | Step 1 − Set MIN to location 0 6 | Step 2 − Search the minimum element in the list 7 | Step 3 − Swap with value at location MIN 8 | Step 4 − Increment MIN to point to next element 9 | Step 5 − Repeat until list is sorted 10 | 11 | Pseudocode- 12 | procedure selection sort 13 | list : array of items 14 | n : size of list 15 | 16 | for i = 1 to n - 1 17 | /* set current element as minimum*/ 18 | min = i 19 | 20 | /* check the element to be minimum */ 21 | 22 | for j = i+1 to n 23 | if list[j] < list[min] then 24 | min = j; 25 | end if 26 | end for 27 | 28 | /* swap the minimum element with the current element*/ 29 | if indexMin != i then 30 | swap list[min] and list[i] 31 | end if 32 | end for 33 | 34 | end procedure 35 | -------------------------------------------------------------------------------- /dsa/Selection_Sort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSortExample { 2 | public static void selectionSort(int[] arr){ 3 | for (int i = 0; i < arr.length - 1; i++) 4 | { 5 | int index = i; 6 | for (int j = i + 1; j < arr.length; j++){ 7 | if (arr[j] < arr[index]){ 8 | index = j; 9 | } 10 | } 11 | int smallerNumber = arr[index]; 12 | arr[index] = arr[i]; 13 | arr[i] = smallerNumber; 14 | } 15 | } 16 | 17 | public static void main(String a[]){ 18 | int[] arr1 = {9,14,3,2,43,11,58,22}; 19 | System.out.println("Before Selection Sort"); 20 | for(int i:arr1){ 21 | System.out.print(i+" "); 22 | } 23 | System.out.println(); 24 | 25 | selectionSort(arr1); 26 | 27 | System.out.println("After Selection Sort"); 28 | for(int i:arr1){ 29 | System.out.print(i+" "); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dsa/SetMismatch.java: -------------------------------------------------------------------------------- 1 | public class SetMismatch { 2 | public int[] findErrorNums(int[] nums) { 3 | int i = 0; 4 | while(i< nums.length){ 5 | int correct = nums[i]-1; 6 | if(nums[i] != nums[correct]){ 7 | swap(nums, i,correct); 8 | }else { 9 | i++; 10 | } 11 | } 12 | // search for first missing number 13 | for (int index = 0;index< nums.length;index++){ 14 | if (nums[index] != index + 1){ 15 | return new int[] {nums[index], index+1}; 16 | } 17 | } 18 | return new int[] {}; 19 | } 20 | static void swap(int[] arr, int first, int second){ 21 | int temp= arr[first]; 22 | arr[first] = arr[second]; 23 | arr[second] = temp; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dsa/doubly_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node { 5 | int data; 6 | struct node *prev, *next; 7 | }*start = NULL; 8 | 9 | void insertAtFront(){ 10 | 11 | int data; 12 | struct node* temp; 13 | temp = (struct node*)malloc(sizeof(struct node)); 14 | 15 | printf("\nEnter number to be inserted: "); 16 | scanf("%d", &data); 17 | 18 | temp->data = data; 19 | temp->prev = NULL; 20 | 21 | temp->next = start; 22 | start = temp; 23 | 24 | } 25 | 26 | void insertAtEnd(){ 27 | 28 | int data; 29 | struct node *temp, *trav; 30 | temp = (struct node*)malloc(sizeof(struct node)); 31 | 32 | temp->prev = NULL; 33 | temp->next = NULL; 34 | 35 | printf("\nEnter number to be inserted: "); 36 | scanf("%d", &data); 37 | 38 | temp->data = data; 39 | temp->next = NULL; 40 | trav = start; 41 | 42 | if (start == NULL) 43 | start = temp; 44 | 45 | else { 46 | while (trav->next != NULL) 47 | trav = trav->next; 48 | temp->prev = trav; 49 | trav->next = temp; 50 | } 51 | } 52 | 53 | void insertAtPosition(){ 54 | 55 | int data, pos, i = 1; 56 | struct node *temp, *extra; 57 | extra = malloc(sizeof(struct node)); 58 | 59 | extra->next = NULL; 60 | extra->prev = NULL; 61 | 62 | printf("\nEnter position : "); 63 | scanf("%d", &pos); 64 | 65 | if (start == NULL) { 66 | start = extra; 67 | extra->prev = NULL; 68 | extra->next = NULL; 69 | } 70 | 71 | else if (pos == 1) 72 | insertAtFront(); 73 | 74 | else { 75 | printf("\nEnter number to be inserted: "); 76 | scanf("%d", &data); 77 | extra->data = data; 78 | temp = start; 79 | while (i < pos - 1) { 80 | temp = temp->next; 81 | i++; 82 | } 83 | extra->next = temp->next; 84 | extra->prev = temp; 85 | temp->next = extra; 86 | temp->next->prev = extra; 87 | } 88 | } 89 | 90 | void deleteFirst(){ 91 | struct node* temp; 92 | 93 | if (start == NULL) 94 | printf("\nList is empty\n"); 95 | else { 96 | temp = start; 97 | start = start->next; 98 | 99 | if (start != NULL) 100 | start->prev = NULL; 101 | 102 | free(temp); 103 | } 104 | } 105 | 106 | void deletePosition(int pos){ 107 | 108 | int i = 1; 109 | struct node *temp, *position; 110 | temp = start; 111 | 112 | if (start == NULL) 113 | printf("\nList is empty\n"); 114 | 115 | else { 116 | 117 | if (pos == 1) { 118 | deleteFirst(); 119 | 120 | if (start != NULL) 121 | start->prev = NULL; 122 | 123 | free(position); 124 | return; 125 | } 126 | 127 | while (i < pos - 1) { 128 | temp = temp->next; 129 | i++; 130 | } 131 | 132 | position = temp->next; 133 | 134 | if (position->next != NULL) 135 | position->next->prev = temp; 136 | 137 | temp->next = position->next; 138 | 139 | free(position); 140 | } 141 | } 142 | 143 | void deletebyvalue(){ 144 | 145 | int num; 146 | struct node* temp; 147 | temp = start; 148 | 149 | if (start == NULL) 150 | printf("\nList is empty\n"); 151 | 152 | else { 153 | printf("\nEnter Value to be deleted : "); 154 | scanf("%d", &num); 155 | } 156 | 157 | int count = 1; 158 | 159 | while(temp->data != num){ 160 | temp = temp->next; 161 | count++; 162 | } 163 | 164 | if(count > 0){ 165 | deletePosition(count); 166 | } 167 | 168 | } 169 | 170 | void print(){ 171 | 172 | if (start == NULL){ 173 | printf("\nList is empty\n"); 174 | return; 175 | } 176 | 177 | struct node* temp; 178 | temp = start; 179 | 180 | printf("\nData = "); 181 | while (temp != NULL) { 182 | printf("%d ", temp->data); 183 | temp = temp->next; 184 | } 185 | printf("\n"); 186 | } 187 | 188 | int main(){ 189 | 190 | int choice; 191 | 192 | while (choice != 8){ 193 | 194 | printf("\nDoubly Linked List Menu:\n"); 195 | printf("1. Insertion at Beginning\n"); 196 | printf("2. Insertion at End\n"); 197 | printf("3. Insertion at particular Location\n"); 198 | printf("4. Deletion by Value\n"); 199 | printf("5. Display the List\n"); 200 | printf("6. Exit the menu\n"); 201 | 202 | printf("Enter your choice : "); 203 | scanf("%d", &choice); 204 | 205 | switch (choice) { 206 | case 1: 207 | insertAtFront(); 208 | break; 209 | case 2: 210 | insertAtEnd(); 211 | break; 212 | case 3: 213 | insertAtPosition(); 214 | break; 215 | case 4: 216 | deletebyvalue(); 217 | break; 218 | case 5: 219 | print(); 220 | break; 221 | case 6: 222 | exit(1); 223 | break; 224 | default: 225 | printf("Incorrect Choice. Please Try Again \n"); 226 | continue; 227 | } 228 | } 229 | return 0; 230 | } 231 | -------------------------------------------------------------------------------- /dsa/mergesort.java: -------------------------------------------------------------------------------- 1 | /* Java program for Merge Sort */ 2 | class MergeSort { 3 | // Merges two subarrays of arr[]. 4 | // First subarray is arr[l..m] 5 | // Second subarray is arr[m+1..r] 6 | void merge(int arr[], int l, int m, int r) 7 | { 8 | // Find sizes of two subarrays to be merged 9 | int n1 = m - l + 1; 10 | int n2 = r - m; 11 | 12 | /* Create temp arrays */ 13 | int L[] = new int[n1]; 14 | int R[] = new int[n2]; 15 | 16 | /*Copy data to temp arrays*/ 17 | for (int i = 0; i < n1; ++i) 18 | L[i] = arr[l + i]; 19 | for (int j = 0; j < n2; ++j) 20 | R[j] = arr[m + 1 + j]; 21 | 22 | /* Merge the temp arrays */ 23 | 24 | // Initial indexes of first and second subarrays 25 | int i = 0, j = 0; 26 | 27 | // Initial index of merged subarray array 28 | int k = l; 29 | while (i < n1 && j < n2) { 30 | if (L[i] <= R[j]) { 31 | arr[k] = L[i]; 32 | i++; 33 | } 34 | else { 35 | arr[k] = R[j]; 36 | j++; 37 | } 38 | k++; 39 | } 40 | 41 | /* Copy remaining elements of L[] if any */ 42 | while (i < n1) { 43 | arr[k] = L[i]; 44 | i++; 45 | k++; 46 | } 47 | 48 | /* Copy remaining elements of R[] if any */ 49 | while (j < n2) { 50 | arr[k] = R[j]; 51 | j++; 52 | k++; 53 | } 54 | } 55 | 56 | // Main function that sorts arr[l..r] using 57 | // merge() 58 | void sort(int arr[], int l, int r) 59 | { 60 | if (l < r) { 61 | // Find the middle point 62 | int m = l + (r - l) / 2; 63 | 64 | // Sort first and second halves 65 | sort(arr, l, m); 66 | sort(arr, m + 1, r); 67 | 68 | // Merge the sorted halves 69 | merge(arr, l, m, r); 70 | } 71 | } 72 | 73 | /* A utility function to print array of size n */ 74 | static void printArray(int arr[]) 75 | { 76 | int n = arr.length; 77 | for (int i = 0; i < n; ++i) 78 | System.out.print(arr[i] + " "); 79 | System.out.println(); 80 | } 81 | 82 | // Driver code 83 | public static void main(String args[]) 84 | { 85 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 86 | 87 | System.out.println("Given Array"); 88 | printArray(arr); 89 | 90 | MergeSort ob = new MergeSort(); 91 | ob.sort(arr, 0, arr.length - 1); 92 | 93 | System.out.println("\nSorted array"); 94 | printArray(arr); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /dsa/reverse_string.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class ReverseStringExample1 3 | { 4 | public static void main(String[] args) 5 | { 6 | String str; 7 | System.out.println("Enter a string: "); 8 | Scanner scanner = new Scanner(System.in); 9 | str = scanner.nextLine(); 10 | scanner.close(); //closes the input stream 11 | String reversed = reverseString(str); 12 | System.out.println("The reversed string is: " + reversed); 13 | } 14 | public static String reverseString(String s) 15 | { 16 | if (s.isEmpty()) //checks the string if empty 17 | return s; 18 | return reverseString(s.substring(1)) + s.charAt(0); //recursively called function 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dsa/shortest_common_supersequence.java: -------------------------------------------------------------------------------- 1 | module hactoberfest { 2 | // Java program to find length of 3 | // the shortest supersequence 4 | class Solution { 5 | 6 | static int shortestSuperSequence(String X, String Y) 7 | { 8 | int m = X.length(); 9 | int n = Y.length(); 10 | 11 | // find lcs 12 | int l = lcs(X, Y, m, n); 13 | 14 | // Result is sum of input string 15 | // lengths - length of lcs 16 | return (m + n - l); 17 | } 18 | 19 | // Returns length of LCS 20 | // for X[0..m - 1], Y[0..n - 1] 21 | static int lcs(String X, String Y, int m, int n) 22 | { 23 | int[][] L = new int[m + 1][n + 1]; 24 | int i, j; 25 | 26 | // Following steps build L[m + 1][n + 1] 27 | // in bottom up fashion. Note that 28 | // L[i][j] contains length of LCS 29 | // of X[0..i - 1]and Y[0..j - 1] 30 | for (i = 0; i <= m; i++) { 31 | for (j = 0; j <= n; j++) { 32 | if (i == 0 || j == 0) 33 | L[i][j] = 0; 34 | 35 | else if (X.charAt(i - 1) == Y.charAt(j - 1)) 36 | L[i][j] = L[i - 1][j - 1] + 1; 37 | 38 | else 39 | L[i][j] = Math.max(L[i - 1][j], 40 | L[i][j - 1]); 41 | } 42 | } 43 | 44 | // L[m][n] contains length of LCS 45 | // for X[0..n - 1] and Y[0..m - 1] 46 | return L[m][n]; 47 | } 48 | public static void main(String args[]) 49 | { 50 | String X = "AGGTAB"; 51 | String Y = "GXTXAYB"; 52 | 53 | System.out.println("Length of the shortest " 54 | + "supersequence is " 55 | + shortestSuperSequence(X, Y)); 56 | } 57 | } 58 | 59 | 60 | 61 | } -------------------------------------------------------------------------------- /dsa/tictactoe.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rahulatrkm/ds_and_algo/6305f016c7c1eaa126469120e54662186b86a60c/dsa/tictactoe.java -------------------------------------------------------------------------------- /easy/countBuildings: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for Java 3 | 4 | 5 | 6 | import java.util.*; 7 | import java.io.*; 8 | 9 | public class Main { 10 | 11 | public static void main(String[] args) throws Exception { 12 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 13 | int tc = Integer.parseInt(br.readLine().trim()); 14 | while (tc-- > 0) { 15 | String[] inputLine; 16 | int n = Integer.parseInt(br.readLine().trim()); 17 | int[] h = new int[n]; 18 | inputLine = br.readLine().trim().split(" "); 19 | for (int i = 0; i < n; i++) { 20 | h[i] = Integer.parseInt(inputLine[i]); 21 | } 22 | 23 | 24 | int ans = new Solution().countBuildings(h, n); 25 | System.out.println(ans); 26 | } 27 | } 28 | }// } Driver Code Ends 29 | 30 | 31 | //User function Template for Java 32 | 33 | 34 | 35 | class Solution { 36 | int countBuildings(int h[], int n) { 37 | int build=1, max=h[0]; 38 | for(int i=1;imax){ 40 | max=h[i]; 41 | build++; 42 | } 43 | } 44 | return build; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /easy/sumElement: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for Java 3 | 4 | 5 | import java.util.*; 6 | import java.io.*; 7 | import java.lang.*; 8 | 9 | class Driver 10 | { 11 | public static void main(String args[])throws IOException 12 | { 13 | BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); 14 | int t = Integer.parseInt(read.readLine()); 15 | 16 | while(t-- > 0) 17 | { 18 | int n = Integer.parseInt(read.readLine()); 19 | String str[] = read.readLine().trim().split(" "); 20 | 21 | int input[] = new int[n]; 22 | for(int i = 0; i < n; i++) 23 | { 24 | input[i] = Integer.parseInt(str[i]); 25 | } 26 | 27 | //int x = Integer.parseInt(read.readLine()); 28 | Get obj = new Get(); 29 | System.out.println(obj.sumElement(input, n)); 30 | 31 | } 32 | } 33 | } 34 | 35 | 36 | // } Driver Code Ends 37 | 38 | 39 | //User function Template for Java 40 | 41 | 42 | class Get 43 | { 44 | public static int sumElement(int arr[], int n) 45 | { 46 | int sum=0; 47 | for(int i=0;i arr[end]) { 6 | while (start <= end) { 7 | mid = start + (end - start) / 2; 8 | if (mid > 0 && arr[mid] < arr[mid - 1]) { 9 | pivot = mid - 1; 10 | break; 11 | } 12 | if (mid < (arr.length - 1) && arr[mid] > arr[mid + 1]) { 13 | pivot = mid; 14 | break; 15 | } 16 | if (arr[mid] > arr[start]) { 17 | start = mid + 1; 18 | } else { 19 | end = mid - 1; 20 | } 21 | 22 | } 23 | if (pivot == -1) { 24 | pivot = start; 25 | } 26 | start = 0; 27 | end = pivot; 28 | while (start <= end) { 29 | mid = start + (end - start) / 2; 30 | if (arr[mid] == target) { 31 | // pos = mid; 32 | break; 33 | } else if (arr[mid] > target) { 34 | end = mid - 1; 35 | } else { 36 | start = mid + 1; 37 | } 38 | } 39 | if (arr[mid] == target) { 40 | pos = mid; 41 | } 42 | if (pos == -1) { 43 | start = pivot + 1; 44 | end = arr.length - 1; 45 | while (start <= end) { 46 | mid = start + (end - start) / 2; 47 | if (arr[mid] == target) { 48 | break; 49 | } else if (arr[mid] > target) { 50 | end = mid - 1; 51 | } else { 52 | start = mid + 1; 53 | } 54 | } 55 | if (arr[mid] == target) { 56 | pos = mid; 57 | } 58 | } 59 | 60 | } else { 61 | pivot = end; 62 | start = 0; 63 | end = arr.length - 1; 64 | while (start <= end) { 65 | mid = start + (end - start) / 2; 66 | if (arr[mid] == target) { 67 | break; 68 | } else if (arr[mid] > target) { 69 | end = mid - 1; 70 | } else { 71 | start = mid + 1; 72 | } 73 | } 74 | 75 | if (arr[mid] == target) { 76 | pos = mid; 77 | } 78 | } 79 | return pos; 80 | } 81 | } 82 | --------------------------------------------------------------------------------