├── Misc ├── README.md ├── MedianOfRunningArray.java ├── PalindromeSinglyLinkedList.java ├── PalindromePrime.java ├── Sparcity.java ├── Sort012D.java ├── matrixTranspose.java ├── TwoSumProblem.java ├── ThreeSumProblem.java ├── RangeInSortedArray.java ├── InverseOfMatrix.java └── ColorContrastRatio.java ├── Others ├── README.md ├── FloydTriangle.java ├── CountChar.java ├── ArrayLeftRotation.java ├── Krishnamurthy.java ├── EulersFunction.java ├── CRC32.java ├── HappyNumbersSeq.java ├── FibbonaciSeries.java ├── RootPrecision.java ├── GuassLegendre.java ├── TowerOfHanoi.java ├── BrianKernighanAlgorithm.java ├── RemoveDuplicateFromString.java ├── BoyerMoore.java ├── StackPostfixNotation.java ├── PasswordGen.java ├── ThreeSum.java ├── CountWords.java ├── InsertDeleteInArray.java ├── TwoPointers.java ├── KMP.java ├── RotateMatriceBy90Degree.java ├── ReverseStackUsingRecursion.java ├── ReturnSubsequence.java ├── LinearCongruentialGenerator.java ├── StringMatchFiniteAutomata.java ├── SieveOfEratosthenes.java ├── RabinKarp.java ├── TopKWords.java ├── PageRank.java ├── Huffman.java ├── BFPRT.java ├── Sudoku.java ├── Damm.java ├── SkylineProblem.java └── MiniMaxAlgorithm.java ├── Searches ├── README.md ├── PerfectBinarySearch.java ├── JumpSearch.java ├── SquareRootBinarySearch.java ├── LinearSearchThread.java ├── ExponentalSearch.java ├── LinearSearch.java ├── HowManyTimesRotated.java ├── UnionFind.java ├── BreadthFirstSearch.java ├── FibonacciSearch.java ├── SaddlebackSearch.java ├── InterpolationSearch.java ├── DepthFirstSearch.java ├── IterativeTernarySearch.java ├── IterativeBinarySearch.java ├── BinarySearch.java ├── UpperBound.java ├── TernarySearch.java ├── LowerBound.java └── QuickSelect.java ├── Strings ├── README.md ├── CharactersSame.java ├── Lower.java ├── Upper.java ├── Alphabetical.java ├── ReverseString.java ├── CheckVowels.java ├── Pangram.java ├── LongestPalindromicSubstring.java ├── CheckAnagrams.java ├── Rotation.java ├── PermuteString.java ├── List_all_Possible_Words_From_Phone_Digits.java ├── Palindrome.java └── WordLadder.java ├── Conversions ├── README.md ├── BinaryToDecimal.java ├── DecimalToOctal.java ├── AnytoAny.java ├── HexaDecimalToBinary.java ├── HexaDecimalToDecimal.java ├── IntegerToRoman.java ├── BinaryToOctal.java ├── DecimalToHexaDecimal.java ├── TurkishToLatinConversion.java ├── OctalToDecimal.java ├── DecimalToBinary.java ├── BinaryToHexadecimal.java ├── RomanToInteger.java ├── OctalToHexadecimal.java ├── AnyBaseToDecimal.java ├── HexToOct.java └── DecimalToAnyBase.java ├── README.md └── CheckVowels.java /Misc/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Others/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Searches/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Strings/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Conversions/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms 🤓 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class FloydTriangle { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 10 | int r = sc.nextInt(), n = 0; 11 | sc.close(); 12 | for (int i = 0; i < r; i++) { 13 | for (int j = 0; j <= i; j++) { 14 | System.out.print(++n + " "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Others/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Enter your text: "); 10 | String str = input.nextLine(); 11 | input.close(); 12 | System.out.println("There are " + CountCharacters(str) + " characters."); 13 | } 14 | 15 | /** 16 | * Count non space character in string 17 | * 18 | * @param str String to count the characters 19 | * @return number of character in the specified string 20 | */ 21 | private static int CountCharacters(String str) { 22 | return str.replaceAll("\\s", "").length(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Others/ArrayLeftRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /* 4 | * A left rotation operation on an array 5 | * shifts each of the array's elements 6 | * given integer n unit to the left. 7 | * 8 | * @author sangin-lee 9 | */ 10 | 11 | public class ArrayLeftRotation { 12 | 13 | /* 14 | * Returns the result of left rotation of given array arr and integer n 15 | * 16 | * @param arr : int[] given array 17 | * 18 | * @param n : int given integer 19 | * 20 | * @return : int[] result of left rotation 21 | */ 22 | public static int[] rotateLeft(int[] arr, int n) { 23 | int size = arr.length; 24 | int[] dst = new int[size]; 25 | n = n % size; 26 | for(int i = 0; i < size; i++) { 27 | dst[i] = arr[n]; 28 | n = (n + 1) % size; 29 | } 30 | return dst; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | */ 8 | class BinaryToDecimal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line arguments 14 | */ 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int binNum, binCopy, d, s = 0, power = 0; 18 | System.out.print("Binary number: "); 19 | binNum = sc.nextInt(); 20 | binCopy = binNum; 21 | while (binCopy != 0) { 22 | d = binCopy % 10; 23 | s += d * (int) Math.pow(2, power++); 24 | binCopy /= 10; 25 | } 26 | System.out.println("Decimal equivalent:" + s); 27 | sc.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | */ 8 | public class DecimalToOctal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line Arguments 14 | */ 15 | 16 | // enter in a decimal value to get Octal output 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n, k, d, s = 0, c = 0; 20 | System.out.print("Decimal number: "); 21 | n = sc.nextInt(); 22 | k = n; 23 | while (k != 0) { 24 | d = k % 8; 25 | s += d * (int) Math.pow(10, c++); 26 | k /= 8; 27 | } 28 | 29 | System.out.println("Octal equivalent:" + s); 30 | sc.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class Krishnamurthy { 6 | 7 | static int fact(int n) { 8 | int i, p = 1; 9 | for (i = n; i >= 1; i--) { 10 | p = p * i; 11 | } 12 | return p; 13 | } 14 | 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int a, b, s = 0; 18 | System.out.print("Enter the number : "); 19 | a = sc.nextInt(); 20 | int n = a; 21 | while (a > 0) { 22 | b = a % 10; 23 | s = s + fact(b); 24 | a = a / 10; 25 | } 26 | if (s == n) { 27 | System.out.print(n + " is a krishnamurthy number"); 28 | } else { 29 | System.out.print(n + " is not a krishnamurthy number"); 30 | } 31 | sc.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | // given a source number , source base, destination base, this code can give you the destination 5 | // number. 6 | // sn ,sb,db ---> ()dn . this is what we have to do . 7 | 8 | public class AnytoAny { 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | int sn = scn.nextInt(); 13 | int sb = scn.nextInt(); 14 | int db = scn.nextInt(); 15 | int m = 1, dec = 0, dn = 0; 16 | while (sn != 0) { 17 | dec = dec + (sn % 10) * m; 18 | m *= sb; 19 | sn /= 10; 20 | } 21 | m = 1; 22 | while (dec != 0) { 23 | dn = dn + (dec % db) * m; 24 | m *= 10; 25 | dec /= db; 26 | } 27 | System.out.println(dn); 28 | scn.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Searches/PerfectBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | class PerfectBinarySearch { 4 | 5 | static int binarySearch(int[] arr, int target) { 6 | int low = 0; 7 | int high = arr.length - 1; 8 | 9 | while (low <= high) { 10 | int mid = (low + high) / 2; 11 | 12 | if (arr[mid] == target) { 13 | return mid; 14 | } else if (arr[mid] > target) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); 25 | int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 26 | assert BinarySearch.binarySearch(array, -1) == -1; 27 | assert BinarySearch.binarySearch(array, 11) == -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class CharactersSame { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | assert isAllCharactersSame(""); 10 | assert !isAllCharactersSame("aab"); 11 | assert isAllCharactersSame("aaa"); 12 | assert isAllCharactersSame("11111"); 13 | } 14 | 15 | /** 16 | * check if all the characters of a string are same 17 | * 18 | * @param s the string to check 19 | * @return {@code true} if all characters of a string are same, otherwise 20 | * {@code false} 21 | */ 22 | public static boolean isAllCharactersSame(String s) { 23 | for (int i = 1, length = s.length(); i < length; ++i) { 24 | if (s.charAt(i) != s.charAt(0)) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Others/EulersFunction.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * You can read more about Euler's totient function 5 | * 6 | *
7 | * See https://en.wikipedia.org/wiki/Euler%27s_totient_function
8 | */
9 | public class EulersFunction {
10 | // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time
11 | // complexity;
12 |
13 | public static int getEuler(int n) {
14 | int result = n;
15 | for (int i = 2; i * i <= n; i++) {
16 | if (n % i == 0) {
17 | while (n % i == 0) {
18 | n /= i;
19 | }
20 | result -= result / i;
21 | }
22 | }
23 | if (n > 1) {
24 | result -= result / n;
25 | }
26 | return result;
27 | }
28 |
29 | public static void main(String[] args) {
30 | for (int i = 1; i < 100; i++) {
31 | System.out.println(getEuler(i));
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Strings/Lower.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | public class Lower {
4 |
5 | /**
6 | * Driver Code
7 | */
8 | public static void main(String[] args) {
9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
10 | for (String s : strings) {
11 | assert toLowerCase(s).equals(s.toLowerCase());
12 | }
13 | }
14 |
15 | /**
16 | * Converts all of the characters in this {@code String} to lower case
17 | *
18 | * @param s the string to convert
19 | * @return the {@code String}, converted to lowercase.
20 | */
21 | public static String toLowerCase(String s) {
22 | char[] values = s.toCharArray();
23 | for (int i = 0; i < values.length; ++i) {
24 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) {
25 | values[i] = Character.toLowerCase(values[i]);
26 | }
27 | }
28 | return new String(values);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Others/CRC32.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.BitSet;
4 |
5 | /**
6 | * Generates a crc32 checksum for a given string or byte array
7 | */
8 | public class CRC32 {
9 |
10 | public static void main(String[] args) {
11 | System.out.println(Integer.toHexString(crc32("Hello World")));
12 | }
13 |
14 | public static int crc32(String str) {
15 | return crc32(str.getBytes());
16 | }
17 |
18 | public static int crc32(byte[] data) {
19 | BitSet bitSet = BitSet.valueOf(data);
20 | int crc32 = 0xFFFFFFFF; // initial value
21 | for (int i = 0; i < data.length * 8; i++) {
22 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) {
23 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
24 | } else {
25 | crc32 = (crc32 << 1);
26 | }
27 | }
28 | crc32 = Integer.reverse(crc32); // result reflect
29 | return crc32 ^ 0xFFFFFFFF; // final xor value
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/Strings/Upper.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | public class Upper {
4 |
5 | /**
6 | * Driver Code
7 | */
8 | public static void main(String[] args) {
9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
10 | for (String s : strings) {
11 | assert toUpperCase(s).equals(s.toUpperCase());
12 | }
13 | }
14 |
15 | /**
16 | * Converts all of the characters in this {@code String} to upper case
17 | *
18 | * @param s the string to convert
19 | * @return the {@code String}, converted to uppercase.
20 | */
21 | public static String toUpperCase(String s) {
22 | if (s == null || "".equals(s)) {
23 | return s;
24 | }
25 | char[] values = s.toCharArray();
26 | for (int i = 0; i < values.length; ++i) {
27 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
28 | values[i] = Character.toUpperCase(values[i]);
29 | }
30 | }
31 | return new String(values);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Others/HappyNumbersSeq.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Scanner;
6 | import java.util.Set;
7 |
8 | public class HappyNumbersSeq {
9 | private static final Set
10 | * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,...
11 | *
12 | *
13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number
14 | *
15 | * Problem Statement: print all Fibonacci numbers that are smaller than your
16 | * given input N
17 | */
18 | public class FibbonaciSeries {
19 |
20 | public static void main(String[] args) {
21 | // Get input from the user
22 | Scanner scan = new Scanner(System.in);
23 | int n = scan.nextInt();
24 | int first = 0, second = 1;
25 | scan.close();
26 | while (first <= n) {
27 | // print first fibo 0 then add second fibo into it while updating second as well
28 | System.out.println(first);
29 | int next = first + second;
30 | first = second;
31 | second = next;
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Others/RootPrecision.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | public class RootPrecision {
6 |
7 | public static void main(String[] args) {
8 | // take input
9 | Scanner scn = new Scanner(System.in);
10 |
11 | // N is the input number
12 | int N = scn.nextInt();
13 |
14 | // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
15 | int P = scn.nextInt();
16 | System.out.println(squareRoot(N, P));
17 |
18 | scn.close();
19 | }
20 |
21 | public static double squareRoot(int N, int P) {
22 | // rv means return value
23 | double rv;
24 |
25 | double root = Math.pow(N, 0.5);
26 |
27 | // calculate precision to power of 10 and then multiply it with root value.
28 | int precision = (int) Math.pow(10, P);
29 | root = root * precision;
30 | /*typecast it into integer then divide by precision and again typecast into double
31 | so as to have decimal points upto P precision */
32 |
33 | rv = (int) root;
34 | return rv / precision;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/Strings/Alphabetical.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /**
4 | * Alphabetical order is a system whereby character strings are placed in order
5 | * based on the position of the characters in the conventional ordering of an
6 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
7 | */
8 | class Alphabetical {
9 |
10 | public static void main(String[] args) {
11 | assert !isAlphabetical("123abc");
12 | assert isAlphabetical("aBC");
13 | assert isAlphabetical("abc");
14 | assert !isAlphabetical("xyzabc");
15 | assert isAlphabetical("abcxyz");
16 | }
17 |
18 | /**
19 | * Check if a string is alphabetical order or not
20 | *
21 | * @param s a string
22 | * @return {@code true} if given string is alphabetical order, otherwise
23 | * {@code false}
24 | */
25 | public static boolean isAlphabetical(String s) {
26 | s = s.toLowerCase();
27 | for (int i = 0; i < s.length() - 1; ++i) {
28 | if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) {
29 | return false;
30 | }
31 | }
32 | return true;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Others/GuassLegendre.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /**
4 | * Guass Legendre Algorithm ref
5 | * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm
6 | *
7 | * @author AKS1996
8 | */
9 | public class GuassLegendre {
10 |
11 | public static void main(String[] args) {
12 | for (int i = 1; i <= 3; ++i) {
13 | System.out.println(pi(i));
14 | }
15 | }
16 |
17 | static double pi(int l) {
18 | /*
19 | * l: No of loops to run
20 | */
21 |
22 | double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
23 | for (int i = 0; i < l; ++i) {
24 | double temp[] = update(a, b, t, p);
25 | a = temp[0];
26 | b = temp[1];
27 | t = temp[2];
28 | p = temp[3];
29 | }
30 |
31 | return Math.pow(a + b, 2) / (4 * t);
32 | }
33 |
34 | static double[] update(double a, double b, double t, double p) {
35 | double values[] = new double[4];
36 | values[0] = (a + b) / 2;
37 | values[1] = Math.sqrt(a * b);
38 | values[2] = t - p * Math.pow(a - values[0], 2);
39 | values[3] = 2 * p;
40 |
41 | return values;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Others/TowerOfHanoi.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | class TowerOfHanoi {
6 |
7 | public static void shift(int n, String startPole, String intermediatePole, String endPole) {
8 | // if n becomes zero the program returns thus ending the loop.
9 | if (n != 0) {
10 | // Shift function is called in recursion for swapping the n-1 disc from the startPole to the
11 | // intermediatePole
12 | shift(n - 1, startPole, endPole, intermediatePole);
13 | System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing
14 | // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole
15 | // to the endPole
16 | shift(n - 1, intermediatePole, startPole, endPole);
17 | }
18 | }
19 |
20 | public static void main(String[] args) {
21 | System.out.print("Enter number of discs on Pole 1: ");
22 | Scanner scanner = new Scanner(System.in);
23 | int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1
24 | shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called
25 | scanner.close();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Strings/ReverseString.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /**
4 | * Reverse String using different version
5 | */
6 | public class ReverseString {
7 |
8 | public static void main(String[] args) {
9 | assert reverse("abc123").equals("321cba");
10 | assert reverse2("abc123").equals("321cba");
11 | }
12 |
13 | /**
14 | * easiest way to reverses the string str and returns it
15 | *
16 | * @param str string to be reversed
17 | * @return reversed string
18 | */
19 | public static String reverse(String str) {
20 | return new StringBuilder(str).reverse().toString();
21 | }
22 |
23 | /**
24 | * second way to reverses the string str and returns it
25 | *
26 | * @param str string to be reversed
27 | * @return reversed string
28 | */
29 | public static String reverse2(String str) {
30 |
31 | if (str == null || str.isEmpty()) {
32 | return str;
33 | }
34 |
35 | char[] value = str.toCharArray();
36 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
37 | char temp = value[i];
38 | value[i] = value[j];
39 | value[j] = temp;
40 | }
41 | return new String(value);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Conversions/HexaDecimalToDecimal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import java.util.Scanner;
4 |
5 | public class HexaDecimalToDecimal {
6 |
7 | // convert hexadecimal to decimal
8 | public static int getHexaToDec(String hex) {
9 | String digits = "0123456789ABCDEF";
10 | hex = hex.toUpperCase();
11 | int val = 0;
12 | for (int i = 0; i < hex.length(); i++) {
13 | int d = digits.indexOf(hex.charAt(i));
14 | val = 16 * val + d;
15 | }
16 | return val;
17 | }
18 |
19 | // Main method gets the hexadecimal input from user and converts it into Decimal output.
20 | public static void main(String args[]) {
21 | String hexa_Input;
22 | int dec_output;
23 | Scanner scan = new Scanner(System.in);
24 |
25 | System.out.print("Enter Hexadecimal Number : ");
26 | hexa_Input = scan.nextLine();
27 |
28 | // convert hexadecimal to decimal
29 | dec_output = getHexaToDec(hexa_Input);
30 | /*
31 | Pass the string to the getHexaToDec function
32 | and it returns the decimal form in the variable dec_output.
33 | */
34 | System.out.println("Number in Decimal: " + dec_output);
35 | scan.close();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/CheckVowels.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * Vowel Count is a system whereby character strings are placed in order based
9 | * on the position of the characters in the conventional ordering of an
10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
11 | */
12 | public class CheckVowels {
13 | private static final Set
7 | * ('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50);
8 | * ('XC',90); ('C', 100); ('D', 500); ('M', 1000);
9 | */
10 | public class IntegerToRoman {
11 |
12 | private static int[] allArabianRomanNumbers
13 | = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
14 | private static String[] allRomanNumbers
15 | = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
16 |
17 | // Value must be > 0
18 | public static String integerToRoman(int num) {
19 | if (num <= 0) {
20 | return "";
21 | }
22 |
23 | StringBuilder builder = new StringBuilder();
24 |
25 | for (int a = 0; a < allArabianRomanNumbers.length; a++) {
26 | int times = num / allArabianRomanNumbers[a];
27 | for (int b = 0; b < times; b++) {
28 | builder.append(allRomanNumbers[a]);
29 | }
30 |
31 | num -= times * allArabianRomanNumbers[a];
32 | }
33 |
34 | return builder.toString();
35 | }
36 |
37 | public static void main(String[] args) {
38 | System.out.println(IntegerToRoman.integerToRoman(2131));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Strings/Pangram.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /**
4 | * Wikipedia: https://en.wikipedia.org/wiki/Pangram
5 | */
6 | public class Pangram {
7 |
8 | /**
9 | * Driver Code
10 | */
11 | public static void main(String[] args) {
12 | assert isPangram("The quick brown fox jumps over the lazy dog");
13 | assert !isPangram("The quick brown fox jumps over the azy dog");
14 | /* not exists l character */
15 | }
16 |
17 | /**
18 | * Check if a string is a pangram string or not
19 | *
20 | * @param s string to check
21 | * @return {@code true} if given string is pangram, otherwise {@code false}
22 | */
23 | public static boolean isPangram(String s) {
24 | boolean[] marked = new boolean[26];
25 | /* by default all letters don't exists */
26 | char[] values = s.toCharArray();
27 | for (char value : values) {
28 | if (Character.isLetter(value)) {
29 | int index = Character.isUpperCase(value) ? value - 'A' : value - 'a';
30 | marked[index] = true;
31 | /* mark current character exists */
32 | }
33 | }
34 |
35 | for (boolean b : marked) {
36 | if (!b) {
37 | return false;
38 | }
39 | }
40 | return true;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Conversions/BinaryToOctal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Converts any Binary number to an Octal Number
7 | *
8 | * @author Zachary Jones
9 | */
10 | public class BinaryToOctal {
11 |
12 | /**
13 | * Main method
14 | *
15 | * @param args Command line arguments
16 | */
17 | public static void main(String args[]) {
18 | Scanner sc = new Scanner(System.in);
19 | System.out.println("Input the binary number: ");
20 | int b = sc.nextInt();
21 | System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
22 | sc.close();
23 | }
24 |
25 | /**
26 | * This method converts a binary number to an octal number.
27 | *
28 | * @param binary The binary number
29 | * @return The octal number
30 | */
31 | public static String convertBinaryToOctal(int binary) {
32 | String octal = "";
33 | int currBit = 0, j = 1;
34 | while (binary != 0) {
35 | int code3 = 0;
36 | for (int i = 0; i < 3; i++) {
37 | currBit = binary % 10;
38 | binary = binary / 10;
39 | code3 += currBit * j;
40 | j *= 2;
41 | }
42 | octal = code3 + octal;
43 | j = 1;
44 | }
45 | return octal;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Conversions/DecimalToHexaDecimal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | // hex = [0 - 9] -> [A - F]
4 | class DecimalToHexaDecimal {
5 |
6 | private static final int sizeOfIntInHalfBytes = 8;
7 | private static final int numberOfBitsInAHalfByte = 4;
8 | private static final int halfByte = 0x0F;
9 | private static final char[] hexDigits = {
10 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
11 | };
12 |
13 | // Returns the hex value of the dec entered in the parameter.
14 | public static String decToHex(int dec) {
15 | StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
16 | hexBuilder.setLength(sizeOfIntInHalfBytes);
17 | for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
18 | int j = dec & halfByte;
19 | hexBuilder.setCharAt(i, hexDigits[j]);
20 | dec >>= numberOfBitsInAHalfByte;
21 | }
22 | return hexBuilder.toString().toLowerCase();
23 | }
24 |
25 | // Test above function.
26 | public static void main(String[] args) {
27 | System.out.println("Test...");
28 | int dec = 305445566;
29 | String libraryDecToHex = Integer.toHexString(dec);
30 | String decToHex = decToHex(dec);
31 | System.out.println("Result from the library : " + libraryDecToHex);
32 | System.out.println("Result decToHex method : " + decToHex);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Conversions/TurkishToLatinConversion.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Converts turkish character to latin character
7 | *
8 | * @author Özgün Gökşenli
9 | */
10 | public class TurkishToLatinConversion {
11 |
12 | /**
13 | * Main method
14 | *
15 | * @param args Command line arguments
16 | */
17 | public static void main(String args[]) {
18 | Scanner sc = new Scanner(System.in);
19 | System.out.println("Input the string: ");
20 | String b = sc.next();
21 | System.out.println("Converted: " + convertTurkishToLatin(b));
22 | sc.close();
23 | }
24 |
25 | /**
26 | * This method converts a turkish character to latin character.
27 | *
28 | * @param param String paramter
29 | * @return String
30 | */
31 | public static String convertTurkishToLatin(String param) {
32 | char[] turkishChars
33 | = new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E};
34 | char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'};
35 | for (int i = 0; i < turkishChars.length; i++) {
36 | param
37 | = param.replaceAll(
38 | new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]}));
39 | }
40 | return param;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Others/BrianKernighanAlgorithm.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * @author Nishita Aggarwal
7 | *
8 | * Brian Kernighan’s Algorithm
9 | *
10 | * algorithm to count the number of set bits in a given number
11 | *
12 | * Subtraction of 1 from a number toggles all the bits (from right to left) till
13 | * the rightmost set bit(including the rightmost set bit). So if we subtract a
14 | * number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the
15 | * rightmost set bit.
16 | *
17 | * If we do n & (n-1) in a loop and count the no of times loop executes we get
18 | * the set bit count.
19 | *
20 | *
21 | * Time Complexity: O(logn)
22 | */
23 | public class BrianKernighanAlgorithm {
24 |
25 | /**
26 | * @param num: number in which we count the set bits
27 | * @return int: Number of set bits
28 | */
29 | static int countSetBits(int num) {
30 | int cnt = 0;
31 | while (num != 0) {
32 | num = num & (num - 1);
33 | cnt++;
34 | }
35 | return cnt;
36 | }
37 |
38 | /**
39 | * @param args : command line arguments
40 | */
41 | public static void main(String args[]) {
42 | Scanner sc = new Scanner(System.in);
43 | int num = sc.nextInt();
44 | int setBitCount = countSetBits(num);
45 | System.out.println(setBitCount);
46 | sc.close();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/Strings/LongestPalindromicSubstring.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | // Longest Palindromic Substring
4 | import java.util.Scanner;
5 |
6 | class LongestPalindromicSubstring {
7 |
8 | public static void main(String[] args) {
9 | Solution s = new Solution();
10 | String str = "";
11 | Scanner sc = new Scanner(System.in);
12 | System.out.print("Enter the string: ");
13 | str = sc.nextLine();
14 | System.out.println("Longest substring is : " + s.longestPalindrome(str));
15 | }
16 | }
17 |
18 | class Solution {
19 |
20 | public String longestPalindrome(String s) {
21 | if (s == null || s.length() == 0) {
22 | return "";
23 | }
24 | int n = s.length();
25 | String maxStr = "";
26 | for (int i = 0; i < n; ++i) {
27 | for (int j = i; j < n; ++j) {
28 | if (isValid(s, i, j) == true) {
29 | if (j - i + 1 > maxStr.length()) { // update maxStr
30 | maxStr = s.substring(i, j + 1);
31 | }
32 | }
33 | }
34 | }
35 | return maxStr;
36 | }
37 |
38 | private boolean isValid(String s, int lo, int hi) {
39 | int n = hi - lo + 1;
40 | for (int i = 0; i < n / 2; ++i) {
41 | if (s.charAt(lo + i) != s.charAt(hi - i)) {
42 | return false;
43 | }
44 | }
45 | return true;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Conversions/OctalToDecimal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Converts any Octal Number to a Decimal Number
7 | *
8 | * @author Zachary Jones
9 | */
10 | public class OctalToDecimal {
11 |
12 | /**
13 | * Main method
14 | *
15 | * @param args Command line arguments
16 | */
17 | public static void main(String args[]) {
18 | Scanner sc = new Scanner(System.in);
19 | System.out.print("Octal Input: ");
20 | String inputOctal = sc.nextLine();
21 | int result = convertOctalToDecimal(inputOctal);
22 | if (result != -1) {
23 | System.out.println("Result convertOctalToDecimal : " + result);
24 | }
25 | sc.close();
26 | }
27 |
28 | /**
29 | * This method converts an octal number to a decimal number.
30 | *
31 | * @param inputOctal The octal number
32 | * @return The decimal number
33 | */
34 | public static int convertOctalToDecimal(String inputOctal) {
35 |
36 | try {
37 | // Actual conversion of Octal to Decimal:
38 | Integer outputDecimal = Integer.parseInt(inputOctal, 8);
39 | return outputDecimal;
40 | } catch (NumberFormatException ne) {
41 | // Printing a warning message if the input is not a valid octal
42 | // number:
43 | System.out.println("Invalid Input, Expecting octal number 0-7");
44 | return -1;
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Misc/MedianOfRunningArray.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import java.util.Collections;
4 | import java.util.PriorityQueue;
5 |
6 | /**
7 | * @author shrutisheoran
8 | */
9 | public class MedianOfRunningArray {
10 |
11 | private PriorityQueue
10 | * Array must be sorted
11 | *
12 | * @author Ujjawal Joshi
13 | * @date 2020.05.18
14 | *
15 | * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12
16 | * Explanation: There is a triplet (12, 3 and 9) present in the array whose sum
17 | * is 24.
18 | */
19 | class ThreeSum {
20 |
21 | public static void main(String args[]) {
22 | Scanner sc = new Scanner(System.in);
23 | int n = sc.nextInt(); // Length of an array
24 |
25 | int a[] = new int[n];
26 |
27 | for (int i = 0; i < n; i++) {
28 | a[i] = sc.nextInt();
29 | }
30 | System.out.println("Target");
31 | int n_find = sc.nextInt();
32 |
33 | Arrays.sort(a); // Sort the array if array is not sorted
34 |
35 | for (int i = 0; i < n; i++) {
36 |
37 | int l = i + 1, r = n - 1;
38 |
39 | while (l < r) {
40 | if (a[i] + a[l] + a[r] == n_find) {
41 | System.out.println(a[i] + " " + a[l] + " " + a[r]);
42 | break;
43 | } // if you want all the triplets write l++;r--; insted of break;
44 | else if (a[i] + a[l] + a[r] < n_find) {
45 | l++;
46 | } else {
47 | r--;
48 | }
49 | }
50 | }
51 |
52 | sc.close();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Misc/PalindromeSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import java.util.Stack;
4 | import com.thealgorithms.datastructures.lists.SinglyLinkedList;
5 |
6 | /**
7 | * A simple way of knowing if a singly linked list is palindrome is to push all
8 | * the values into a Stack and then compare the list to popped vales from the
9 | * Stack.
10 | *
11 | * See more:
12 | * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/
13 | */
14 | public class PalindromeSinglyLinkedList {
15 |
16 | public static void main(String[] args) {
17 | SinglyLinkedList linkedList = new SinglyLinkedList();
18 |
19 | linkedList.insertHead(3);
20 | linkedList.insertNth(2, 1);
21 | linkedList.insertNth(1, 2);
22 | linkedList.insertNth(2, 3);
23 | linkedList.insertNth(3, 4);
24 |
25 | if (isPalindrome(linkedList)) {
26 | System.out.println("It's a palindrome list");
27 | } else {
28 | System.out.println("It's NOT a palindrome list");
29 | }
30 | }
31 |
32 | public static boolean isPalindrome(SinglyLinkedList linkedList) {
33 | boolean ret = true;
34 | Stack
10 | * link: https://www.geeksforgeeks.org/two-pointers-technique/
11 | */
12 | class TwoPointers {
13 |
14 | public static void main(String[] args) {
15 | int[] arr = {10, 20, 35, 50, 75, 80};
16 | int key = 70;
17 | assert isPairedSum(arr, key);
18 | /* 20 + 60 == 70 */
19 |
20 | arr = new int[]{1, 2, 3, 4, 5, 6, 7};
21 | key = 13;
22 | assert isPairedSum(arr, key);
23 | /* 6 + 7 == 13 */
24 |
25 | key = 14;
26 | assert !isPairedSum(arr, key);
27 | }
28 |
29 | /**
30 | * Given a sorted array arr (sorted in ascending order). Find if there
31 | * exists any pair of elements such that their sum is equal to key.
32 | *
33 | * @param arr the array contains elements
34 | * @param key the number to search
35 | * @return {@code true} if there exists a pair of elements, {@code false}
36 | * otherwise.
37 | */
38 | private static boolean isPairedSum(int[] arr, int key) {
39 | /* array sorting is necessary for this algorithm to function correctly */
40 | Arrays.sort(arr);
41 | int i = 0;
42 | /* index of first element */
43 | int j = arr.length - 1;
44 | /* index of last element */
45 |
46 | while (i < j) {
47 | if (arr[i] + arr[j] == key) {
48 | return true;
49 | } else if (arr[i] + arr[j] < key) {
50 | i++;
51 | } else {
52 | j--;
53 | }
54 | }
55 | return false;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Misc/Sparcity.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import java.util.*;
4 |
5 | /*
6 | *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse).
7 | *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse.
8 | *
9 | * @author Ojasva Jain
10 | */
11 |
12 | class Sparcity {
13 |
14 | /*
15 | * @return Sparcity of matrix
16 | *
17 | * where sparcity = number of zeroes/total elements in matrix
18 | *
19 | */
20 | static double sparcity(double[][] mat) {
21 | int zero = 0;
22 | //Traversing the matrix to count number of zeroes
23 | for (int i = 0; i < mat.length; i++) {
24 | for (int j = 0; j < mat[i].length; j++) {
25 | if (mat[i][j] == 0) {
26 | zero++;
27 | }
28 | }
29 | }
30 | //return sparcity
31 | return ((double) zero / (mat.length * mat[1].length));
32 | }
33 |
34 | //Driver method
35 | public static void main(String[] args) {
36 | Scanner in = new Scanner(System.in);
37 | System.out.println("Enter number of rows in matrix: ");
38 | int n = in.nextInt();
39 | System.out.println("Enter number of Columns in matrix: ");
40 | int m = in.nextInt();
41 |
42 | System.out.println("Enter Matrix elements: ");
43 | double[][] mat = new double[n][m];
44 | for (int i = 0; i < n; i++) {
45 | for (int j = 0; j < m; j++) {
46 | mat[i][j] = in.nextDouble();
47 | }
48 | }
49 | System.out.println("Sparcity of matrix is: " + sparcity(mat));
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/Others/KMP.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /**
4 | * Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function
5 | * for an example
6 | */
7 | public class KMP {
8 | // a working example
9 |
10 | public static void main(String[] args) {
11 | final String haystack = "AAAAABAAABA"; // This is the full string
12 | final String needle = "AAAA"; // This is the substring that we want to find
13 | KMPmatcher(haystack, needle);
14 | }
15 |
16 | // find the starting index in string haystack[] that matches the search word P[]
17 | public static void KMPmatcher(final String haystack, final String needle) {
18 | final int m = haystack.length();
19 | final int n = needle.length();
20 | final int[] pi = computePrefixFunction(needle);
21 | int q = 0;
22 | for (int i = 0; i < m; i++) {
23 | while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
24 | q = pi[q - 1];
25 | }
26 |
27 | if (haystack.charAt(i) == needle.charAt(q)) {
28 | q++;
29 | }
30 |
31 | if (q == n) {
32 | System.out.println("Pattern starts: " + (i + 1 - n));
33 | q = pi[q - 1];
34 | }
35 | }
36 | }
37 |
38 | // return the prefix function
39 | private static int[] computePrefixFunction(final String P) {
40 | final int n = P.length();
41 | final int[] pi = new int[n];
42 | pi[0] = 0;
43 | int q = 0;
44 | for (int i = 1; i < n; i++) {
45 | while (q > 0 && P.charAt(q) != P.charAt(i)) {
46 | q = pi[q - 1];
47 | }
48 |
49 | if (P.charAt(q) == P.charAt(i)) {
50 | q++;
51 | }
52 |
53 | pi[i] = q;
54 | }
55 | return pi;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/Conversions/BinaryToHexadecimal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * Converts any Binary Number to a Hexadecimal Number
7 | *
8 | * @author Nishita Aggarwal
9 | */
10 | public class BinaryToHexadecimal {
11 |
12 | /**
13 | * This method converts a binary number to a hexadecimal number.
14 | *
15 | * @param binary The binary number
16 | * @return The hexadecimal number
17 | */
18 | static String binToHex(int binary) {
19 | // hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for
20 | // decimal numbers 0 to 15
21 | HashMap
9 | * For example, if x = 5, The answer should be 2 which is the floor value of √5.
10 | *
11 | * The approach that will be used for solving the above problem is not going to
12 | * be a straight forward Math.sqrt(). Instead we will be using Binary Search to
13 | * find the square root of a number in the most optimised way.
14 | *
15 | * @author sahil
16 | */
17 | public class SquareRootBinarySearch {
18 |
19 | /**
20 | * This is the driver method.
21 | *
22 | * @param args Command line arguments
23 | */
24 | public static void main(String args[]) {
25 | Scanner sc = new Scanner(System.in);
26 | System.out.print("Enter a number you want to calculate square root of : ");
27 | int num = sc.nextInt();
28 | long ans = squareRoot(num);
29 | System.out.println("The square root is : " + ans);
30 | }
31 |
32 | /**
33 | * This function calculates the floor of square root of a number. We use
34 | * Binary Search algorithm to calculate the square root in a more optimised
35 | * way.
36 | *
37 | * @param num Number
38 | * @return answer
39 | */
40 | private static long squareRoot(long num) {
41 | if (num == 0 || num == 1) {
42 | return num;
43 | }
44 | long l = 1;
45 | long r = num;
46 | long ans = 0;
47 | while (l <= r) {
48 | long mid = l + (r - l) / 2;
49 | if (mid == num / mid) {
50 | return mid;
51 | } else if (mid < num / mid) {
52 | ans = mid;
53 | l = mid + 1;
54 | } else {
55 | r = mid - 1;
56 | }
57 | }
58 | return ans;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Misc/Sort012D.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * The array is divided into four sections: a[1..Lo-1] zeroes a[Lo..Mid-1] ones
7 | * a[Mid..Hi] unknown a[Hi+1..N] twos If array [mid] =0, then swap array [mid]
8 | * with array [low] and increment both pointers once. If array [mid] = 1, then
9 | * no swapping is required. Increment mid pointer once. If array [mid] = 2, then
10 | * we swap array [mid] with array [high] and decrement the high pointer once.
11 | * For more information on the Dutch national flag algorithm refer
12 | * https://en.wikipedia.org/wiki/Dutch_national_flag_problem
13 | */
14 | public class Sort012D {
15 |
16 | public static void main(String args[]) {
17 | Scanner np = new Scanner(System.in);
18 | int n = np.nextInt();
19 | int a[] = new int[n];
20 | for (int i = 0; i < n; i++) {
21 | a[i] = np.nextInt();
22 | }
23 | sort012(a);
24 | }
25 |
26 | public static void sort012(int[] a) {
27 | int l = 0;
28 | int h = a.length - 1;
29 | int mid = 0;
30 | int temp;
31 | while (mid <= h) {
32 | switch (a[mid]) {
33 | case 0: {
34 | temp = a[l];
35 | a[l] = a[mid];
36 | a[mid] = temp;
37 | l++;
38 | mid++;
39 | break;
40 | }
41 | case 1:
42 | mid++;
43 | break;
44 | case 2: {
45 | temp = a[mid];
46 | a[mid] = a[h];
47 | a[h] = temp;
48 | h--;
49 | break;
50 | }
51 | }
52 | }
53 | System.out.println("the Sorted array is ");
54 | for (int i = 0; i < a.length; i++) {
55 | System.out.print(+a[i] + " ");
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Others/RotateMatriceBy90Degree.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /**
4 | * Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here
5 | * is the algorithm for this problem .
6 | */
7 | import java.util.*;
8 |
9 | class Rotate_by_90_degree {
10 |
11 | public static void main(String[] args) {
12 | Scanner sc = new Scanner(System.in);
13 | int t = sc.nextInt();
14 |
15 | while (t-- > 0) {
16 | int n = sc.nextInt();
17 | int[][] arr = new int[n][n];
18 |
19 | for (int i = 0; i < n; i++) {
20 | for (int j = 0; j < n; j++) {
21 | arr[i][j] = sc.nextInt();
22 | }
23 | }
24 |
25 | Rotate g = new Rotate();
26 | g.rotate(arr);
27 | printMatrix(arr);
28 | }
29 | sc.close();
30 | }
31 |
32 | static void printMatrix(int arr[][]) {
33 | for (int i = 0; i < arr.length; i++) {
34 | for (int j = 0; j < arr[0].length; j++) {
35 | System.out.print(arr[i][j] + " ");
36 | }
37 | System.out.println("");
38 | }
39 | }
40 | }
41 |
42 | /**
43 | * Class containing the algo to roate matrix by 90 degree
44 | */
45 | class Rotate {
46 |
47 | static void rotate(int a[][]) {
48 | int n = a.length;
49 | for (int i = 0; i < n; i++) {
50 | for (int j = 0; j < n; j++) {
51 | if (i > j) {
52 | int temp = a[i][j];
53 | a[i][j] = a[j][i];
54 | a[j][i] = temp;
55 | }
56 | }
57 | }
58 | int i = 0, k = n - 1;
59 | while (i < k) {
60 | for (int j = 0; j < n; j++) {
61 | int temp = a[i][j];
62 | a[i][j] = a[k][j];
63 | a[k][j] = temp;
64 | }
65 |
66 | i++;
67 | k--;
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Searches/LinearSearchThread.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import java.util.Scanner;
4 |
5 | public class LinearSearchThread {
6 | public static void main(String[] args) {
7 | int[] list = new int[200];
8 | for (int j = 0; j < list.length; j++) {
9 | list[j] = (int) (Math.random() * 100);
10 | }
11 | for (int y : list) {
12 | System.out.print(y + " ");
13 | }
14 | System.out.println();
15 | System.out.print("Enter number to search for: ");
16 | Scanner in = new Scanner(System.in);
17 | int x = in.nextInt();
18 | Searcher t = new Searcher(list, 0, 50, x);
19 | Searcher t1 = new Searcher(list, 50, 100, x);
20 | Searcher t2 = new Searcher(list, 100, 150, x);
21 | Searcher t3 = new Searcher(list, 150, 200, x);
22 | t.start();
23 | t1.start();
24 | t2.start();
25 | t3.start();
26 | try {
27 | t.join();
28 | t1.join();
29 | t2.join();
30 | t3.join();
31 | } catch (InterruptedException e) {
32 | }
33 | boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult();
34 | System.out.println("Found = " + found);
35 | }
36 | }
37 |
38 | class Searcher extends Thread {
39 | private final int[] arr;
40 | private final int left, right;
41 | private final int x;
42 | private boolean found;
43 |
44 | Searcher(int[] arr, int left, int right, int x) {
45 | this.arr = arr;
46 | this.left = left;
47 | this.right = right;
48 | this.x = x;
49 | }
50 |
51 | @Override
52 | public void run() {
53 | int k = left;
54 | found = false;
55 | while (k < right && !found) {
56 | if (arr[k++] == x) {
57 | found = true;
58 | }
59 | }
60 | }
61 |
62 | boolean getResult() {
63 | return found;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/Conversions/AnyBaseToDecimal.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | /**
4 | * @author Varun Upadhyay (https://github.com/varunu28)
5 | */
6 | // Driver program
7 | public class AnyBaseToDecimal {
8 |
9 | public static void main(String[] args) {
10 | assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2);
11 | assert convertToDecimal("777", 8) == Integer.valueOf("777", 8);
12 | assert convertToDecimal("999", 10) == Integer.valueOf("999", 10);
13 | assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16);
14 | assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36);
15 | }
16 |
17 | /**
18 | * Convert any radix to decimal number
19 | *
20 | * @param s the string to be convert
21 | * @param radix the radix
22 | * @return decimal of bits
23 | * @throws NumberFormatException if {@code bits} or {@code radix} is invalid
24 | */
25 | public static int convertToDecimal(String s, int radix) {
26 | int num = 0;
27 | int pow = 1;
28 |
29 | for (int i = s.length() - 1; i >= 0; i--) {
30 | int digit = valOfChar(s.charAt(i));
31 | if (digit >= radix) {
32 | throw new NumberFormatException("For input string " + s);
33 | }
34 | num += valOfChar(s.charAt(i)) * pow;
35 | pow *= radix;
36 | }
37 | return num;
38 | }
39 |
40 | /**
41 | * Convert character to integer
42 | *
43 | * @param c the character
44 | * @return represented digit of given character
45 | * @throws NumberFormatException if {@code ch} is not UpperCase or Digit
46 | * character.
47 | */
48 | public static int valOfChar(char c) {
49 | if (!(Character.isUpperCase(c) || Character.isDigit(c))) {
50 | throw new NumberFormatException("invalid character :" + c);
51 | }
52 | return Character.isDigit(c) ? c - '0' : c - 'A' + 10;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Strings/Rotation.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /**
4 | * Given a string, moving several characters in front of the string to the end
5 | * of the string. For example, move the two characters'a' and 'b' in front of
6 | * the string "abcdef" to the end of the string, so that the original string
7 | * becomes the string "cdefab"
8 | */
9 | public class Rotation {
10 |
11 | public static void main(String[] args) {
12 | assert rotation("abcdef", 2).equals("cdefab");
13 |
14 | char[] values = "abcdef".toCharArray();
15 | rotation(values, 2);
16 | assert new String(values).equals("cdefab");
17 | }
18 |
19 | /**
20 | * Move {@code n} characters in front of given string to the end of string
21 | * time complexity: O(n) space complexity: O(n)
22 | *
23 | * @param s given string
24 | * @param n the total characters to be moved
25 | * @return string after rotation
26 | */
27 | public static String rotation(String s, int n) {
28 | return s.substring(n) + s.substring(0, n);
29 | }
30 |
31 | /**
32 | * Move {@code n} characters in front of given character array to the end of
33 | * array time complexity: O(n) space complexity: O(1)
34 | *
35 | * @param values given character array
36 | * @param n the total characters to be moved
37 | */
38 | public static void rotation(char[] values, int n) {
39 | reverse(values, 0, n - 1);
40 | reverse(values, n, values.length - 1);
41 | reverse(values, 0, values.length - 1);
42 | }
43 |
44 | /**
45 | * Reverse character array
46 | *
47 | * @param values character array
48 | * @param from begin index of given array
49 | * @param to end index of given array
50 | */
51 | public static void reverse(char[] values, int from, int to) {
52 | while (from < to) {
53 | char temp = values[from];
54 | values[from] = values[to];
55 | values[to] = temp;
56 | from++;
57 | to--;
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/Others/ReverseStackUsingRecursion.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /* Program to reverse a Stack using Recursion*/
4 | import java.util.Stack;
5 |
6 | public class ReverseStackUsingRecursion {
7 |
8 | // Stack
9 | private static Stack
13 | * Worst-case performance O(n) Best-case performance O(1) Average performance
14 | * O(n) Worst-case space complexity
15 | *
16 | * @author Varun Upadhyay (https://github.com/varunu28)
17 | * @author Podshivalov Nikita (https://github.com/nikitap492)
18 | * @see BinarySearch
19 | * @see SearchAlgorithm
20 | */
21 | public class LinearSearch implements SearchAlgorithm {
22 |
23 | /**
24 | * Generic Linear search method
25 | *
26 | * @param array List to be searched
27 | * @param value Key being searched for
28 | * @return Location of the key
29 | */
30 | @Override
31 | public
14 | * Note: Giving proper comments in your program makes it more user
15 | * friendly and it is assumed as a high quality code.
16 | *
17 | * @author Rajat-Jain29
18 | * @version 11.0.9
19 | * @since 2014-03-31
20 | */
21 | public class matrixTranspose {
22 |
23 | public static void main(String[] args) {
24 | /*
25 | * This is the main method
26 | *
27 | * @param args Unused.
28 | *
29 | * @return Nothing.
30 | */
31 | Scanner sc = new Scanner(System.in);
32 | int i, j, row, column;
33 | System.out.println("Enter the number of rows in the 2D matrix:");
34 |
35 | /*
36 | * Take input from user for how many rows to be print
37 | */
38 | row = sc.nextInt();
39 |
40 | System.out.println("Enter the number of columns in the 2D matrix:");
41 |
42 | /*
43 | * Take input from user for how many coloumn to be print
44 | */
45 | column = sc.nextInt();
46 | int[][] arr = new int[row][column];
47 | System.out.println("Enter the elements");
48 | for (i = 0; i < row; i++) {
49 | for (j = 0; j < column; j++) {
50 | arr[i][j] = sc.nextInt();
51 | }
52 | }
53 |
54 | /*
55 | * Print matrix before the Transpose in proper way
56 | */
57 | System.out.println("The matrix is:");
58 | for (i = 0; i < row; i++) {
59 | for (j = 0; j < column; j++) {
60 | System.out.print(arr[i][j] + "\t");
61 | }
62 | System.out.print("\n");
63 | }
64 |
65 | /*
66 | * Print matrix after the tranpose in proper way Transpose means Interchanging
67 | * of rows wth column so we interchange the rows in next loop Thus at last
68 | * matrix of transpose is obtained through user input...
69 | */
70 | System.out.println("The Transpose of the given matrix is:");
71 | for (i = 0; i < column; i++) {
72 | for (j = 0; j < row; j++) {
73 | System.out.print(arr[j][i] + "\t");
74 | }
75 | System.out.print("\n");
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Searches/BreadthFirstSearch.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import com.thealgorithms.searches.DepthFirstSearch.Node;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 | import java.util.Objects;
8 | import java.util.Optional;
9 |
10 | /**
11 | * @author: caos321
12 | * @date: 31 October 2021 (Sunday)
13 | */
14 | public class BreadthFirstSearch {
15 |
16 | public static Optional
11 | * we start from bottom left corner if the current element is greater than the
12 | * given element then we move up else we move right Sample Input: 5 5
13 | * ->Dimensions -10 -5 -3 4 9 -6 -2 0 5 10 -4 -1 1 6 12 2 3 7 8 13 100 120 130
14 | * 140 150 140 ->element to be searched output: 4 3 // first value is row,
15 | * second one is column
16 | *
17 | * @author Nishita Aggarwal
18 | */
19 | public class SaddlebackSearch {
20 |
21 | /**
22 | * This method performs Saddleback Search
23 | *
24 | * @param arr The **Sorted** array in which we will search the element.
25 | * @param row the current row.
26 | * @param col the current column.
27 | * @param key the element that we want to search for.
28 | * @return The index(row and column) of the element if found. Else returns
29 | * -1 -1.
30 | */
31 | private static int[] find(int arr[][], int row, int col, int key) {
32 |
33 | // array to store the answer row and column
34 | int ans[] = {-1, -1};
35 | if (row < 0 || col >= arr[row].length) {
36 | return ans;
37 | }
38 | if (arr[row][col] == key) {
39 | ans[0] = row;
40 | ans[1] = col;
41 | return ans;
42 | } // if the current element is greater than the given element then we move up
43 | else if (arr[row][col] > key) {
44 | return find(arr, row - 1, col, key);
45 | }
46 | // else we move right
47 | return find(arr, row, col + 1, key);
48 | }
49 |
50 | /**
51 | * Main method
52 | *
53 | * @param args Command line arguments
54 | */
55 | public static void main(String[] args) {
56 | // TODO Auto-generated method stub
57 | Scanner sc = new Scanner(System.in);
58 | int arr[][];
59 | int i, j, rows = sc.nextInt(), col = sc.nextInt();
60 | arr = new int[rows][col];
61 | for (i = 0; i < rows; i++) {
62 | for (j = 0; j < col; j++) {
63 | arr[i][j] = sc.nextInt();
64 | }
65 | }
66 | int ele = sc.nextInt();
67 | // we start from bottom left corner
68 | int ans[] = find(arr, rows - 1, 0, ele);
69 | System.out.println(ans[0] + " " + ans[1]);
70 | sc.close();
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/Searches/InterpolationSearch.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import static java.lang.String.format;
4 |
5 | import java.util.Arrays;
6 | import java.util.Random;
7 | import java.util.stream.IntStream;
8 |
9 | /**
10 | * Interpolation search algorithm implementation
11 | *
12 | *
13 | * Worst-case performance O(n) Best-case performance O(1) Average performance
14 | * O(log(log(n))) if the elements are uniformly distributed if not O(n)
15 | * Worst-case space complexity O(1)
16 | *
17 | * @author Podshivalov Nikita (https://github.com/nikitap492)
18 | */
19 | class InterpolationSearch {
20 |
21 | /**
22 | * @param array is a sorted array
23 | * @param key is a value what shoulb be found in the array
24 | * @return an index if the array contains the key unless -1
25 | */
26 | public int find(int array[], int key) {
27 | // Find indexes of two corners
28 | int start = 0, end = (array.length - 1);
29 |
30 | // Since array is sorted, an element present
31 | // in array must be in range defined by corner
32 | while (start <= end && key >= array[start] && key <= array[end]) {
33 | // Probing the position with keeping
34 | // uniform distribution in mind.
35 | int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start]));
36 |
37 | // Condition of target found
38 | if (array[pos] == key) {
39 | return pos;
40 | }
41 |
42 | // If key is larger, key is in upper part
43 | if (array[pos] < key) {
44 | start = pos + 1;
45 | } // If key is smaller, x is in lower part
46 | else {
47 | end = pos - 1;
48 | }
49 | }
50 | return -1;
51 | }
52 |
53 | // Driver method
54 | public static void main(String[] args) {
55 | Random r = new Random();
56 | int size = 100;
57 | int maxElement = 100000;
58 | int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray();
59 |
60 | // the element that should be found
61 | Integer shouldBeFound = integers[r.nextInt(size - 1)];
62 |
63 | InterpolationSearch search = new InterpolationSearch();
64 | int atIndex = search.find(integers, shouldBeFound);
65 |
66 | System.out.println(
67 | String.format(
68 | "Should be found: %d. Found %d at index %d. An array length %d",
69 | shouldBeFound, integers[atIndex], atIndex, size));
70 |
71 | int toCheck = Arrays.binarySearch(integers, shouldBeFound);
72 | System.out.println(
73 | format(
74 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Searches/DepthFirstSearch.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Objects;
6 | import java.util.Optional;
7 |
8 | /**
9 | * @author: caos321
10 | * @date: 31 October 2021 (Sunday)
11 | */
12 | public class DepthFirstSearch {
13 |
14 | static class Node {
15 |
16 | private final String name;
17 | private final List
18 | * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average
19 | * performance Θ(log3(N)) Worst-case space complexity O(1)
20 | *
21 | * @author Podshivalov Nikita (https://github.com/nikitap492)
22 | * @see SearchAlgorithm
23 | * @see TernarySearch
24 | * @since 2018-04-13
25 | */
26 | public class IterativeTernarySearch implements SearchAlgorithm {
27 |
28 | @Override
29 | public
18 | * Worst-case performance O(log n) Best-case performance O(1) Average
19 | * performance O(log n) Worst-case space complexity O(1)
20 | *
21 | * @author Gabriele La Greca : https://github.com/thegabriele97
22 | * @author Podshivalov Nikita (https://github.com/nikitap492)
23 | * @see SearchAlgorithm
24 | * @see BinarySearch
25 | */
26 | public final class IterativeBinarySearch implements SearchAlgorithm {
27 |
28 | /**
29 | * This method implements an iterative version of binary search algorithm
30 | *
31 | * @param array a sorted array
32 | * @param key the key to search in array
33 | * @return the index of key in the array or -1 if not found
34 | */
35 | @Override
36 | public
16 | * Poetry about Sieve of Eratosthenes:
17 | *
18 | * Sift the Two's and Sift the Three's:
20 | * The Sieve of Eratosthenes.
22 | * When the multiples sublime,
24 | * The numbers that remain are Prime.
18 | * This is an extension of BinarySearch.
19 | *
20 | *
21 | * Worst-case performance O(log n) Best-case performance O(1) Average
22 | * performance O(log n) Worst-case space complexity O(1)
23 | *
24 | * @author Pratik Padalia (https://github.com/15pratik)
25 | * @see SearchAlgorithm
26 | * @see BinarySearch
27 | */
28 | class UpperBound implements SearchAlgorithm {
29 |
30 | // Driver Program
31 | public static void main(String[] args) {
32 | // Just generate data
33 | Random r = ThreadLocalRandom.current();
34 |
35 | int size = 100;
36 | int maxElement = 100000;
37 |
38 | Integer[] integers
39 | = IntStream.generate(() -> r.nextInt(maxElement))
40 | .limit(size)
41 | .sorted()
42 | .boxed()
43 | .toArray(Integer[]::new);
44 |
45 | // The element for which the upper bound is to be found
46 | int val = integers[r.nextInt(size - 1)] + 1;
47 |
48 | UpperBound search = new UpperBound();
49 | int atIndex = search.find(integers, val);
50 |
51 | System.out.println(
52 | format(
53 | "Val: %d. Upper Bound Found %d at index %d. An array length %d",
54 | val, integers[atIndex], atIndex, size));
55 |
56 | boolean toCheck = integers[atIndex] > val || integers[size - 1] < val;
57 | System.out.println(
58 | format(
59 | "Upper Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck));
60 | }
61 |
62 | /**
63 | * @param array is an array where the UpperBound value is to be found
64 | * @param key is an element for which the UpperBound is to be found
65 | * @param
18 | * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average
19 | * performance Θ(log3(N)) Worst-case space complexity O(1)
20 | *
21 | * @author Podshivalov Nikita (https://github.com/nikitap492)
22 | * @see SearchAlgorithm
23 | * @see IterativeBinarySearch
24 | */
25 | public class TernarySearch implements SearchAlgorithm {
26 |
27 | /**
28 | * @param arr The **Sorted** array in which we will search the element.
29 | * @param value The value that we want to search for.
30 | * @return The index of the element if found. Else returns -1.
31 | */
32 | @Override
33 | public
18 | * This is an extension of BinarySearch.
19 | *
20 | *
21 | * Worst-case performance O(log n) Best-case performance O(1) Average
22 | * performance O(log n) Worst-case space complexity O(1)
23 | *
24 | * @author Pratik Padalia (https://github.com/15pratik)
25 | * @see SearchAlgorithm
26 | * @see BinarySearch
27 | */
28 | class LowerBound implements SearchAlgorithm {
29 |
30 | // Driver Program
31 | public static void main(String[] args) {
32 | // Just generate data
33 | Random r = ThreadLocalRandom.current();
34 |
35 | int size = 100;
36 | int maxElement = 100000;
37 |
38 | Integer[] integers
39 | = IntStream.generate(() -> r.nextInt(maxElement))
40 | .limit(size)
41 | .sorted()
42 | .boxed()
43 | .toArray(Integer[]::new);
44 |
45 | // The element for which the lower bound is to be found
46 | int val = integers[r.nextInt(size - 1)] + 1;
47 |
48 | LowerBound search = new LowerBound();
49 | int atIndex = search.find(integers, val);
50 |
51 | System.out.println(
52 | format(
53 | "Val: %d. Lower Bound Found %d at index %d. An array length %d",
54 | val, integers[atIndex], atIndex, size));
55 |
56 | boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val;
57 | System.out.println(
58 | format(
59 | "Lower Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck));
60 | }
61 |
62 | /**
63 | * @param array is an array where the LowerBound value is to be found
64 | * @param key is an element for which the LowerBound is to be found
65 | * @param
15 | * Calling this function might change the order of elements in {@code list}.
16 | *
17 | * @param list the list of elements
18 | * @param n the index
19 | * @param Find the Transpose of Matrix!
9 | *
10 | * Simply take input from the user and print the matrix before the transpose and
11 | * after the transpose.
12 | *
13 | * > BruteForce(int[] nums, int target) {
26 | List
> arr = new ArrayList
>();
27 |
28 | for (int i = 0; i < nums.length; i++) {
29 | for (int j = i + 1; j < nums.length; j++) {
30 | for (int k = j + 1; k < nums.length; k++) {
31 | if (nums[i] + nums[j] + nums[k] == target) {
32 | List
>(new LinkedHashSet
>(arr));
44 | return arr;
45 | }
46 |
47 | public List
> TwoPointer(int[] nums, int target) {
48 | Arrays.sort(nums);
49 | List
> arr = new ArrayList
>();
50 | int start = 0;
51 | int end = 0;
52 | int i = 0;
53 | while (i < nums.length - 1) {
54 | start = i + 1;
55 | end = nums.length - 1;
56 | while (start < end) {
57 | if (nums[start] + nums[end] + nums[i] == target) {
58 | List
> set = new LinkedHashSet
>(arr);
75 | return new ArrayList
>(set);
76 | }
77 |
78 | public List
> Hashmap(int[] nums, int target) {
79 | Arrays.sort(nums);
80 | Set
> ts = new HashSet();
81 | HashMap