├── ARRAYS ├── 13. Kadane's Algorithm.txt ├── 7. Write a program to cyclically rotate an array by one..txt ├── 30. Chocolate Distribution problem.txt ├── 10. Minimum no. of Jumps to reach end of an array.txt ├── 11. Find duplicate in an array of N+1 Integers.txt ├── 1. Reverse Of Array.txt ├── 27. Find whether an array is a subset of another array.txt ├── 9. Minimise the maximum difference between heights [V.IMP].txt ├── 17. Best time to buy and Sell stock.txt ├── 19. find common elements In 3 sorted arrays.txt ├── 8. Kadane's Algorithm(find Largest sum contiguous Subarray [V. IMP]).txt ├── 34. Minimum no. of operations required to make an array palindrome.txt ├── 3. Find the Kth max and min element of an array.txt ├── 21. Find if there is any subarray with sum equal to 0.txt ├── 23. find maximum product subarray.txt ├── 18. find all pairs on integer array whose sum is equal to given number.txt ├── 35. Median of 2 sorted arrays of equal size.txt ├── 28. Find the triplet that sum to a given value.txt ├── 20. Rearrange the array in alternating positive and negative items with O(1) extra space.txt ├── 24. Find longest coinsecutive subsequence.txt ├── 15. Next Permutation.txt ├── 33. Minimum swaps required bring elements less equal K together.txt ├── 12. Merge 2 sorted arrays without using Extra space..txt ├── 22. Find factorial of a large number.txt ├── 14. Merge Intervals.txt ├── 4. Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo.txt ├── 31. Smallest Subarray with sum greater than a given value.txt ├── 2. To Find the Minimum and Maximum element in an array.txt ├── 36. Median of 2 sorted arrays of different size.txt ├── 26. Maximum profit by buying and selling a share atmost twice.txt ├── 6. Find the Union and Intersection of the two sorted arrays..txt ├── 32. Three way partitioning of an array around a given value.txt ├── 16. Count Inversion.txt ├── 29. Trapping Rain water problem.txt ├── 25. Given an array of size n and a number k, fin all elements that appear more than nk times..txt └── 5. Move all the negative elements to one side of the array.txt ├── FINAL450.xlsx ├── STRINGS ├── 1. Reverse a String.txt ├── 4. Why strings are immutable in Java.txt ├── 37. Recursively remove all adjacent duplicates.txt ├── 2. Check whether a String is Palindrome or not.txt ├── 30. Minimum number of swaps for bracket balancing..txt ├── 10. Print all Subsequences of a string..txt ├── 38. String matching where one string contains wildcard characters.txt ├── 28. Number of flips to make binary string alternate.txt ├── 35. Given a sequence of words, print all anagrams together.txt ├── 26. Converting Roman Numerals to Decimal.txt ├── 31. Find the longest common subsequence between two strings..txt ├── 17. Word break Problem[ Very Imp].txt ├── 5. Write a Code to check whether one string is a rotation of another.txt ├── 12. Split the Binary string into two substring with equal 0’s and 1’s.txt ├── 7. Count and Say problem.txt ├── 3. Find Duplicate characters in a string.txt ├── 9. Find Longest Recurring Subsequence in String.txt ├── 19. KMP Algo.txt ├── 14. EDIT Distance [Very Imp].txt ├── 27. Longest Common Prefix.txt ├── 16. Balanced Parenthesis problem.[Imp].txt ├── 32. Program to generate all possible valid IP addresses from given string..txt ├── 8. Write a program to find the longest Palindrome in a string.[ Longest palindromic Substring].txt ├── 36. Find the smallest window in a string containing all characters of another string.txt ├── 20. Convert a Sentence into its equivalent mobile numeric keypad sequence..txt ├── 22. Count All Palindromic Subsequence in a given String..txt ├── 29. Find the first repeated word in string..txt ├── 13. Word Wrap Problem [VERY IMP]..txt ├── 18. Rabin Karp.txt ├── 33. Smallest distinct window.txt ├── 25. Boyer Moore Algorithm for Pattern Searching..txt ├── 11. Print all the permutations of the given string.txt ├── 34. Minimum characters to be added at front to make string palindrome.txt ├── 21. Minimum number of bracket reversals needed to make an expression balanced..txt ├── 15. Find next greater number with same set of digits. [Very Very IMP].txt ├── 6. Write a Program to check whether a string is a valid shuffle of two strings or not.txt ├── 23. Count of number of given string in 2D character array.txt └── 24. Search a Word in a 2D Grid of characters..txt ├── MATRIX ├── 9. Kth smallest element in a row-cpumn wise sorted matrix.txt ├── 4. Find row with maximum no. of 1's.txt ├── 5. Print elements in sorted order using row-column wise sorted matrix.txt ├── 3. Find median in a row wise sorted matrix.txt ├── 8. Rotate matrix by 90 degrees.txt ├── 2. Search an element in a matriix.txt ├── 7. Find a specific pair in matrix.txt ├── 6. Maximum size rectangle.txt ├── 10. Common elements in all rows of a given matrix.txt └── 1. Spiral traversal on a Matrix.txt ├── Searching & Sorting ├── 2. Find a Fixed Point (Value equal to index) in a given array.txt ├── 7. find majority element.txt ├── 6. Find the repeating and the missing.txt ├── 5. Maximum and minimum of an array using minimum number of comparisons.txt ├── 4. square root of an integer.txt ├── 3. Search in a rotated sorted array.txt └── 1. Find first and last positions of an element in a sorted array.txt └── BASIC ├── 9. Fibonacci Using Recursion.txt ├── 5. Print 1 To N Without Loop.txt ├── 6. Sum of Digits of a Number.txt ├── 13. Power Using Recursion.txt ├── 7. Count Total Digits in a Number.txt ├── 12. Lucky Numbers.txt ├── 1. Find first set bit.txt ├── 3. Check whether K-th bit is set or not.txt ├── 11. Josephus problem.txt ├── 8. Digital Root.txt ├── 4. Count total set bits.txt ├── 2. Rightmost different bit.txt └── 10. Tower Of Hanoi.txt /ARRAYS/13. Kadane's Algorithm.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /FINAL450.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrinceKumawat1109/DSA/HEAD/FINAL450.xlsx -------------------------------------------------------------------------------- /ARRAYS/7. Write a program to cyclically rotate an array by one..txt: -------------------------------------------------------------------------------- 1 | class Compute 2 | { 3 | public void rotate(int arr[], int n) 4 | { 5 | int temp=arr[n-1]; 6 | for(int i=n-2;i>=0;i--){ 7 | arr[i+1]=arr[i]; 8 | } 9 | arr[0]=temp; 10 | } 11 | } -------------------------------------------------------------------------------- /ARRAYS/30. Chocolate Distribution problem.txt: -------------------------------------------------------------------------------- 1 | long long findMinDiff(vector a, long long n, long long m){ 2 | sort(a.begin(),a.end()); 3 | ll diff=INT_MAX; 4 | for(int i=0;i<=n-m;++i){ 5 | diff=min(diff,a[i+m-1]-a[i]); 6 | } 7 | return diff; 8 | } -------------------------------------------------------------------------------- /ARRAYS/10. Minimum no. of Jumps to reach end of an array.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public int jump(int [] nums){ 3 | int jump=0; 4 | int pos =0; 5 | int des =0 ; 6 | for(int i=0;i pq; 4 | for(int i=0;ik) 10 | pq.pop(); 11 | } 12 | } 13 | return pq.top(); 14 | } -------------------------------------------------------------------------------- /STRINGS/4. Why strings are immutable in Java.txt: -------------------------------------------------------------------------------- 1 | The String is immutable in Java because of the security, synchronization 2 | and concurrency, caching, and class loading. The reason of making string 3 | final is to destroy the immutability and to not allow others to extend it. 4 | The String objects are cached in the String pool, and it makes the String 5 | immutable. -------------------------------------------------------------------------------- /Searching & Sorting/2. Find a Fixed Point (Value equal to index) in a given array.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList < Integer > valueEqualToIndex(int arr[], int n) { 3 | ArrayList < Integer > ans = new ArrayList < Integer > (); 4 | for(int i = 0; i < arr.length; i++) { 5 | if(arr[i] == i + 1) ans.add(i + 1); 6 | } 7 | return ans; 8 | } 9 | } -------------------------------------------------------------------------------- /ARRAYS/1. Reverse Of Array.txt: -------------------------------------------------------------------------------- 1 | class Reverse 2 | { 3 | // Complete the function 4 | // str: input string 5 | public static String reverseWord(String str) 6 | { 7 | String s=""; 8 | // Reverse the string str 9 | for(int i=str.length()-1;i>=0;i--){ 10 | s=s+str.charAt(i); 11 | } 12 | return s; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ARRAYS/27. Find whether an array is a subset of another array.txt: -------------------------------------------------------------------------------- 1 | public String isSubset( long a1[], long a2[], long n, long m) { 2 | HashSetset=new HashSet<>(); 3 | for(long i:a1){ 4 | set.add(i); 5 | } 6 | for(long j:a2){ 7 | if(!set.contains(j)) 8 | return "No"; 9 | } 10 | return "Yes"; 11 | } -------------------------------------------------------------------------------- /Searching & Sorting/7. find majority element.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | int majorityElement(int a[], int n) 4 | { 5 | mapmp; 6 | for(int i=0;i=n/2+1){ 12 | return m.first; 13 | } 14 | } 15 | return -1; 16 | } 17 | }; -------------------------------------------------------------------------------- /ARRAYS/9. Minimise the maximum difference between heights [V.IMP].txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | int getMInDiff(int [] arr, int n, int k){ 3 | if(n==1)return 0; 4 | Arrays.sort(arr); 5 | int diff = arr[n-1]-arr[0]; 6 | int min, max; 7 | for(int i=1;intprofit){ 8 | profit=prices[i]-cur; 9 | } 10 | } 11 | return profit; 12 | } 13 | } -------------------------------------------------------------------------------- /ARRAYS/19. find common elements In 3 sorted arrays.txt: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | static void common(int a[], int b[], int c[]) 3 | { 4 | int i=0,j=0,k=0; 5 | while(i map; 3 | int *a = new int[2]; 4 | for(int i=0;i1){ 9 | a[0]=i; 10 | } 11 | if(map[i]==0){ 12 | a[1]=i; 13 | } 14 | } 15 | return a; -------------------------------------------------------------------------------- /ARRAYS/34. Minimum no. of operations required to make an array palindrome.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int PalinArray(int a[], int n) 4 | { 5 | for(int i=0;i0){ 8 | rev=(rev*10)+temp%10; 9 | temp=temp/10; 10 | } 11 | if(rev!=a[i]){ 12 | return 0; 13 | } 14 | } 15 | return 1; 16 | } 17 | }; -------------------------------------------------------------------------------- /Searching & Sorting/5. Maximum and minimum of an array using minimum number of comparisons.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | int middle(int A, int B, int C){ 3 | if(AB && A>C){ 10 | if(B maxHeap = new PriorityQueue(); 5 | for(int i=l;i<=r;i++){ 6 | maxHeap.add(arr[i]); 7 | } 8 | int ans=0; 9 | for(int i=0;iset=new HashSet<>(); 5 | int sum=0; 6 | set.add(0); 7 | for(int i=0;i=0){ 6 | if(arr[i][j]==0) 7 | { 8 | i++; 9 | } 10 | else{ 11 | index =i; 12 | j--; 13 | } 14 | } 15 | return index; 16 | } 17 | } -------------------------------------------------------------------------------- /ARRAYS/23. find maximum product subarray.txt: -------------------------------------------------------------------------------- 1 | long long maxProduct(vector arr, int n) { 2 | long long mini = arr[0]; 3 | long long maxi = arr[0]; 4 | long long ans = arr[0]; 5 | 6 | for(int i=1; i> sortedMatrix(int N, vector> Mat) { 2 | vector v; 3 | for(int i=0;imax) 7 | max=m[i][c-1]; 8 | } 9 | int desired=(r*c+1)/2; 10 | while(min ha=new HashMap<>(); 5 | for(int i=0;i y) high--; 12 | else low++; 13 | } 14 | } 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /MATRIX/8. Rotate matrix by 90 degrees.txt: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class Main { 3 | static int N = 4; 4 | static void rotate90Clockwise(int arr[][]) 5 | { 6 | for (int j = 0; j < N; j++) 7 | { 8 | for (int i = N - 1; i >= 0; i--) 9 | System.out.print(arr[i][j] + " "); 10 | System.out.println(); 11 | } 12 | } 13 | public static void main(String[] args) 14 | { 15 | int arr[][] = { { 1, 2, 3, 4 }, 16 | { 5, 6, 7, 8 }, 17 | { 9, 10, 11, 12 }, 18 | { 13, 14, 15, 16 } }; 19 | rotate90Clockwise(arr); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ARRAYS/20. Rearrange the array in alternating positive and negative items with O(1) extra space.txt: -------------------------------------------------------------------------------- 1 | public class rearrange{ 2 | static void rearrange(int a[],int b[]){ 3 | int i=0; 4 | int j=n-1; 5 | while(i0 7 | i+=1; 8 | while(j>=0 && a[j]<0) 9 | j-=1; 10 | if(i al = new ArrayList<>(); 4 | public static void main(String[] args) 5 | { 6 | String s = "abcd"; 7 | findsubsequences(s, ""); 8 | System.out.println(al); 9 | } 10 | 11 | private static void findsubsequences(String s, String ans) 12 | { 13 | if (s.length() == 0) { 14 | al.add(ans); 15 | return; 16 | } 17 | findsubsequences(s.substring(1), ans + s.charAt(0)); 18 | findsubsequences(s.substring(1), ans); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /STRINGS/38. String matching where one string contains wildcard characters.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static boolean match(String wild, String pattern) 3 | { 4 | String w = ""; 5 | for(int i =0 ; i< wild.length(); i++) 6 | { 7 | if(wild.charAt(i) == '?') 8 | w+= "[a-z]"; 9 | else if(wild.charAt(i) == '*') 10 | w+= "([a-z]*)*"; 11 | else 12 | w+= wild.charAt(i); 13 | } 14 | return java.util.regex.Pattern.matches(w , pattern); 15 | } 16 | } -------------------------------------------------------------------------------- /ARRAYS/24. Find longest coinsecutive subsequence.txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static int findLongestConseqSubseq(int arr[]) 4 | { 5 | HashSet hs = new HashSet<>(); 6 | for(int i=0;i> Anagrams(String[] str) { 3 | HashMap> map = new HashMap<>(); 4 | for (String s:str) { 5 | char arr[] = s.toCharArray(); 6 | Arrays.sort(arr); 7 | String sort = new String(arr); 8 | if(!map.containsKey(sort)){ 9 | map.put(sort,new LinkedList()); 10 | } 11 | map.get(sort).add(s); 12 | } 13 | return new LinkedList<>(map.values()); 14 | } 15 | } -------------------------------------------------------------------------------- /Searching & Sorting/4. square root of an integer.txt: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static int floorSqrt(int x) 3 | { 4 | if (x == 0 || x == 1) 5 | return x; 6 | long start = 1, end = x / 2, ans = 0; 7 | while (start <= end) { 8 | long mid = (start + end) / 2; 9 | if (mid * mid == x) 10 | return (int)mid; 11 | if (mid * mid < x) { 12 | start = mid + 1; 13 | ans = mid; 14 | } 15 | else 16 | end = mid - 1; 17 | } 18 | return (int)ans; 19 | } 20 | public static void main(String args[]) 21 | { 22 | int x = 11; 23 | System.out.println(floorSqrt(x)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /STRINGS/26. Converting Roman Numerals to Decimal.txt: -------------------------------------------------------------------------------- 1 | public int romanToDecimal(String str) { 2 | HashMap mp=new HashMap<>(); 3 | mp.put('I',1); 4 | mp.put('V',5); 5 | mp.put('X',10); 6 | mp.put('L',50); 7 | mp.put('C',100); 8 | mp.put('D',500); 9 | mp.put('M',1000); 10 | int ans=0,prev=0; 11 | for(int i=str.length()-1;i>=0;i--) 12 | { 13 | if(mp.get(str.charAt(i))>=prev) 14 | ans+=mp.get(str.charAt(i)); 15 | else 16 | ans-=mp.get(str.charAt(i)); 17 | prev=mp.get(str.charAt(i)); 18 | } 19 | return ans; 20 | } -------------------------------------------------------------------------------- /STRINGS/31. Find the longest common subsequence between two strings..txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { static int lcs(int x, int y, String s1, String s2) 3 | { 4 | int [][] dp = new int[x + 1][y + 1]; 5 | for(int i = 1; i <= x; i++){ 6 | for(int j = 1; j <= y; j++){ 7 | if(s1.charAt(i - 1) == s2.charAt(j - 1)){ 8 | dp[i][j] = dp[i - 1][j - 1] + 1; 9 | } else { 10 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 11 | } 12 | } 13 | } 14 | return dp[x][y]; 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /ARRAYS/15. Next Permutation.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void nextPermutation(int[] A) { 3 | if(A==null||A.length<=1)return; 4 | int i=A.length-2; 5 | while(i>=0&&A[i]>=A[i+1])i--; 6 | if(i>=0){ 7 | int j=A.length-1; 8 | while(A[j] <= A[i])j--; 9 | swap(A,i,j); 10 | } 11 | reverse(A,i+1,A.length-1); 12 | } 13 | public void swap(int[] A,int i,int j){ 14 | int temp=A[i]; 15 | A[i]=A[j]; 16 | A[j]=temp; 17 | } 18 | public void reverse(int[] A,int i,int j){ 19 | while(i B ) 4 | { 5 | //code here 6 | if(fun(A,B,0)) return 1; 7 | return 0; 8 | } 9 | 10 | static boolean fun(String s, ArrayList list, int ind){ 11 | if(s.length()==0) return true; 12 | if(ind>=s.length()) return false; 13 | 14 | for (int i=ind;iB[0]){ 6 | e=A[i]; 7 | A[i]=B[0]; 8 | B[0]=e; 9 | int j=0; 10 | while((j+1B[j+1])){ 11 | e=B[j]; 12 | B[j+1]=e; 13 | j++; 14 | } 15 | } 16 | } 17 | } 18 | public static void main(String args[]){ 19 | int a[]={1,2,6,8}; 20 | int b[]={3,5,7}; 21 | int m=a.length; 22 | int n=b.length; 23 | merge(m,n,a,b); 24 | for(int i=0;i 1) 14 | System.out.println((char)(i) + 15 | ", count = " + count[i]); 16 | } 17 | 18 | // Driver Method 19 | public static void main(String[] args) 20 | { 21 | String str = "test string"; 22 | printDups(str); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ARRAYS/22. Find factorial of a large number.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static ArrayList factorial(int N){ 3 | 4 | ArrayList result = new ArrayList(); 5 | 6 | java.math.BigInteger factorial = new java.math.BigInteger("1"); 7 | for (int i = 2; i <= N; i++) { 8 | factorial = factorial.multiply(java.math.BigInteger.valueOf(i)); 9 | } 10 | 11 | String ans = factorial.toString(); 12 | 13 | for (int i = 0; i < ans.length(); i++) { 14 | char c = ans.charAt(i); 15 | result.add(Integer.parseInt(String.valueOf(c))); 16 | } 17 | 18 | return result; 19 | } 20 | } -------------------------------------------------------------------------------- /STRINGS/9. Find Longest Recurring Subsequence in String.txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int LongestRepeatingSubsequence(String str) 4 | { 5 | int n= str.length(); 6 | int [][] dp = new int[n+1][n+1]; 7 | for(int i=0 ; i res = new ArrayList<>(); 4 | if(intervals.length == 0){ 5 | return res.toArray(new int[0][]); 6 | } 7 | Arrays.sort(intervals, (a,b) -> a[0] - b[0]); 8 | int start = intervals[0][0], end = intervals[0][1]; 9 | for(int i[] : intervals){ 10 | if(i[0] <= end){ 11 | end = Math.max(i[1], end); 12 | } 13 | else { 14 | res.add(new int[]{start,end}); 15 | start = i[0]; 16 | end = i[1]; 17 | } 18 | } 19 | res.add(new int[]{start,end}); 20 | return res.toArray(new int[0][]); 21 | } 22 | } -------------------------------------------------------------------------------- /ARRAYS/4. Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo.txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public static void sort012(int a[], int n) 4 | { 5 | int m=0; 6 | int l=0; 7 | int h=n-1; 8 | while(m<=h) 9 | { 10 | if(a[m]==0){ 11 | int temp=a[m]; 12 | a[m]=a[l]; 13 | a[l]=temp; 14 | m++; 15 | l++; 16 | } 17 | else if(a[m]==1){ 18 | m++; 19 | } 20 | else{ 21 | int temp=a[m]; 22 | a[m]=a[h]; 23 | a[h]=temp; 24 | h--; 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /STRINGS/19. KMP Algo.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int lps(String s) { 3 | // code here 4 | int N = s.length(); 5 | int[] lps = new int[N]; 6 | lps[0] = 0; 7 | int len = 0,i=1; 8 | while(i 0) 19 | { 20 | len = lps[len-1]; 21 | } 22 | else 23 | { 24 | lps[i]=0; 25 | i++; 26 | } 27 | } 28 | } 29 | return lps[N-1]; 30 | } 31 | } -------------------------------------------------------------------------------- /STRINGS/14. EDIT Distance [Very Imp].txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int editDistance(String s, String t) { 3 | int x = s.length(); 4 | int y = t.length(); 5 | int[][] dp = new int[x + 1][y + 1]; 6 | for(int i = 0; i <= x; i++) dp[i][0] = i; 7 | for(int j = 0; j <= y; j++) dp[0][j] = j; 8 | for(int i = 1; i <= x; i++) { 9 | for(int j = 1; j <= y; j++) { 10 | if(s.charAt(i - 1) == t.charAt(j - 1)) { 11 | dp[i][j] = dp[i - 1][j - 1]; 12 | } 13 | else { 14 | dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], 15 | Math.min(dp[i][j - 1], dp[i - 1][j])); 16 | } 17 | } 18 | } 19 | return dp[x][y]; 20 | } -------------------------------------------------------------------------------- /ARRAYS/31. Smallest Subarray with sum greater than a given value.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int smallestSubWithSum(int a[], int n, int x) { 3 | int i = 0; 4 | int min = n; 5 | int sum = 0; 6 | int j = 0; 7 | while( i < n){ 8 | if(a[i] > x){ 9 | min = 1; 10 | break; 11 | } 12 | 13 | sum += a[i]; 14 | 15 | if(sum > x){ 16 | 17 | while(sum > x && j < i) 18 | { 19 | min = Math.min(min,i-j+1); 20 | 21 | sum = sum-a[j]; 22 | j++; 23 | } 24 | } 25 | 26 | i++; 27 | } 28 | return min; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /STRINGS/27. Longest Common Prefix.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestCommonPrefix(String[] strs) { 3 | String result = ""; 4 | if (strs.length == 1) 5 | return strs[0]; 6 | for (int i = 0; i < strs[0].length(); i++) { 7 | boolean isEqual = false; 8 | for (int j = 1; j < strs.length; j++) { 9 | if (i < strs[j].length() && strs[0].charAt(i) == strs[j].charAt(i)) 10 | isEqual = true; 11 | else { 12 | isEqual = false; 13 | break; 14 | } 15 | } 16 | if (isEqual) 17 | result += strs[0].charAt(i); 18 | else 19 | break; 20 | } 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /STRINGS/16. Balanced Parenthesis problem.[Imp].txt: -------------------------------------------------------------------------------- 1 | static boolean ispar(String x) 2 | { 3 | // add your code here 4 | Stack stack = new Stack<>(); 5 | 6 | for(int i = 0; i < x.length(); i++){ 7 | char ch = x.charAt(i); 8 | 9 | if(ch == '(' || ch == '{' || ch == '['){ 10 | stack.push(ch); 11 | } 12 | else { 13 | if(stack.isEmpty()) 14 | return false; 15 | 16 | if(stack.peek() == '(' && ch == ')' || stack.peek() == '{' && ch == '}' || stack.peek() == '[' && ch == ']') 17 | stack.pop(); 18 | else 19 | return false; 20 | } 21 | } 22 | 23 | return stack.isEmpty(); 24 | } -------------------------------------------------------------------------------- /BASIC/9. Fibonacci Using Recursion.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 1 5 | Output: 1 6 | Explanation: The first fibonacci 7 | number is 1 8 | 9 | Example 2: 10 | 11 | Input: 12 | n = 20 13 | Output:6765 14 | Explanation: The 20th fibonacci 15 | number is 6765 16 | 17 | Solution: 18 | --------- 19 | 20 | -> 21 | import java.util.Scanner; 22 | public class Main { 23 | public static void main(String[] args) { 24 | Scanner sc=new Scanner(System.in); 25 | int t=sc.nextInt(); 26 | while(t-->0) 27 | { 28 | int n=sc.nextInt(); 29 | System.out.println(new Solution().fibonacci(n)); 30 | } 31 | } 32 | } 33 | 34 | 35 | -> 36 | import java.util.Scanner; 37 | public class Solution { 38 | static int fibonacci(int n) { 39 | if(n<2) { 40 | return n; 41 | } 42 | else return fibonacci(n-1)+fibonacci(n-2); 43 | 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /STRINGS/32. Program to generate all possible valid IP addresses from given string..txt: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | class GFG { 4 | static void solve(String s, int i, int j, int level, String temp, 5 | ArrayListres) 6 | { 7 | if (i == (j + 1) && level == 5) { 8 | res.add(temp.substring(1)); 9 | } 10 | for (int k = i; k < i + 3 && k <= j; k++) { 11 | String ad = s.substring(i, k + 1); 12 | if ((s.charAt(i) == '0'&& ad.length()>1 ) || Integer.valueOf(ad) > 255) 13 | return; 14 | solve(s, k + 1, j, level + 1, temp + '.' + ad, res); 15 | } 16 | } 17 | public static void main(String args[]) 18 | { 19 | String s = "25525511135"; 20 | int n = s.length(); 21 | 22 | ArrayList ans = new ArrayList<>(); 23 | 24 | solve(s, 0, n - 1, 1, "", ans); 25 | 26 | for (String s1 : ans) 27 | System.out.println(s1); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /STRINGS/8. Write a program to find the longest Palindrome in a string.[ Longest palindromic Substring].txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static String longestPalin(String s){ 3 | int n = s.length(); 4 | String longest = ""; 5 | for(int i=0; i i){ 8 | String res = s.substring(i,n-j); 9 | if(checkPalindrome(res)) 10 | longest = (longest.length() >= res.length()) ? longest : res; 11 | } 12 | } 13 | } 14 | return longest; 15 | } 16 | static boolean checkPalindrome(String s){ 17 | int n = s.length(); 18 | for (int i=0; i 17 | package RailwayReservationSystem; 18 | 19 | import java.util.Scanner; 20 | public class Main { 21 | public static void main(String[] args) { 22 | Scanner sc=new Scanner(System.in); 23 | int t=sc.nextInt(); 24 | while(t-->0) 25 | { 26 | int n=sc.nextInt(); 27 | Solution obj=new Solution(); 28 | obj.print1toN(n); 29 | } 30 | } 31 | } 32 | 33 | -> 34 | package RailwayReservationSystem; 35 | 36 | import java.util.Scanner; 37 | 38 | public class Solution { 39 | static void print1toN(int n) { 40 | if(n==0) { 41 | return; 42 | } 43 | System.out.println(n +" "); 44 | print1toN(n-1); 45 | } 46 | } 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /STRINGS/36. Find the smallest window in a string containing all characters of another string.txt: -------------------------------------------------------------------------------- 1 | public static String smallestWindow(String s, String p) 2 | { 3 | int[] count = new int[128]; 4 | int required = p.length(); 5 | int bestLeft = -1; 6 | int minLength = s.length() + 1; 7 | for (final char c : p.toCharArray()) 8 | ++count[c]; 9 | for (int l = 0, r = 0; r < s.length(); ++r) { 10 | if (--count[s.charAt(r)] >= 0) 11 | --required; 12 | while (required == 0) { 13 | if (r - l + 1 < minLength) { 14 | bestLeft = l; 15 | minLength = r - l + 1; 16 | } 17 | if (++count[s.charAt(l++)] > 0) 18 | ++required; 19 | } 20 | } 21 | return bestLeft == -1 ? "-1" : s.substring(bestLeft, bestLeft + minLength); 22 | } -------------------------------------------------------------------------------- /ARRAYS/2. To Find the Minimum and Maximum element in an array.txt: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class GFG { 3 | static void rearrange(int arr[], int n) 4 | { 5 | int j = 0, temp; 6 | for (int i = 0; i < n; i++) { 7 | if (arr[i] < 0) { 8 | if (i != j) { 9 | temp = arr[i]; 10 | arr[i] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | j++; 14 | } 15 | } 16 | } 17 | static void printArray(int arr[], int n) 18 | { 19 | for (int i = 0; i < n; i++) 20 | System.out.print(arr[i] + " "); 21 | } 22 | public static void main(String args[]) 23 | { 24 | int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 }; 25 | int n = arr.length; 26 | rearrange(arr, n); 27 | printArray(arr, n); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ARRAYS/36. Median of 2 sorted arrays of different size.txt: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.Arrays; 3 | public class GFG { 4 | public static int Solution(int[] arr) 5 | { 6 | int n = arr.length; 7 | if (n % 2 == 0) 8 | { 9 | int z = n / 2; 10 | int e = arr[z]; 11 | int q = arr[z - 1]; 12 | 13 | int ans = (e + q) / 2; 14 | return ans; 15 | } 16 | else 17 | { 18 | int z = Math.round(n / 2); 19 | return arr[z]; 20 | } 21 | } 22 | public static void main(String[] args) 23 | { 24 | int[] arr1 = { -5, 3, 6, 12, 15 }; 25 | int[] arr2 = { -12, -10, -6, -3, 4, 10 }; 26 | 27 | int i = arr1.length; 28 | int j = arr2.length; 29 | 30 | int[] arr3 = new int[i + j]; 31 | System.arraycopy(arr1, 0, arr3, 0, i); 32 | System.arraycopy(arr2, 0, arr3, i, j); 33 | Arrays.sort(arr3); 34 | System.out.print("Median = " + Solution(arr3)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /BASIC/6. Sum of Digits of a Number.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 1 5 | Output: 1 6 | Explanation: Sum of digit of 1 is 1. 7 | 8 | Example 2: 9 | 10 | Input: 11 | n = 99999 12 | Output: 45 13 | Explanation: Sum of digit of 99999 is 45. 14 | 15 | Solution: 16 | --------- 17 | -> 18 | package RailwayReservationSystem; 19 | 20 | import java.util.Scanner; 21 | public class Main { 22 | public static void main(String[] args) { 23 | Scanner sc=new Scanner(System.in); 24 | int t=sc.nextInt(); 25 | while(t-->0) 26 | { 27 | int n=sc.nextInt(); 28 | System.out.println(new Solution().sumofdigit(n)); 29 | } 30 | } 31 | } 32 | 33 | -> 34 | package RailwayReservationSystem; 35 | 36 | import java.util.Scanner; 37 | 38 | public class Solution { 39 | static int sumofdigit(int n) { 40 | if(n==0) { 41 | return 0; 42 | } 43 | else 44 | return sumofdigit(n/10)+n%10; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MATRIX/2. Search an element in a matriix.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int binSrch(int [][]arr,int target) 3 | { 4 | int lo=0,hi=arr.length-1,col=arr[0].length-1; 5 | while(lo<=hi) 6 | { 7 | int mid=(lo+hi)/2; 8 | if(arr[mid][0]<=target&&target<=arr[mid][col]) 9 | return mid; 10 | else if(arr[mid][0]>target) 11 | hi=mid-1; 12 | else 13 | lo=mid+1; 14 | } 15 | return 0; 16 | } 17 | public boolean searchMatrix(int[][] matrix, int target) { 18 | int row=matrix.length; 19 | int col=matrix[0].length; 20 | int r=0,c=col-1; 21 | int v=binSrch(matrix,target); 22 | for(int i=0;itarget){ 13 | high=mid-1; 14 | } 15 | else{ 16 | low=mid+1; 17 | } 18 | } 19 | else{ 20 | if(target>nums[mid] && target<=nums[high]){ 21 | low =mid+1; 22 | } 23 | else{ 24 | high =mid-1; 25 | } 26 | } 27 | } 28 | return-1; 29 | } 30 | } -------------------------------------------------------------------------------- /STRINGS/20. Convert a Sentence into its equivalent mobile numeric keypad sequence..txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class GFG 3 | { 4 | static String printSequence(String arr[], String input) 5 | { 6 | String output = ""; 7 | int n = input.length(); 8 | for (int i = 0; i < n; i++) 9 | { 10 | if (input.charAt(i) == ' ') 11 | output = output + "0"; 12 | else 13 | { 14 | int position = input.charAt(i) - 'A'; 15 | output = output + arr[position]; 16 | } 17 | } 18 | return output; 19 | } 20 | public static void main(String[] args) 21 | { 22 | String str[] = {"2","22","222", 23 | "3","33","333", 24 | "4","44","444", 25 | "5","55","555", 26 | "6","66","666", 27 | "7","77","777","7777", 28 | "8","88","888", 29 | "9","99","999","9999" 30 | }; 31 | String input = "GEEKSFORGEEKS"; 32 | System.out.println(printSequence(str, input)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /STRINGS/22. Count All Palindromic Subsequence in a given String..txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | long mod=1000000007; 4 | long[][] dp; 5 | long countPS(String str) 6 | { 7 | // Your code here 8 | int n=str.length(); 9 | dp=new long[n+1][n+1]; 10 | 11 | for(int i=0;i<=n;i++){ 12 | Arrays.fill(dp[i],-1); 13 | } 14 | long ans=countPs(str,0,n-1); 15 | return ans<0?ans+mod:ans; 16 | } 17 | 18 | long countPs(String p,int i,int j){ 19 | if(i>j) return dp[i][j]=0; 20 | if(dp[i][j]!=-1) return dp[i][j]; 21 | if(i==j) return dp[i][j]=1; 22 | 23 | if(p.charAt(i)==p.charAt(j)){ 24 | return dp[i][j]=(1+countPs(p,i,j-1)%mod+countPs(p,i+1,j)%mod)%mod; 25 | }else{ 26 | return dp[i][j]=(countPs(p,i,j-1)%mod+countPs(p,i+1,j)%mod-countPs(p,i+1,j-1)%mod)%mod; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /ARRAYS/26. Maximum profit by buying and selling a share atmost twice.txt: -------------------------------------------------------------------------------- 1 | class Profit { 2 | static int maxProfit(int price[], int n) 3 | { 4 | int profit[] = new int[n]; 5 | for (int i = 0; i < n; i++) 6 | profit[i] = 0; 7 | int max_price = price[n - 1]; 8 | for (int i = n - 2; i >= 0; i--) { 9 | if (price[i] > max_price) 10 | max_price = price[i]; 11 | profit[i] = Math.max(profit[i + 1], 12 | max_price - price[i]); 13 | } 14 | int min_price = price[0]; 15 | for (int i = 1; i < n; i++) { 16 | if (price[i] < min_price) 17 | min_price = price[i]; 18 | profit[i] = Math.max( 19 | profit[i - 1], 20 | profit[i] + (price[i] - min_price)); 21 | } 22 | int result = profit[n - 1]; 23 | return result; 24 | } -------------------------------------------------------------------------------- /STRINGS/29. Find the first repeated word in string..txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | String secFrequent(String arr[], int N){ 3 | HashMap map = new HashMap<>(); 4 | 5 | //get Frequency 6 | for(int i = 0; i < N; i++){ 7 | map.put(arr[i], map.getOrDefault(arr[i], 0)+1); 8 | } 9 | 10 | TreeMap map1 = new TreeMap(); 11 | ArrayList adj = new ArrayList<>(); 12 | 13 | //sort by value using TreeMap 14 | for(String str: map.keySet()){ 15 | String val = str; 16 | int key = map.get(str); 17 | map1.put(key, val); 18 | } 19 | 20 | // Store in ArrayList 21 | for(String str: map1.values()){ 22 | adj.add(str); 23 | } 24 | 25 | //Fetch and return 26 | return adj.get(adj.size() - 2); 27 | } 28 | } -------------------------------------------------------------------------------- /BASIC/13. Power Using Recursion.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 9 p = 9 5 | Output: 387420489 6 | Explanation: 387420489 is the value 7 | obtained when 9 is raised to the 8 | power of 9. 9 | 10 | Example 2: 11 | 12 | Input: 13 | n = 2 p = 9 14 | Output: 512 15 | Explanation: 512 is the value 16 | obtained when 2 is raised to 17 | the power of 9. 18 | 19 | Solution: 20 | --------- 21 | 22 | -> 23 | 24 | import java.util.Scanner; 25 | public class Main { 26 | public static void main(String[] args) { 27 | Scanner sc=new Scanner(System.in); 28 | int t=sc.nextInt(); 29 | while(t-->0) 30 | { 31 | int n=sc.nextInt(); 32 | int p=sc.nextInt(); 33 | System.out.println(new Solution().RecursivePower(n,p)); 34 | } 35 | } 36 | 37 | -> 38 | public class Solution { 39 | public int RecursivePower(int n, int p) { 40 | if(p==0) { 41 | return 1; 42 | } 43 | else 44 | return n*RecursivePower(n,p-1); 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /ARRAYS/6. Find the Union and Intersection of the two sorted arrays..txt: -------------------------------------------------------------------------------- 1 | UNION: 2 | ------ 3 | 4 | class Solution{ 5 | public static int doUnion(int a[], int n, int b[], int m) 6 | { 7 | n=a.length(); 8 | m=b.length(); 9 | Set s=new HashSet<>(); 10 | for(int i=0;i s=new HashSet<>(); 31 | while(ib[j]) 35 | j++; 36 | else{ 37 | s.add(a[i]); 38 | i++; 39 | j++;} 40 | } 41 | return s.size(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /BASIC/7. Count Total Digits in a Number.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 1 5 | Output: 1 6 | Explanation: Number of digit in 1 is 1. 7 | 8 | Example 2: 9 | 10 | Input: 11 | n = 99999 12 | Output: 5 13 | Explanation:Number of digit in 99999 is 5 14 | 15 | Solution: 16 | --------- 17 | -> 18 | package RailwayReservationSystem; 19 | import java.util.Scanner; 20 | public class Main { 21 | public static void main(String[] args) { 22 | Scanner sc=new Scanner(System.in); 23 | int t=sc.nextInt(); 24 | while(t-->0) 25 | { 26 | int n=sc.nextInt(); 27 | System.out.println(new Solution().countofdigit(n)); 28 | } 29 | } 30 | } 31 | 32 | -> 33 | package RailwayReservationSystem; 34 | import java.util.Scanner; 35 | public class Solution { 36 | static int countofdigit(int n) { 37 | int x=0,y,c=0; 38 | if(n/10==0) { 39 | return 1; 40 | } 41 | else 42 | x=x+n%10; 43 | c++; 44 | return c+countofdigit(n/10); 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /ARRAYS/32. Three way partitioning of an array around a given value.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public void threeWayPartition(int array[], int a, int b) 3 | { 4 | int k = 0; 5 | int n = array.length; 6 | 7 | for(int i=0; i b) 28 | { 29 | int temp = array[i]; 30 | array[i] = array[k]; 31 | array[k++] = temp; 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /BASIC/12. Lucky Numbers.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | N = 5 5 | Output: 0 6 | Explanation: 5 is not a lucky number 7 | as it gets deleted in the second 8 | iteration. 9 | 10 | 11 | Example 2: 12 | 13 | Input: 14 | N = 19 15 | Output: 1 16 | Explanation: 19 is a lucky number 17 | 18 | Solution: 19 | --------- 20 | 21 | -> 22 | import java.util.Scanner; 23 | public class Main { 24 | public static void main(String[] args) { 25 | Scanner sc=new Scanner(System.in); 26 | int t=sc.nextInt(); 27 | while(t-->0) 28 | { 29 | Solution obj=new Solution(); 30 | int n=sc.nextInt(); 31 | System.out.println(obj.isLucky(n)? "1" : "0"); 32 | } 33 | } 34 | } 35 | 36 | -> 37 | import java.util.Scanner; 38 | public class Solution { 39 | public static boolean isLucky(int n) { 40 | for (int i=2;i<=n;i++) { 41 | if(n%i==0) { 42 | return false; 43 | } 44 | if(i>n) { 45 | return true; 46 | } 47 | n=n-(n/i); 48 | } 49 | return true; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ARRAYS/16. Count Inversion.txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | long inversionCount(long a[], long n){ 3 | return dividing(0, a.length-1, a); 4 | } 5 | long dividing(int x , int y, long a[]){ 6 | long c=0; 7 | if(x0) 22 | { 23 | int n=sc.nextInt(); 24 | Solution ob=new Solution(); 25 | System.out.println(ob.getFirstSetBit(n)); 26 | } 27 | } 28 | } 29 | 30 | public class Solution { 31 | public static int getFirstSetBit(int n){ 32 | if(n == 0) return 0; 33 | int count = 0; 34 | while(n > 0 && (n & 1) == 0) { 35 | n = n >> 1; 36 | count++; 37 | } 38 | return ++count; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /STRINGS/13. Word Wrap Problem [VERY IMP]..txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int recSol(int i,int rem,int []arr,int k,int n,int dp[][]) 4 | { 5 | if(i == n)return 0; 6 | if(dp[i+1][rem+1] != -1){ 7 | return dp[i+1][rem+1]; 8 | } 9 | int ans; 10 | if(arr[i]>rem){ 11 | ans = (rem+1)*(rem+1)+recSol(i+1,k-arr[i]-1,arr,k,n,dp); 12 | }else{ 13 | int c1 = (rem+1)*(rem+1)+recSol(i+1,k-arr[i]-1,arr,k,n,dp); 14 | int c2 = recSol(i+1,rem-arr[i]-1,arr,k,n,dp); 15 | ans = Math.min(c1,c2); 16 | } 17 | dp[i+1][rem+1] = ans; 18 | return ans; 19 | } 20 | 21 | public int solveWordWrap (int[] nums, int k) 22 | { 23 | int n = nums.length; 24 | 25 | int dp[][] = new int [n+5][k+5]; 26 | for(int i =0;i= 1; i--) 17 | { 18 | right = Integer.max(right, bars[i + 1]); 19 | if (Integer.min(left[i], right) > bars[i]) { 20 | water += Integer.min(left[i], right) - bars[i]; 21 | } 22 | } 23 | return water; 24 | } 25 | public static void main(String[] args) 26 | { 27 | int[] heights = { 7, 0, 4, 2, 5, 0, 6, 4, 0, 5 }; 28 | System.out.print("The maximum amount of water that can be trapped is " + trap(heights)); 29 | } 30 | } -------------------------------------------------------------------------------- /BASIC/3. Check whether K-th bit is set or not.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: N = 4, K = 0 4 | Output: No 5 | Explanation: Binary representation of 4 is 100, 6 | in which 0th bit from LSB is not set. 7 | So, return false. 8 | 9 | Example 2: 10 | 11 | Input: N = 4, K = 2 12 | Output: Yes 13 | Explanation: Binary representation of 4 is 100, 14 | in which 2nd bit from LSB is set. 15 | So, return true. 16 | 17 | Example 3: 18 | 19 | Input: N = 500, K = 3 20 | Output: No 21 | Explanation: Binary representation of 500 is 22 | 111110100, in which 3rd bit from LSB is not set. 23 | So, return false. 24 | 25 | 26 | Solution: 27 | 28 | package Solution; 29 | 30 | import java.util.Scanner; 31 | public class Main { 32 | public static void main(String[] args) { 33 | Scanner sc=new Scanner(System.in); 34 | int t=sc.nextInt(); 35 | while(t-->0) 36 | { 37 | int n=sc.nextInt(); 38 | int k=sc.nextInt(); 39 | if((n&(1<<(k-1)))>0) 40 | System.out.println("YES"); 41 | else 42 | System.out.println("NO"); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /BASIC/11. Josephus problem.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 3 k = 2 5 | Output: 3 6 | Explanation: There are 3 persons so 7 | skipping 1 person i.e 1st person 2nd 8 | person will be killed. Thus the safe 9 | position is 3. 10 | 11 | 12 | Example 2: 13 | 14 | Input: 15 | n = 5 k = 3 16 | Output: 4 17 | Explanation: There are 5 persons so 18 | skipping 2 person i.e 3rd person will 19 | be killed. Thus the safe position is 4. 20 | 21 | Solution: 22 | --------- 23 | 24 | -> 25 | import java.util.Scanner; 26 | public class Main { 27 | public static void main(String[] args) { 28 | Scanner sc=new Scanner(System.in); 29 | int t=sc.nextInt(); 30 | while(t-->0) 31 | { 32 | Solution obj=new Solution(); 33 | int n=sc.nextInt(); 34 | int k=sc.nextInt(); 35 | System.out.println(obj.Josephus(n,k)); 36 | } 37 | } 38 | } 39 | 40 | -> 41 | import java.util.Scanner; 42 | public class Solution { 43 | public int Josephus(int n, int k) { 44 | if(n==1) { 45 | return 1; 46 | } 47 | else 48 | return(Josephus(n-1,k)+k-1)%n+1; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /STRINGS/33. Smallest distinct window.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findSubString( String str) { 3 | HashSet st = new HashSet<>(); 4 | int n = str.length(); 5 | for(int i = 0;i mp = new HashMap<>(); 11 | for(int i = 0;i1){ 19 | mp.put(tmp,mp.get(tmp)-1); 20 | }else{ 21 | mp.remove(tmp); 22 | } 23 | start++; 24 | } 25 | } 26 | } 27 | return ans; 28 | } 29 | } -------------------------------------------------------------------------------- /STRINGS/25. Boyer Moore Algorithm for Pattern Searching..txt: -------------------------------------------------------------------------------- 1 | class AWQ{ 2 | static int NO_OF_CHARS = 256; 3 | static int max (int a, int b) { return (a > b)? a: b; } 4 | static void badCharHeuristic( char []str, int size,int badchar[]) 5 | { 6 | for (int i = 0; i < NO_OF_CHARS; i++) 7 | badchar[i] = -1; 8 | for (int i = 0; i < size; i++) 9 | badchar[(int) str[i]] = i; 10 | } 11 | static void search( char txt[], char pat[]) 12 | { 13 | int m = pat.length; 14 | int n = txt.length; 15 | int badchar[] = new int[NO_OF_CHARS]; 16 | badCharHeuristic(pat, m, badchar); 17 | int s = 0; 18 | while(s <= (n - m)) 19 | { 20 | int j = m-1; 21 | while(j >= 0 && pat[j] == txt[s+j]) 22 | j--; 23 | if (j < 0) 24 | { 25 | System.out.println("Patterns occur at shift = " + s); 26 | s += (s+m < n)? m-badchar[txt[s+m]] : 1; 27 | 28 | } 29 | 30 | else 31 | s += max(1, j - badchar[txt[s+j]]); 32 | } 33 | } 34 | public static void main(String []args) { 35 | 36 | char txt[] = "ABAAABCD".toCharArray(); 37 | char pat[] = "ABC".toCharArray(); 38 | search(txt, pat); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /BASIC/8. Digital Root.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | n = 1 5 | Output: 1 6 | Explanation: Digital root of 1 is 1 7 | 8 | Example 2: 9 | 10 | Input: 11 | n = 99999 12 | Output: 9 13 | Explanation: Sum of digits of 99999 is 45 14 | which is not a single digit number, hence 15 | sum of digit of 45 is 9 which is a single 16 | digit number. 17 | 18 | Solution: 19 | -------- 20 | -> 21 | package RailwayReservationSystem; 22 | 23 | import java.util.Scanner; 24 | public class Main { 25 | public static void main(String[] args) { 26 | Scanner sc=new Scanner(System.in); 27 | int t=sc.nextInt(); 28 | while(t-->0) 29 | { 30 | int n=sc.nextInt(); 31 | System.out.println(new Solution().digitalroot(n)); 32 | } 33 | } 34 | } 35 | 36 | -> 37 | package RailwayReservationSystem; 38 | import java.util.Scanner; 39 | public class Solution { 40 | static int digitalroot(int n) { 41 | int storage = 0; 42 | if(n<10){return n;} 43 | else{storage += n%10 + digitalroot(n/10);} 44 | if(storage<10){return storage;} 45 | else{return (storage%10) + digitalroot(storage/10);} 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ARRAYS/25. Given an array of size n and a number k, fin all elements that appear more than nk times..txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Main 3 | { 4 | public static void morethanNdK(int a[], int n, int k) 5 | { 6 | int x = n / k; 7 | HashMap y = new HashMap<>(); 8 | for (int i = 0; i < n; i++) 9 | { 10 | if (!y.containsKey(a[i])) 11 | y.put(a[i], 1); 12 | else 13 | { 14 | int count = y.get(a[i]); 15 | y.put(a[i], count + 1); 16 | } 17 | } 18 | for (Map.Entry m : y.entrySet()) 19 | { 20 | Integer temp = (Integer)m.getValue(); 21 | if (temp > x) 22 | System.out.println(m.getKey()); 23 | } 24 | } 25 | 26 | // Driver Code 27 | public static void main(String[] args) 28 | { 29 | 30 | int a[] = new int[] { 1, 1, 2, 2, 3, 5, 4, 31 | 2, 2, 3, 1, 1, 1 }; 32 | int n = 12; 33 | int k = 4; 34 | morethanNdK(a, n, k); 35 | } 36 | } -------------------------------------------------------------------------------- /STRINGS/11. Print all the permutations of the given string.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List find_permutation(String S) { 3 | char[] arr = S.toCharArray(); 4 | Arrays.sort(arr); 5 | List ans = new ArrayList<>(); 6 | findPermutationUtil(0,arr.length,arr, ans); 7 | Collections.sort(ans); 8 | return ans; 9 | } 10 | void findPermutationUtil(int idx,int n, char[] arr, List ans){ 11 | if(idx == n){ 12 | ans.add(String.valueOf(arr)); 13 | return; 14 | } 15 | HashSet hset = new HashSet<>(); 16 | for(int i=idx; i 0) { 25 | // if string becomes palindrome then break 26 | if (ispalindrome(s)) { 27 | flag = 1; 28 | break; 29 | } else { 30 | cnt++; 31 | 32 | // erase the last element of the string 33 | s = s.substring(0, s.length() - 1); 34 | //s.erase(s.begin() + s.length() - 1); 35 | } 36 | } 37 | 38 | // print the number of insertion at front 39 | if (flag == 1) { 40 | System.out.println(cnt); 41 | } 42 | } 43 | } 44 | 45 | // This code is contributed by 29AjayKumar 46 | -------------------------------------------------------------------------------- /Searching & Sorting/1. Find first and last positions of an element in a sorted array.txt: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class GFG { 3 | static int first(int arr[], int x, int n) 4 | { 5 | int low = 0, high = n - 1, res = -1; 6 | while (low <= high) { 7 | int mid = (low + high) / 2; 8 | if (arr[mid] > x) 9 | high = mid - 1; 10 | else if (arr[mid] < x) 11 | low = mid + 1; 12 | else { 13 | res = mid; 14 | high = mid - 1; 15 | } 16 | } 17 | return res; 18 | } 19 | static int last(int arr[], int x, int n) 20 | { 21 | int low = 0, high = n - 1, res = -1; 22 | while (low <= high) { 23 | int mid = (low + high) / 2; 24 | if (arr[mid] > x) 25 | high = mid - 1; 26 | else if (arr[mid] < x) 27 | low = mid + 1; 28 | else { 29 | res = mid; 30 | low = mid + 1; 31 | } 32 | } 33 | return res; 34 | } 35 | public static void main(String[] args) 36 | { 37 | int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 }; 38 | int n = arr.length; 39 | int x = 8; 40 | System.out.println("First Occurrence = " 41 | + first(arr, x, n)); 42 | System.out.println("Last Occurrence = " 43 | + last(arr, x, n)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /BASIC/4. Count total set bits.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: N = 4 4 | Output: 5 5 | Explanation: 6 | For numbers from 1 to 4. 7 | For 1: 0 0 1 = 1 set bits 8 | For 2: 0 1 0 = 1 set bits 9 | For 3: 0 1 1 = 2 set bits 10 | For 4: 1 0 0 = 1 set bits 11 | Therefore, the total set bits is 5. 12 | 13 | Example 2: 14 | 15 | Input: N = 17 16 | Output: 35 17 | Explanation: From numbers 1 to 17(both inclusive), 18 | the total number of set bits is 35. 19 | 20 | Solution: 21 | 22 | package Solution; 23 | 24 | import java.util.Scanner; 25 | 26 | public class Solution { 27 | static int findLargestPower(int n) 28 | { 29 | int x = 0; 30 | while ((1 << x) <= n) 31 | x++; 32 | return x - 1; 33 | } 34 | 35 | static int countSetBits(int n) 36 | { 37 | if (n <= 1) 38 | return n; 39 | int x = findLargestPower(n); 40 | return (x * (int)Math.pow(2, (x - 1))) + (n - (int)Math.pow(2, x) + 1) 41 | + countSetBits(n - (int)Math.pow(2, x)); 42 | } 43 | 44 | public static void main(String[] args) 45 | { 46 | Scanner sc=new Scanner(System.in); 47 | int N=sc.nextInt(); 48 | System.out.print(countSetBits(N)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ARRAYS/5. Move all the negative elements to one side of the array.txt: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class GFG{ 3 | static void shiftall(int[] arr, int left, int right) 4 | { 5 | while (left <= right) 6 | { 7 | if (arr[left] < 0 && arr[right] < 0) 8 | left++; 9 | else if (arr[left] > 0 && arr[right] < 0) 10 | { 11 | int temp = arr[left]; 12 | arr[left] = arr[right]; 13 | arr[right] = temp; 14 | left++; 15 | right--; 16 | } 17 | else if (arr[left] > 0 && arr[right] > 0) 18 | right--; 19 | else 20 | { 21 | left++; 22 | right--; 23 | } 24 | } 25 | } 26 | static void display(int[] arr, int right) 27 | { 28 | for(int i = 0; i <= right; ++i) 29 | System.out.print(arr[i] + " "); 30 | System.out.println(); 31 | } 32 | public static void main(String[] args) 33 | { 34 | int[] arr = { -12, 11, -13, -5, 35 | 6, -7, 5, -3, 11 }; 36 | 37 | int arr_size = arr.length; 38 | 39 | // Function Call 40 | shiftall(arr, 0, arr_size - 1); 41 | display(arr, arr_size - 1); 42 | } 43 | } -------------------------------------------------------------------------------- /BASIC/2. Rightmost different bit.txt: -------------------------------------------------------------------------------- 1 | Input: M = 11, N = 9 2 | Output: 2 3 | Explanation: Binary representation of the given 4 | numbers are: 1011 and 1001, 5 | 2nd bit from right is different. 6 | 7 | Input: M = 52, N = 4 8 | Output: 5 9 | Explanation: Binary representation of the given 10 | numbers are: 110100 and 0100, 11 | 5th-bit from right is different. 12 | 13 | --------- 14 | Solution: 15 | 16 | package RailwayReservationSystem; 17 | 18 | import java.util.Scanner; 19 | public class Main { 20 | public static void main(String[] args) { 21 | Scanner sc=new Scanner(System.in); 22 | int t=sc.nextInt(); 23 | while(t-->0) 24 | { 25 | int n=sc.nextInt(); 26 | int m=sc.nextInt(); 27 | Solution ob=new Solution(); 28 | System.out.println(ob.posOfRightMostDiffBit(m ,n)); 29 | } 30 | } 31 | } 32 | 33 | package RailwayReservationSystem; 34 | 35 | public class Solution { 36 | public static int posOfRightMostDiffBit(int m, int n) 37 | { 38 | if(m == n) return -1; 39 | 40 | int count = 1; 41 | while((m & 1) == (n & 1)) { 42 | count++; 43 | m = m >> 1; 44 | n = n >> 1; 45 | } 46 | return count; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /MATRIX/7. Find a specific pair in matrix.txt: -------------------------------------------------------------------------------- 1 | // A Naive method to find maximum value of mat1[d][e] 2 | // - ma[a][b] such that d > a and e > b 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class GFG 7 | { 8 | // The function returns maximum value A(d,e) - A(a,b) 9 | // over all choices of indexes such that both d > a 10 | // and e > b. 11 | static int findMaxValue(int N,int mat[][]) 12 | { 13 | // stores maximum value 14 | int maxValue = Integer.MIN_VALUE; 15 | 16 | // Consider all possible pairs mat[a][b] and 17 | // mat1[d][e] 18 | for (int a = 0; a < N - 1; a++) 19 | for (int b = 0; b < N - 1; b++) 20 | for (int d = a + 1; d < N; d++) 21 | for (int e = b + 1; e < N; e++) 22 | if (maxValue < (mat[d][e] - mat[a][b])) 23 | maxValue = mat[d][e] - mat[a][b]; 24 | 25 | return maxValue; 26 | } 27 | 28 | // Driver code 29 | public static void main (String[] args) 30 | { 31 | int N = 5; 32 | 33 | int mat[][] = { 34 | { 1, 2, -1, -4, -20 }, 35 | { -8, -3, 4, 2, 1 }, 36 | { 3, 8, 6, 1, 3 }, 37 | { -4, -1, 1, 7, -6 }, 38 | { 0, -4, 10, -5, 1 } 39 | }; 40 | 41 | System.out.print("Maximum Value is " + 42 | findMaxValue(N,mat)); 43 | } 44 | } 45 | 46 | // This code is contributed 47 | // by Prakriti Gupta 48 | -------------------------------------------------------------------------------- /MATRIX/6. Maximum size rectangle.txt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int M[][], int n, int m) { 3 | int[] dp = new int[M[0].length]; 4 | Arrays.fill(dp,0); 5 | int maxArea = -1; 6 | for(int i = 0 ; i < M.length; i++){ 7 | for(int j = 0; j < M[0].length; j++){ 8 | dp[j] = M[i][j] == 0 ? 0 : dp[j] + 1; 9 | } 10 | int area = calculateMaxArea(dp); 11 | maxArea = Math.max(area,maxArea); 12 | } 13 | return maxArea; 14 | } 15 | 16 | private int calculateMaxArea(int[] hist){ 17 | Stack st = new Stack<>(); 18 | int i = 0; 19 | int len = hist.length; 20 | int maxArea = -1; 21 | while(i < len){ 22 | if(st.isEmpty() || hist[st.peek()] < hist[i]){ 23 | st.push(i++); 24 | }else{ 25 | int top = st.pop(); 26 | int area = hist[top] * (st.isEmpty() ? i : i - st.peek() -1); 27 | maxArea = Math.max(area,maxArea); 28 | } 29 | } 30 | while(!st.isEmpty()){ 31 | int top = st.pop(); 32 | int area = hist[top] * (st.isEmpty() ? i : i - st.peek() -1); 33 | maxArea = Math.max(area,maxArea); 34 | } 35 | return maxArea; 36 | } 37 | } -------------------------------------------------------------------------------- /MATRIX/10. Common elements in all rows of a given matrix.txt: -------------------------------------------------------------------------------- 1 | // Java Program to prints common element in all 2 | // rows of matrix 3 | import java.util.*; 4 | 5 | class GFG 6 | { 7 | 8 | // Specify number of rows and columns 9 | static int M = 4; 10 | static int N =5; 11 | 12 | // prints common element in all rows of matrix 13 | static void printCommonElements(int mat[][]) 14 | { 15 | 16 | Map mp = new HashMap<>(); 17 | 18 | // initialize 1st row elements with value 1 19 | for (int j = 0; j < N; j++) 20 | mp.put(mat[0][j],1); 21 | 22 | // traverse the matrix 23 | for (int i = 1; i < M; i++) 24 | { 25 | for (int j = 0; j < N; j++) 26 | { 27 | // If element is present in the map and 28 | // is not duplicated in current row. 29 | if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i) 30 | { 31 | // we increment count of the element 32 | // in map by 1 33 | mp.put(mat[i][j], i + 1); 34 | 35 | // If this is last row 36 | if (i == M - 1) 37 | System.out.print(mat[i][j] + " "); 38 | } 39 | } 40 | } 41 | } 42 | 43 | // Driver code 44 | public static void main(String[] args) 45 | { 46 | int mat[][] = 47 | { 48 | {1, 2, 1, 4, 8}, 49 | {3, 7, 8, 5, 1}, 50 | {8, 7, 7, 3, 1}, 51 | {8, 1, 2, 7, 9}, 52 | }; 53 | 54 | printCommonElements(mat); 55 | } 56 | } 57 | 58 | // This code contributed by Rajput-Ji 59 | -------------------------------------------------------------------------------- /STRINGS/21. Minimum number of bracket reversals needed to make an expression balanced..txt: -------------------------------------------------------------------------------- 1 | class Sol 2 | { 3 | public static boolean isOpening(char a){ 4 | return (a=='{'); 5 | } 6 | public static boolean isClosing(char a){ 7 | return (a=='}'); 8 | } 9 | public static boolean isMatching(char a,char b){ 10 | return (a=='{'&&b=='}'); 11 | } 12 | int countRev (String s) 13 | { 14 | Stack stack=new Stack(); 15 | if(s.length()%2==1) 16 | { 17 | return -1; 18 | } 19 | else{ 20 | for(int i=0;i spiralOrder(int[][] matrix) { 3 | List lst = new ArrayList(); 4 | int row = matrix.length; 5 | int col = matrix[0].length; 6 | 7 | if(row==0){//edge case 8 | return lst; 9 | } 10 | 11 | int left=0, right=col-1, top=0, bottom=row-1, direction=0; 12 | 13 | while(left<=right && top<=bottom){ 14 | if(direction==0){ 15 | for(int i=left; i<=right; i++){ 16 | lst.add(matrix[top][i]); 17 | } 18 | direction=1;top++; 19 | } 20 | else if(direction==1){ 21 | for(int i=top; i<=bottom; i++){ 22 | lst.add(matrix[i][right]); 23 | } 24 | direction=2;right--; 25 | } 26 | else if(direction==2){ 27 | for(int i=right; i>=left; i--){ 28 | lst.add(matrix[bottom][i]); 29 | } 30 | direction=3;bottom--; 31 | } 32 | else if(direction==3){ 33 | for(int i=bottom; i>=top; i--){ 34 | lst.add(matrix[i][left]); 35 | } 36 | direction=0;left++; 37 | } 38 | } 39 | return lst; 40 | } 41 | } -------------------------------------------------------------------------------- /BASIC/10. Tower Of Hanoi.txt: -------------------------------------------------------------------------------- 1 | Example 1: 2 | 3 | Input: 4 | N = 2 5 | Output: 6 | move disk 1 from rod 1 to rod 2 7 | move disk 2 from rod 1 to rod 3 8 | move disk 1 from rod 2 to rod 3 9 | 3 10 | Explanation: For N=2 , steps will be 11 | as follows in the example and total 12 | 3 steps will be taken. 13 | 14 | 15 | Example 2: 16 | 17 | Input: 18 | N = 3 19 | Output: 20 | move disk 1 from rod 1 to rod 3 21 | move disk 2 from rod 1 to rod 2 22 | move disk 1 from rod 3 to rod 2 23 | move disk 3 from rod 1 to rod 3 24 | move disk 1 from rod 2 to rod 1 25 | move disk 2 from rod 2 to rod 3 26 | move disk 1 from rod 1 to rod 3 27 | 7 28 | Explanation: For N=3 , steps will be 29 | as follows in the example and total 30 | 7 steps will be taken. 31 | 32 | Solution: 33 | --------- 34 | 35 | -> 36 | import java.util.Scanner; 37 | public class Main { 38 | public static void main(String[] args) { 39 | Scanner sc=new Scanner(System.in); 40 | int t=sc.nextInt(); 41 | while(t-->0) 42 | { 43 | Solution obj=new Solution(); 44 | int n=sc.nextInt(); 45 | System.out.println(obj.Hanoi(n,1,3,2)); 46 | } 47 | } 48 | } 49 | 50 | -> 51 | import java.util.Scanner; 52 | public class Solution { 53 | public int Hanoi(int n, int a, int b, int c) { 54 | if(n==1) { 55 | System.out.println("Move " + n+"from rod "+a+"to "+c); 56 | return 1; 57 | } 58 | int i=Hanoi(n-1,a,b,c); 59 | System.out.println("move "+n+"from "+a+"to "+c); 60 | i=i+Hanoi(n-1,b,c,a); 61 | 62 | return (i+1); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /STRINGS/15. Find next greater number with same set of digits. [Very Very IMP].txt: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static List nextPermutation(int N, int arr[]){ 3 | ArrayList ans = new ArrayList<>(); 4 | 5 | int lastPeek = -1; 6 | 7 | for(int i = N - 2; i >= 0; i--){ 8 | if(arr[i + 1] > arr[i]){ 9 | lastPeek = i + 1; 10 | break; 11 | } 12 | } 13 | 14 | // If there is no peek. 15 | // That is if numbers are arranged in decending order. 16 | // reverse the array 17 | if(lastPeek == -1){ 18 | reverse(arr, 0, N - 1); 19 | }else{ 20 | // Special case: 21 | // find value after peek which is in the range: (arr[lastPeek - 1], arr[lastPeek]) 22 | int index = lastPeek; 23 | for(int i = lastPeek; i < N; i++){ 24 | if(arr[i] > arr[lastPeek - 1] && arr[i] < arr[index]){ 25 | index = i; 26 | } 27 | } 28 | 29 | swap(arr, lastPeek - 1, index); 30 | reverse(arr, lastPeek, N - 1); 31 | } 32 | 33 | 34 | // copy arr 35 | for(int num:arr) ans.add(num); 36 | 37 | return ans; 38 | 39 | } 40 | 41 | static void reverse(int[] arr, int i, int j){ 42 | while(i < j){ 43 | swap(arr, i , j); 44 | i++; 45 | j--; 46 | } 47 | } 48 | 49 | static void swap(int[] arr, int i , int j){ 50 | int temp = arr[i]; 51 | arr[i] = arr[j]; 52 | arr[j] = temp; 53 | } 54 | } -------------------------------------------------------------------------------- /STRINGS/6. Write a Program to check whether a string is a valid shuffle of two strings or not.txt: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Test { 4 | static boolean checkLength(String first, String second, String result) { 5 | if (first.length() + second.length() != result.length()) { 6 | return false; 7 | } 8 | else { 9 | return true; 10 | } 11 | } 12 | static String sortString(String str) { 13 | char[] charArray = str.toCharArray(); 14 | Arrays.sort(charArray); 15 | str = String.valueOf(charArray); 16 | return str; 17 | } 18 | static boolean shuffleCheck(String first, String second, String result) { 19 | first = sortString(first); 20 | second = sortString(second); 21 | result = sortString(result); 22 | int i = 0, j = 0, k = 0; 23 | while (k != result.length()) { 24 | if (i < first.length() && first.charAt(i) == result.charAt(k)) 25 | i++; 26 | else if (j < second.length() && second.charAt(j) == result.charAt(k)) 27 | j++; 28 | else { 29 | return false; 30 | } 31 | k++; 32 | } 33 | if(i < first.length() || j < second.length()) { 34 | return false; 35 | } 36 | return true; 37 | } 38 | 39 | public static void main(String[] args) { 40 | 41 | String first = "XY"; 42 | String second = "12"; 43 | String[] results = {"1XY2", "Y1X2", "Y21XX"}; 44 | for (String result : results) { 45 | if (checkLength(first, second, result) == true && shuffleCheck(first, second, result) == true) { 46 | System.out.println(result + " is a valid shuffle of " + first + " and " + second); 47 | } 48 | else { 49 | System.out.println(result + " is not a valid shuffle of " + first + " and " + second); 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /STRINGS/23. Count of number of given string in 2D character array.txt: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | class GFG{ 4 | static int internalSearch(String needle, int row, 5 | int col, String hay[], 6 | int row_max, int col_max, 7 | int xx) 8 | { 9 | int found = 0; 10 | if (row >= 0 && row <= row_max && col >= 0 && 11 | col <= col_max && xx < needle.length() && 12 | needle.charAt(xx) == hay[row].charAt(col)) 13 | { 14 | char match = needle.charAt(xx); 15 | xx += 1; 16 | hay[row] = hay[row].substring(0, col) + "0" + 17 | hay[row].substring(col + 1); 18 | if (xx == needle.length()) 19 | { 20 | found = 1; 21 | } 22 | else 23 | { 24 | found += internalSearch(needle, row, 25 | col + 1, hay, 26 | row_max, col_max,xx); 27 | found += internalSearch(needle, row, col - 1, 28 | hay, row_max, col_max,xx); 29 | found += internalSearch(needle, row + 1, col, 30 | hay, row_max, col_max,xx); 31 | found += internalSearch(needle, row - 1, col, 32 | hay, row_max, col_max,xx); 33 | } 34 | 35 | hay[row] = hay[row].substring(0, col) + 36 | match + hay[row].substring(col + 1); 37 | } 38 | return found; 39 | } 40 | static int searchString(String needle, int row, int col, 41 | String str[], int row_count, 42 | int col_count) 43 | { 44 | int found = 0; 45 | int r, c; 46 | for(r = 0; r < row_count; ++r) 47 | { 48 | for(c = 0; c < col_count; ++c) 49 | { 50 | found += internalSearch(needle, r, c, str, 51 | row_count - 1, 52 | col_count - 1, 0); 53 | } 54 | } 55 | return found; 56 | } 57 | public static void main(String args[]) 58 | { 59 | String needle = "MAGIC"; 60 | String input[] = { "BBABBM", "CBMBBA", 61 | "IBABBG", "GOZBBI", 62 | "ABBBBC", "MCIGAM" }; 63 | String str[] = new String[input.length]; 64 | int i; 65 | for(i = 0; i < input.length; ++i) 66 | { 67 | str[i] = input[i]; 68 | } 69 | System.out.println("count: " + 70 | searchString(needle, 0, 0, str, 71 | str.length, 72 | str[0].length())); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /STRINGS/24. Search a Word in a 2D Grid of characters..txt: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public int[][] searchWord(char[][] grid, String word) 4 | { 5 | // Code here 6 | ArrayList arr = new ArrayList<>(); 7 | int rn = grid.length; 8 | int cn =grid[0].length; 9 | char character = word.charAt(0); 10 | for(int r =0;r= rn || column >=cn || row<0 || column<0 || grid[row][column]!= rigth){ 32 | return false; 33 | } 34 | 35 | if(word.length()==0){ 36 | return true; 37 | } 38 | 39 | boolean r = check(grid, rn,cn, word.substring(1),row,column+1,word.charAt(1)); 40 | boolean l = check(grid, rn,cn, word.substring(1),row,column-1,word.charAt(1)); 41 | boolean d = check(grid, rn,cn, word.substring(1),row+1,column,word.charAt(1)); 42 | boolean u = check(grid, rn,cn, word.substring(1),row-1,column,word.charAt(1)); 43 | boolean dl = check(grid, rn,cn, word.substring(1),row+1,column+1,word.charAt(1)); 44 | boolean dr = check(grid, rn,cn, word.substring(1),row+1,column-1,word.charAt(1)); 45 | boolean ul = check(grid, rn,cn, word.substring(1),row-1,column+1,word.charAt(1)); 46 | boolean ur = check(grid, rn,cn, word.substring(1),row-1,column-1,word.charAt(1)); 47 | 48 | return false; 49 | 50 | } 51 | } --------------------------------------------------------------------------------