├── .gitignore
├── ConceptOfTheDay
├── Java
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── org
│ │ └── redquark
│ │ └── conceptoftheday
│ │ ├── AnagramSubstringSearch.java
│ │ ├── KadaneAlgorithm.java
│ │ ├── Knapsack.java
│ │ └── MaximumSumOfKElements.java
├── JavaScript
│ ├── package-lock.json
│ ├── package.json
│ └── src
│ │ ├── anagram_substring_search.js
│ │ ├── kadane_algorithm.js
│ │ ├── knapsack.js
│ │ └── maximum_sum_of_k_elements.js
├── Kotlin
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle
│ └── src
│ │ └── main
│ │ └── java
│ │ └── org
│ │ └── redquark
│ │ └── conceptoftheday
│ │ ├── AnagramSubstringSearch.kt
│ │ ├── KadaneAlgorithm.kt
│ │ ├── Knapsack.kt
│ │ └── MaximuSumOfKElements.kt
└── Python
│ ├── setup.py
│ └── src
│ ├── anagram_substring_search.py
│ ├── kadane_algorithm.py
│ ├── knapsack.py
│ └── maximum_sum_of_k_elements.py
├── Design
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── org
│ │ └── redquark
│ │ └── tutorials
│ │ └── design
│ │ └── caching
│ │ ├── LFUCache.java
│ │ └── LRUCache.java
│ └── test
│ └── java
│ └── org
│ └── redquark
│ └── tutorials
│ └── design
│ └── caching
│ ├── LFUCacheTest.java
│ └── LRUCacheTest.java
├── LICENSE
├── LeetCode
├── Java
│ ├── build.gradle
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle
│ └── src
│ │ └── main
│ │ └── java
│ │ └── org
│ │ └── redquark
│ │ └── tutorials
│ │ └── leetcode
│ │ ├── AddTwoNumbers.java
│ │ ├── ContainerWithMostWater.java
│ │ ├── DivideTwoIntegers.java
│ │ ├── FindFirstAndLastPositionOfElementInSortedArray.java
│ │ ├── FourSum.java
│ │ ├── GenerateParentheses.java
│ │ ├── ImplementStrStr.java
│ │ ├── IntegerToRoman.java
│ │ ├── LetterCombinationsOfAPhoneNumber.java
│ │ ├── LongestCommonPrefix.java
│ │ ├── LongestPalindromicSubstring.java
│ │ ├── LongestSubstringWithoutRepeatingCharacters.java
│ │ ├── LongestValidParentheses.java
│ │ ├── MedianOfTwoSortedArrays.java
│ │ ├── MergeKSortedLists.java
│ │ ├── MergeTwoSortedLists.java
│ │ ├── NextPermutation.java
│ │ ├── PalindromeNumber.java
│ │ ├── RegularExpressionMatching.java
│ │ ├── RemoveDuplicatesFromSortedArray.java
│ │ ├── RemoveElement.java
│ │ ├── RemoveNthNodeFromEndOfList.java
│ │ ├── ReverseInteger.java
│ │ ├── ReverseNodesInKGroup.java
│ │ ├── RomanToInteger.java
│ │ ├── SearchInRotatedSortedArray.java
│ │ ├── StringToInteger.java
│ │ ├── SubstringWithConcatenationOfAllWords.java
│ │ ├── SwapNodesInPairs.java
│ │ ├── ThreeSum.java
│ │ ├── ThreeSumClosest.java
│ │ ├── TwoSum.java
│ │ ├── ValidParentheses.java
│ │ └── ZigZagConversion.java
├── JavaScript
│ ├── package-lock.json
│ ├── package.json
│ └── src
│ │ ├── add_two_numbers.js
│ │ ├── container_with_most_water.js
│ │ ├── divide_two_integers.js
│ │ ├── find_first_and_last_position_of_element_in_sorted_array.js
│ │ ├── four_sum.js
│ │ ├── generate_parentheses.js
│ │ ├── implement_strstr.js
│ │ ├── integer_to_roman.js
│ │ ├── letter_combinations_of_a_phone_number.js
│ │ ├── longest_common_prefix.js
│ │ ├── longest_palindromic_substring.js
│ │ ├── longest_substring_without_repeating_characters.js
│ │ ├── longest_valid_parentheses.js
│ │ ├── median_of_two_sorted_arrays.js
│ │ ├── merge_k_sorted_lists.js
│ │ ├── merge_two_sorted_lists.js
│ │ ├── next_permutation.js
│ │ ├── palindrome_number.js
│ │ ├── regular_expression_matching.js
│ │ ├── remove_duplicates_from_sorted_array.js
│ │ ├── remove_element.js
│ │ ├── remove_nth_node_from_end_of_list.js
│ │ ├── reverse_integer.js
│ │ ├── reverse_nodes_in_k_group.js
│ │ ├── roman_to_integer.js
│ │ ├── search_in_rotated_sorted_array.js
│ │ ├── string_to_integer.js
│ │ ├── substring_with_concatenation_of_all_words.js
│ │ ├── swap_nodes_in_pairs.js
│ │ ├── three_sum.js
│ │ ├── three_sum_closest.js
│ │ ├── two_sum.js
│ │ ├── valid_parentheses.js
│ │ └── zigzag_conversion.js
├── Kotlin
│ ├── build.gradle.kts
│ ├── gradle.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ │ └── main
│ │ └── kotlin
│ │ └── org
│ │ └── redquark
│ │ └── tutorials
│ │ └── leetcode
│ │ ├── AddTwoNumbers.kt
│ │ ├── ContainerWithMostWater.kt
│ │ ├── DivideTwoIntegers.kt
│ │ ├── FindFirstAndLastPositionOfElementInSortedArray.kt
│ │ ├── FourSum.kt
│ │ ├── GenerateParentheses.kt
│ │ ├── ImplementStrStr.kt
│ │ ├── IntegerToRoman.kt
│ │ ├── LetterCombinationsOfAPhoneNumber.kt
│ │ ├── LongestCommonPrefix.kt
│ │ ├── LongestPalindromeSubstring.kt
│ │ ├── LongestSubstringWithoutRepeatingCharacters.kt
│ │ ├── LongestValidParentheses.kt
│ │ ├── MedianOfTwoSortedArrays.kt
│ │ ├── MergeKSortedLists.kt
│ │ ├── MergeTwoSortedLists.kt
│ │ ├── NextPermutation.kt
│ │ ├── PalindromeNumber.kt
│ │ ├── RegularExpressionMatching.kt
│ │ ├── RemoveDuplicatesFromSortedArray.kt
│ │ ├── RemoveElement.kt
│ │ ├── RemoveNthNodeFromEndOfList.kt
│ │ ├── ReverseInteger.kt
│ │ ├── ReverseNodesInKGroup.kt
│ │ ├── RomanToInteger.kt
│ │ ├── SearchInRotatedSortedArray.kt
│ │ ├── StringToInteger.kt
│ │ ├── SubstringWithConcatenationOfAllWords.kt
│ │ ├── SwapNodesInPairs.kt
│ │ ├── ThreeSum.kt
│ │ ├── ThreeSumClosest.kt
│ │ ├── TwoSum.kt
│ │ ├── ValidParentheses.kt
│ │ └── ZigZagConversion.kt
└── Python
│ ├── setup.py
│ └── src
│ ├── Add_Two_Numbers.py
│ ├── Container_With_Most_Water.py
│ ├── Divide_Two_Integers.py
│ ├── Find_First_And_Last_Position_Of_Element_In_Sorted_Array.py
│ ├── Four_Sum.py
│ ├── Generate_Parentheses.py
│ ├── Implement_StrStr.py
│ ├── Integer_To_Roman.py
│ ├── Letter_Combinations_Of_A_Phone_Number.py
│ ├── Longest_Common_Prefix.py
│ ├── Longest_Palindromic_Substring.py
│ ├── Longest_Substring_Without_Repeating_Characters.py
│ ├── Longest_Valid_Parentheses.py
│ ├── Median_Of_Two_Sorted_Arrays.py
│ ├── Merge_K_Sorted_Lists.py
│ ├── Merge_Two_Sorted_Lists.py
│ ├── Next_Permutation.py
│ ├── Palindrome_Number.py
│ ├── Regular_Expression_Matching.py
│ ├── Remove_Duplicates_From_Sorted_Array.py
│ ├── Remove_Element.py
│ ├── Remove_Nth_Node_From_End_Of_List.py
│ ├── Reverse_Integer.py
│ ├── Reverse_Nodes_In_K_Group.py
│ ├── Roman_To_Integer.py
│ ├── Search_In_Rotated_Sorted_Array.py
│ ├── String_To_Integer.py
│ ├── Substring_With_Concatenation_Of_All_Words.py
│ ├── Swap_Nodes_In_Pairs.py
│ ├── Three_Sum.py
│ ├── Three_Sum_Closest.py
│ ├── Two_Sum.py
│ ├── Valid_Parentheses.py
│ └── ZigZag_Conversion.py
├── ProblemSolving
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
│ └── main
│ └── java
│ └── org
│ └── redquark
│ └── tutorials
│ └── problemsolving
│ └── bitmagic
│ ├── BitDifference.java
│ ├── CheckEvenOrOdd.java
│ ├── CheckKthBit.java
│ ├── CheckOppositeSign.java
│ ├── CountSetBitsInANumber.java
│ ├── CountTotalSetBits.java
│ ├── FindFirstSetBit.java
│ ├── GeneratePowerSet.java
│ ├── LongestConsecutive1s.java
│ ├── MaximumSubsetXOR.java
│ ├── PowerOf4And8.java
│ ├── PowerOfTwo.java
│ ├── ReverseBits.java
│ ├── RightMostDifferentBit.java
│ ├── RotateBits.java
│ ├── SetKthBit.java
│ ├── SingleNumber.java
│ ├── SparseNumber.java
│ ├── SwapEvenOddBits.java
│ └── ToggleBitsInRange.java
├── README.md
└── Snippets
└── JavaScript
├── emails
├── index.js
└── sendEmail.js
├── files
├── deleteFile.js
├── index.js
├── readFile.js
├── sample-text-file.txt
└── writeFile.js
├── index.js
├── jobs
├── cronJob..js
└── index.js
├── package-lock.json
└── package.json
/ConceptOfTheDay/Java/src/main/java/org/redquark/conceptoftheday/KadaneAlgorithm.java:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class KadaneAlgorithm {
7 |
8 | private static int maximumSum(int[] a) {
9 | if (a == null || a.length == 0) {
10 | return 0;
11 | }
12 | int globalMaximum = a[0];
13 | int localMaximum = a[0];
14 | for (int i = 1; i < a.length; i++) {
15 | localMaximum = Math.max(a[i], a[i] + localMaximum);
16 | if (globalMaximum < localMaximum) {
17 | globalMaximum = localMaximum;
18 | }
19 | }
20 | return globalMaximum;
21 | }
22 |
23 | public static void main(String[] args) {
24 | int[] a = new int[]{-2, -3, 4, -1, -2, 1, 5, -3};
25 | System.out.println("Maximum sum: " + maximumSum(a));
26 |
27 | a = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
28 | System.out.println("Maximum sum: " + maximumSum(a));
29 |
30 | a = new int[]{0, 1, 2, -2, 3, 2};
31 | System.out.println("Maximum sum: " + maximumSum(a));
32 |
33 | a = new int[]{-2, 2, 5, -11, 6};
34 | System.out.println("Maximum sum: " + maximumSum(a));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Java/src/main/java/org/redquark/conceptoftheday/Knapsack.java:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class Knapsack {
7 |
8 | public static int getMaximumValue(int W, int n, int[] weights, int[] values) {
9 | // Create the lookup table
10 | int[][] lookup = new int[n + 1][W + 1];
11 | // Solve for each case
12 | for (int i = 0; i <= n; i++) {
13 | for (int j = 0; j <= W; j++) {
14 | // Base condition - no item, no capacity
15 | if (i == 0 || j == 0) {
16 | lookup[i][j] = 0;
17 | }
18 | // If we include the i-th item
19 | else if (weights[i - 1] <= j) {
20 | lookup[i][j] = Math.max(values[i - 1] + lookup[i - 1][j - weights[i - 1]], lookup[i - 1][j]);
21 | }
22 | // If we have out of the capacity
23 | else {
24 | lookup[i][j] = lookup[i - 1][j];
25 | }
26 | }
27 | }
28 | return lookup[n][W];
29 | }
30 |
31 | public static void main(String[] args) {
32 | int[] weights = new int[]{10, 20, 30};
33 | int[] values = new int[]{60, 100, 120};
34 | int W = 50;
35 | int n = weights.length;
36 | System.out.println("Maximum value: " + getMaximumValue(W, n, weights, values));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Java/src/main/java/org/redquark/conceptoftheday/MaximumSumOfKElements.java:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | *
6 | * Find maximum sum of k consecutive elements in the array
7 | */
8 | public class MaximumSumOfKElements {
9 |
10 | private static int findMaximumSum(int[] a, int k) {
11 | int n = a.length;
12 | // Current sum - sum of the current window
13 | int currentSum = 0;
14 | // Maximum sum - maximum sum of k consecutive elements in an array
15 | int maximumSum = 0;
16 | // Find the sum of first k elements
17 | for (int i = 0; i < k; i++) {
18 | currentSum += a[i];
19 | }
20 | // At this point, maximum and current sum will be same
21 | maximumSum = currentSum;
22 | // Loop for the remaining elements by sliding the window
23 | for (int i = k; i < n; i++) {
24 | // Discard the left most element
25 | currentSum -= a[i - k];
26 | // Included the current element
27 | currentSum += a[i];
28 | if (maximumSum < currentSum) {
29 | maximumSum = currentSum;
30 | }
31 | }
32 | return maximumSum;
33 | }
34 |
35 | public static void main(String[] args) {
36 | int[] a = {1, 4, 2, 10, 2, 3, 1, 0, 20};
37 | int k = 4;
38 | System.out.println("Maximum sum: " + findMaximumSum(a, k));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "JavaScript",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "lodash": {
8 | "version": "4.17.19",
9 | "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz",
10 | "integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ=="
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "JavaScript",
3 | "version": "1.0.0",
4 | "description": "Programming concepts implemented in JavaScript",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "keywords": [],
10 | "author": "Anirudh Sharma",
11 | "license": "ISC",
12 | "dependencies": {
13 | "lodash": "^4.17.19"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/src/anagram_substring_search.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharna
3 | */
4 | function find_indices(s, p) {
5 | // Set of indices
6 | let result = [];
7 | // Build a hash of the letters.
8 | let wordHash = {}; // Master copy.
9 | let hash = {}; // Current copy.
10 | p.split('').forEach(function (letter) {
11 | wordHash[letter] = wordHash[letter] ? wordHash[letter] + 1 : 1;
12 | hash[letter] = hash[letter] ? hash[letter] + 1 : 1;
13 | });
14 |
15 | let count = 0;
16 | let index = -1;
17 |
18 | for (let i = 0; i < s.length; i++) {
19 | let letter = s[i];
20 | if (hash[letter]) {
21 | // Part or start of an anagram.
22 | if (index === -1) {
23 | index = i;
24 | }
25 | hash[letter]--;
26 | count++;
27 | if (count === p.length) {
28 | // Completed an anagram.
29 | result.push(index);
30 |
31 | // Reset variables.
32 | hash[s[index]]++;
33 |
34 | count = p.length - 1;
35 | index++;
36 | }
37 | }
38 | else {
39 | // Reset variables.
40 | if (index !== -1 && hash[letter] !== undefined && (p.length <= s.length - index)) {
41 | // Find first occurrence of 'letter'. Set the starting point 'index' to next letter.
42 | for (var j = index; j < i; j++) {
43 | index++;
44 | if (s[j] === letter) {
45 | break;
46 | }
47 | else {
48 | hash[s[j]]++;
49 | count--;
50 | }
51 | }
52 | }
53 | else {
54 | // Restore hash and counter.
55 | let keys = Object.keys(hash);
56 | for (let j = 0; j < keys.length; j++) {
57 | hash[keys[j]] = wordHash[keys[j]];
58 | }
59 | count = 0;
60 | index = -1;
61 | }
62 | }
63 | }
64 | return result;
65 | }
66 |
67 |
68 | let text = "BACDGABCDA";
69 | let pattern = "ABCD";
70 | console.log("Anagrams found at: " + find_indices(text, pattern));
71 |
72 | text = "XYYZXZYZXXYZ";
73 | pattern = "XYZ";
74 | console.log("Anagrams found at: " + find_indices(text, pattern));
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/src/kadane_algorithm.js:
--------------------------------------------------------------------------------
1 | function maximum_sum(a) {
2 | if (!a || a.length == 0) {
3 | return 0;
4 | }
5 | let localMaximum = a[0];
6 | let globalMaximum = a[0];
7 | for(let i = 0; i < a.length; i++) {
8 | localMaximum = Math.max(a[i], localMaximum + a[i]);
9 | if(globalMaximum < localMaximum) {
10 | globalMaximum = localMaximum;
11 | }
12 | }
13 | return globalMaximum;
14 | }
15 |
16 | a = [-2, -3, 4, -1, -2, 1, 5, -3];
17 | console.log(maximum_sum(a));
18 |
19 | a = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
20 | console.log(maximum_sum(a));
21 |
22 | a = [0, 1, 2, -2, 3, 2];
23 | console.log(maximum_sum(a));
24 |
25 | a = [-2, 2, 5, -11, 6];
26 | console.log(maximum_sum(a));
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/src/knapsack.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 |
5 | function getMaximumValue(W, n, weights, values) {
6 | // Lookup table
7 | let lookup = Array.from(Array(n + 1), () => new Array(W + 1))
8 | // Check for each case
9 | for (let i = 0; i <= n; i++) {
10 | for (let j = 0; j <= W; j++) {
11 | // Base condition - no item, no capacity
12 | if (i == 0 || j == 0) {
13 | lookup[i][j] = 0;
14 | }
15 | // If we consider the i-th element
16 | else if (weights[i - 1] <= j) {
17 | lookup[i][j] = Math.max(values[i - 1] + lookup[i - 1][j - weights[i - 1]], lookup[i - 1][j]);
18 | }
19 | // For all other cases, get the values from previous row
20 | else {
21 | lookup[i][j] = lookup[i - 1][j];
22 | }
23 | }
24 | }
25 | return lookup[n][W];
26 | }
27 |
28 | function create2DArray(rows, columns) {
29 | let lookup = [];
30 | }
31 |
32 | const weights = [10, 20, 30];
33 | const values = [60, 100, 120];
34 | const W = 50;
35 | const n = weights.length;
36 |
37 | console.log("Maximum value: " + getMaximumValue(W, n, weights, values));
--------------------------------------------------------------------------------
/ConceptOfTheDay/JavaScript/src/maximum_sum_of_k_elements.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 | function find_maximum_sum(a, k) {
5 | const n = a.length;
6 | // Current sum - sum of the current window
7 | let current_sum = 0;
8 | // Maximum sum - maximum sum of k consecutive elements in an array
9 | let maximum_sum = 0;
10 | // Find the sum of first k elements
11 | for (let i = 0; i < k; i++) {
12 | current_sum += a[i];
13 | }
14 | // At this point, maximum and current sum will be same
15 | maximum_sum = current_sum;
16 | // Loop for the remaining elements by sliding the window
17 | for (let i = k; i < n; i++) {
18 | // Discard the left most element
19 | current_sum -= a[i - k];
20 | // Included the current element
21 | current_sum += a[i];
22 | if (maximum_sum < current_sum) {
23 | maximum_sum = current_sum;
24 | }
25 | }
26 | return maximum_sum;
27 | }
28 |
29 | const a = [1, 4, 2, 10, 2, 3, 1, 0, 20];
30 | const k = 4;
31 | console.log("Maximum sum: " + find_maximum_sum(a, k));
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.jetbrains.kotlin.jvm' version '1.3.72'
3 | }
4 |
5 | group 'org.redquark.conceptoftheday'
6 | version '1.0-SNAPSHOT'
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
14 | }
15 |
16 | compileKotlin {
17 | kotlinOptions.jvmTarget = "1.8"
18 | }
19 | compileTestKotlin {
20 | kotlinOptions.jvmTarget = "1.8"
21 | }
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Kotlin'
2 |
3 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/AnagramSubstringSearch.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | *
6 | * We are given two strings "text" and "pattern" of size n and m respectively where m < n.
7 | * Find all the indices in text where anagrams of pattern are found.
8 | */
9 | private fun findIndices(text: String, pattern: String): List {
10 | // Lengths of strings
11 | val n = text.length
12 | val m = pattern.length
13 | // List that will store the indices
14 | val indices: MutableList = ArrayList()
15 | // Frequency arrays - assuming we have a set of 256 characters
16 | val textCount = IntArray(256)
17 | val patternCount = IntArray(256)
18 | // Loop until m
19 | for (i in 0 until m) {
20 | textCount[text[i].toInt()]++
21 | patternCount[pattern[i].toInt()]++
22 | }
23 | // At this point, we have traversed m characters in both the arrays.
24 | // Now we will loop through the remaining characters
25 | for (i in m until n) {
26 | // Check if the counts of characters in frequency arrays are equal or not
27 | if (isCountEqual(textCount, patternCount)) {
28 | indices.add(i - m)
29 | }
30 | // Discard left most character
31 | textCount[text[i - m].toInt()]--
32 | // Include current character
33 | textCount[text[i].toInt()]++
34 | }
35 | // Check for the last window
36 | if (isCountEqual(textCount, patternCount)) {
37 | indices.add(n - m)
38 | }
39 | return indices
40 | }
41 |
42 | private fun isCountEqual(textCount: IntArray, patternCount: IntArray): Boolean {
43 | for (i in 0..255) {
44 | if (textCount[i] != patternCount[i]) {
45 | return false
46 | }
47 | }
48 | return true
49 | }
50 |
51 | fun main() {
52 | var text = "BACDGABCDA"
53 | var pattern = "ABCD"
54 | println("Anagrams are found at: " + findIndices(text, pattern))
55 |
56 | text = "XYYZXZYZXXYZ"
57 | pattern = "XYZ"
58 | println("Anagrams are found at: " + findIndices(text, pattern))
59 | }
60 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/KadaneAlgorithm.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday
2 |
3 | import kotlin.math.max
4 |
5 | fun maximumSum(a: IntArray): Int {
6 | if (a.isEmpty()) {
7 | return 0
8 | }
9 | var globalMaximum = a[0]
10 | var localMaximum = a[0]
11 | for (i in 1 until a.size) {
12 | localMaximum = max(a[i], localMaximum + a[i])
13 | if (globalMaximum < localMaximum) {
14 | globalMaximum = localMaximum
15 | }
16 | }
17 | return globalMaximum
18 | }
19 |
20 | fun main() {
21 | var a = intArrayOf(-2, -3, 4, -1, -2, 1, 5, -3)
22 | println("Maximum sum: " + maximumSum(a))
23 |
24 | a = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)
25 | println("Maximum sum: " + maximumSum(a))
26 |
27 | a = intArrayOf(0, 1, 2, -2, 3, 2)
28 | println("Maximum sum: " + maximumSum(a))
29 |
30 | a = intArrayOf(-2, 2, 5, -11, 6)
31 | println("Maximum sum: " + maximumSum(a))
32 | }
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/Knapsack.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday
2 |
3 | import kotlin.math.max
4 |
5 | /**
6 | * @author Anirudh Sharma
7 | */
8 |
9 | fun getMaximumValue(W: Int, n: Int, weights: IntArray, values: IntArray): Int {
10 | // Lookup table
11 | val lookup = Array(n + 1) { i -> Array(W + 1) { j -> 0 } }
12 | // Loop for each case
13 | for (i in 0..n) {
14 | for (j in 0..W) {
15 | // Base condition - no item, no capacity
16 | if (i == 0 || j == 0) {
17 | lookup[i][j] = 0
18 | }
19 | // For the i-th element
20 | else if (weights[i - 1] <= j) {
21 | lookup[i][j] = max(values[i - 1] + lookup[i - 1][j - weights[i - 1]], lookup[i - 1][j])
22 | }
23 | // For all other cases take value from the previous row
24 | else {
25 | lookup[i][j] = lookup[i - 1][j]
26 | }
27 | }
28 | }
29 | return lookup[n][W]
30 | }
31 |
32 | fun main() {
33 | val weights = intArrayOf(10, 20, 30)
34 | val values = intArrayOf(60, 100, 120)
35 | val W = 50
36 | val n = weights.size
37 | println("Maximum sum: " + getMaximumValue(W, n, weights, values))
38 | }
--------------------------------------------------------------------------------
/ConceptOfTheDay/Kotlin/src/main/java/org/redquark/conceptoftheday/MaximuSumOfKElements.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.conceptoftheday
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | fun findMaximumSum(a: IntArray, k: Int): Int {
7 | val n = a.size
8 | // Current sum - sum of the current window
9 | var currentSum = 0
10 | // Maximum sum - maximum sum of k consecutive elements in an array
11 | var maximumSum: Int
12 | // Find the sum of first k elements
13 | for (i in 0 until k) {
14 | currentSum += a[i]
15 | }
16 | // At this point, maximum and current sum will be same
17 | maximumSum = currentSum
18 | // Loop for the remaining elements by sliding the window
19 | for (i in k until n) {
20 | // Discard the left most element
21 | currentSum -= a[i - k]
22 | // Included the current element
23 | currentSum += a[i]
24 | if (maximumSum < currentSum) {
25 | maximumSum = currentSum
26 | }
27 | }
28 | return maximumSum
29 | }
30 |
31 | fun main() {
32 | val a = intArrayOf(1, 4, 2, 10, 2, 3, 1, 0, 20)
33 | val k = 4
34 | println("Maximum sum: " + findMaximumSum(a, k))
35 | }
36 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Python/setup.py:
--------------------------------------------------------------------------------
1 | project_info = ["name - Concept Of The Day",
2 | "version = 1.0",
3 | "description = Programming concepts implemented in Python",
4 | "author = Anirudh Sharma",
5 | "author_email = anirudh03sharma@gmail.com",
6 | "repo = https://github.com/ani03sha/ConceptOfTheDay",
7 | ]
8 |
9 | print(project_info)
10 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Python/src/anagram_substring_search.py:
--------------------------------------------------------------------------------
1 | """
2 | @author Anirudh Sharma
3 | """
4 |
5 |
6 | def isCountEqual(text_count, pattern_count):
7 | for i in range(0, 256):
8 | if text_count[i] != pattern_count[i]:
9 | return False
10 | return True
11 |
12 |
13 | def find_indices(text, patten):
14 | # Lengths of input strings
15 | n = len(text)
16 | m = len(patten)
17 | # list that will store the indices
18 | indices = []
19 | # Frequency arrays - assuming we have a set of 256 characters
20 | text_count = [0] * 256
21 | pattern_count = [0] * 256
22 | # Loop for the first m characters
23 | for i in range(0, m):
24 | text_count[ord(text[i])] += 1
25 | pattern_count[ord(patten[i])] += 1
26 | # At this point, we have traversed m characters in both the arrays.
27 | # Now we will loop through the remaining characters
28 | for i in range(m, n):
29 | # Check if the counts of characters in frequency arrays are equal or not
30 | if isCountEqual(text_count, pattern_count):
31 | indices.append(i - m)
32 | # Discard the left most character
33 | text_count[ord(text[i - m])] -= 1
34 | # Include the current character
35 | text_count[ord(text[i])] += 1
36 | # For the last window
37 | if isCountEqual(text_count, pattern_count):
38 | indices.append(n - m)
39 | return indices
40 |
41 |
42 | text = "BACDGABCDA"
43 | pattern = "ABCD"
44 | print(str(find_indices(text, pattern))[1:-1])
45 |
46 | text = "XYYZXZYZXXYZ"
47 | pattern = "XYZ"
48 | print(str(find_indices(text, pattern))[1:-1])
49 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Python/src/kadane_algorithm.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def maximum_sum(a):
7 | if a is None or len(a) == 0:
8 | return 0
9 | global_maximum = a[0]
10 | local_maximum = a[0]
11 | for i in range(1, len(a)):
12 | local_maximum = max(a[i], local_maximum + a[i])
13 | if global_maximum < local_maximum:
14 | global_maximum = local_maximum
15 | return global_maximum
16 |
17 |
18 | a = [-2, -3, 4, -1, -2, 1, 5, -3]
19 | print(maximum_sum(a))
20 |
21 | a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
22 | print(maximum_sum(a))
23 |
24 | a = [0, 1, 2, -2, 3, 2]
25 | print(maximum_sum(a))
26 |
27 | a = [-2, 2, 5, -11, 6]
28 | print(maximum_sum(a))
29 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Python/src/knapsack.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def get_maximum_value(W, n, weights, values):
7 | # Lookup table for memoization
8 | lookup = [[0 for i in range(W + 1)] for j in range(n + 1)]
9 | # Loop for items
10 | for i in range(n + 1):
11 | for j in range(W + 1):
12 | # Base condition - no item, no capacity
13 | if i == 0 or j == 0:
14 | lookup[i][j] = 0
15 | # For the i-th item
16 | elif weights[i - 1] <= j:
17 | lookup[i][j] = max(values[i - 1] + lookup[i - 1][j - weights[i - 1]], lookup[i - 1][j])
18 | # Take the values from the previous row
19 | else:
20 | lookup[i][j] = lookup[i - 1][j]
21 | return lookup[n][W]
22 |
23 |
24 | weights = [10, 20, 30]
25 | values = [60, 100, 120]
26 | W = 50
27 | n = len(weights)
28 |
29 | print("Maximum value: ", get_maximum_value(W, n, weights, values))
30 |
--------------------------------------------------------------------------------
/ConceptOfTheDay/Python/src/maximum_sum_of_k_elements.py:
--------------------------------------------------------------------------------
1 | """
2 | @author Anirudh Sharma
3 | """
4 |
5 |
6 | def find_maximum_sum(a, k):
7 | n = len(a)
8 | # Current sum - sum of the current window
9 | current_sum = 0
10 | # Maximum sum - maximum sum of k consecutive elements in an array
11 | maximum_sum = 0
12 | # Find the sum of first k elements
13 | for i in range(0, k):
14 | current_sum += a[i]
15 | # At this point, maximum and current sum will be same
16 | maximum_sum = current_sum
17 | # Loop for the remaining elements by sliding the window
18 | for i in range(k, n):
19 | # Discard the left most element
20 | current_sum -= a[i - k]
21 | # Include the current element
22 | current_sum += a[i]
23 | if maximum_sum < current_sum:
24 | maximum_sum = current_sum
25 | return maximum_sum
26 |
27 |
28 | a = [1, 4, 2, 10, 2, 3, 1, 0, 20]
29 | k = 4
30 | print("Maximum sum:", find_maximum_sum(a, k))
31 |
--------------------------------------------------------------------------------
/Design/src/test/java/org/redquark/tutorials/design/caching/LFUCacheTest.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.design.caching;
2 |
3 | import org.junit.jupiter.api.BeforeEach;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.assertEquals;
7 | import static org.junit.jupiter.api.Assertions.assertFalse;
8 | import static org.junit.jupiter.api.Assertions.assertNotNull;
9 | import static org.junit.jupiter.api.Assertions.assertNull;
10 | import static org.junit.jupiter.api.Assertions.assertTrue;
11 |
12 | public class LFUCacheTest {
13 |
14 | private LFUCache lfuCache;
15 |
16 | @BeforeEach
17 | public void setUp() {
18 | this.lfuCache = new LFUCache<>(5);
19 | this.lfuCache.set(1, "One");
20 | this.lfuCache.set(2, "Two");
21 | this.lfuCache.set(3, "Three");
22 | }
23 |
24 | @Test
25 | public void testHas() {
26 | assertTrue(lfuCache.has(3));
27 | assertTrue(lfuCache.has(1));
28 | assertFalse(lfuCache.has(4));
29 | assertTrue(lfuCache.has(2));
30 | assertFalse(lfuCache.has(5));
31 | }
32 |
33 | @Test
34 | public void testGet() {
35 | assertEquals("One", lfuCache.get(1));
36 | assertEquals("Two", lfuCache.get(2));
37 | assertEquals("Three", lfuCache.get(3));
38 | assertNull(lfuCache.get(4));
39 | assertNull(lfuCache.get(5));
40 | }
41 |
42 | @Test
43 | public void testSet() {
44 | lfuCache.set(4, "Four");
45 | lfuCache.set(5, "Five");
46 | assertEquals("One", lfuCache.get(1));
47 | lfuCache.set(6, "Six");
48 | assertNotNull(lfuCache.get(1));
49 | assertNull(lfuCache.get(2));
50 | assertEquals("Five", lfuCache.get(5));
51 | }
52 |
53 | @Test
54 | public void testInvalidate() {
55 | assertEquals("One", lfuCache.get(1));
56 | assertEquals("Two", lfuCache.get(2));
57 | assertEquals("Three", lfuCache.get(3));
58 | assertTrue(lfuCache.invalidate());
59 | assertFalse(lfuCache.has(1));
60 | assertFalse(lfuCache.has(2));
61 | assertFalse(lfuCache.has(3));
62 | }
63 | }
--------------------------------------------------------------------------------
/Design/src/test/java/org/redquark/tutorials/design/caching/LRUCacheTest.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.design.caching;
2 |
3 | import org.junit.jupiter.api.BeforeEach;
4 | import org.junit.jupiter.api.Test;
5 |
6 | import static org.junit.jupiter.api.Assertions.assertEquals;
7 | import static org.junit.jupiter.api.Assertions.assertFalse;
8 | import static org.junit.jupiter.api.Assertions.assertNull;
9 | import static org.junit.jupiter.api.Assertions.assertTrue;
10 |
11 | public class LRUCacheTest {
12 |
13 | private LRUCache lruCache;
14 |
15 | @BeforeEach
16 | public void setUp() {
17 | this.lruCache = new LRUCache<>(5);
18 | this.lruCache.set(1, "One");
19 | this.lruCache.set(2, "Two");
20 | this.lruCache.set(3, "Three");
21 | }
22 |
23 | @Test
24 | public void testHas() {
25 | assertTrue(lruCache.has(3));
26 | assertTrue(lruCache.has(1));
27 | assertFalse(lruCache.has(4));
28 | assertTrue(lruCache.has(2));
29 | assertFalse(lruCache.has(5));
30 | }
31 |
32 | @Test
33 | public void testGet() {
34 | assertEquals("One", lruCache.get(1));
35 | assertEquals("Two", lruCache.get(2));
36 | assertEquals("Three", lruCache.get(3));
37 | assertNull(lruCache.get(4));
38 | assertNull(lruCache.get(5));
39 | }
40 |
41 | @Test
42 | public void testSet() {
43 | lruCache.set(4, "Four");
44 | lruCache.set(5, "Five");
45 | lruCache.set(6, "Six");
46 | assertNull(lruCache.get(1));
47 | assertEquals("Five", lruCache.get(5));
48 | }
49 |
50 | @Test
51 | public void testInvalidate() {
52 | assertEquals("One", lruCache.get(1));
53 | assertEquals("Two", lruCache.get(2));
54 | assertEquals("Three", lruCache.get(3));
55 | assertTrue(lruCache.invalidate());
56 | assertFalse(lruCache.has(1));
57 | assertFalse(lruCache.has(2));
58 | assertFalse(lruCache.has(3));
59 | }
60 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Anirudh Sharma
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/LeetCode/Java/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java'
3 | }
4 |
5 | group 'org.redquark.tutorials.leetcode'
6 | version '1.0-SNAPSHOT'
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | testCompile group: 'junit', name: 'junit', version: '4.12'
14 | }
15 |
--------------------------------------------------------------------------------
/LeetCode/Java/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Java'
2 |
3 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ContainerWithMostWater.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class ContainerWithMostWater {
7 |
8 | /**
9 | * @param height - input array of heights of lines
10 | * @return maximum area
11 | */
12 | private static int maxArea(int[] height) {
13 | // Maximum area will be stored in this variable
14 | int maximumArea = Integer.MIN_VALUE;
15 | // Left and right pointers
16 | int left = 0;
17 | int right = height.length - 1;
18 | // Loop until left and right meet
19 | while (left < right) {
20 | // Shorter pole/vertical line
21 | int shorterLine = Math.min(height[left], height[right]);
22 | // Update maximum area if required
23 | maximumArea = Math.max(maximumArea, shorterLine * (right - left));
24 | // If there is a longer vertical line present
25 | if (height[left] < height[right]) {
26 | left++;
27 | } else {
28 | right--;
29 | }
30 | }
31 | return maximumArea;
32 | }
33 |
34 | public static void main(String[] args) {
35 | System.out.println(maxArea(new int[]{1, 8, 6, 2, 5, 4, 8, 3, 7}));
36 | System.out.println(maxArea(new int[]{1, 1}));
37 | System.out.println(maxArea(new int[]{4, 3, 2, 1, 4}));
38 | System.out.println(maxArea(new int[]{1, 2, 1}));
39 | System.out.println(maxArea(new int[]{3, 9, 3, 4, 7, 2, 12, 6}));
40 | }
41 | }
42 |
43 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/DivideTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class DivideTwoIntegers {
7 |
8 | private static int divide(int dividend, int divisor) {
9 | // Check for overflow
10 | if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
11 | return Integer.MAX_VALUE;
12 | }
13 | // Sign of result
14 | int sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) ? -1 : 1;
15 | // Quotient
16 | int quotient = 0;
17 | // Take the absolute value
18 | long absoluteDividend = Math.abs((long) dividend);
19 | long absoluteDivisor = Math.abs((long) divisor);
20 | // Loop until the dividend is greater than divisor
21 | while (absoluteDividend >= absoluteDivisor) {
22 | // This represents the number of bits shifted or
23 | // how many times we can double the number
24 | int shift = 0;
25 | while (absoluteDividend >= (absoluteDivisor << shift)) {
26 | shift++;
27 | }
28 | // Add the number of times we shifted to the quotient
29 | quotient += (1 << (shift - 1));
30 | // Update the dividend for the next iteration
31 | absoluteDividend -= absoluteDivisor << (shift - 1);
32 | }
33 | return sign == -1 ? -quotient : quotient;
34 | }
35 |
36 | public static void main(String[] args) {
37 | System.out.println(divide(10, 3));
38 | System.out.println(divide(7, -3));
39 | System.out.println(divide(0, 1));
40 | System.out.println(divide(1, 1));
41 | System.out.println(divide(Integer.MAX_VALUE, 1));
42 | System.out.println(divide(Integer.MIN_VALUE, 1));
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/GenerateParentheses.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Anirudh Sharma
8 | */
9 | public class GenerateParentheses {
10 |
11 | private static List generateParenthesis(int n) {
12 | // Resultant list
13 | List result = new ArrayList<>();
14 | /// Recursively generate parentheses
15 | generateParenthesis(result, "", 0, 0, n);
16 | return result;
17 | }
18 |
19 | private static void generateParenthesis(List result, String s, int open, int close, int n) {
20 | // Base case
21 | if (open == n && close == n) {
22 | result.add(s);
23 | return;
24 | }
25 | // If the number of open parentheses is less than the given n
26 | if (open < n) {
27 | generateParenthesis(result, s + "(", open + 1, close, n);
28 | }
29 | // If we need more close parentheses to balance
30 | if (close < open) {
31 | generateParenthesis(result, s + ")", open, close + 1, n);
32 | }
33 | }
34 |
35 | public static void main(String[] args) {
36 | System.out.println(generateParenthesis(3));
37 | System.out.println(generateParenthesis(1));
38 | System.out.println(generateParenthesis(8));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ImplementStrStr.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class ImplementStrStr {
7 |
8 | private static int strStr(String haystack, String needle) {
9 | // Base condition
10 | if (haystack == null || needle == null) {
11 | return -1;
12 | }
13 | // Special case
14 | if (haystack.equals(needle)) {
15 | return 0;
16 | }
17 | // length of the needle
18 | int needleLength = needle.length();
19 | // Loop through the haystack and slide the window
20 | for (int i = 0; i < haystack.length() - needleLength + 1; i++) {
21 | // Check if the subtring equals to the needle
22 | if (haystack.substring(i, i + needleLength).equals(needle)) {
23 | return i;
24 | }
25 | }
26 | return -1;
27 | }
28 |
29 | public static void main(String[] args) {
30 | String haystack = "hello";
31 | String needle = "ll";
32 | System.out.println(strStr(haystack, needle));
33 |
34 | haystack = "aaaaa";
35 | needle = "bba";
36 | System.out.println(strStr(haystack, needle));
37 |
38 | haystack = "";
39 | needle = "";
40 | System.out.println(strStr(haystack, needle));
41 |
42 | haystack = "abc";
43 | needle = "c";
44 | System.out.println(strStr(haystack, needle));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/IntegerToRoman.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class IntegerToRoman {
7 |
8 | private static String intToRoman(int num) {
9 | String[] M = {"", "M", "MM", "MMM"};
10 | String[] C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
11 | String[] X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
12 | String[] I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
13 |
14 | return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10];
15 | }
16 |
17 | public static void main(String[] args) {
18 | System.out.println(intToRoman(3));
19 | System.out.println(intToRoman(4));
20 | System.out.println(intToRoman(9));
21 | System.out.println(intToRoman(58));
22 | System.out.println(intToRoman(1994));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/LetterCombinationsOfAPhoneNumber.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Anirudh Sharma
8 | */
9 | public class LetterCombinationsOfAPhoneNumber {
10 |
11 | private static List letterCombinations(String digits) {
12 | // Resultant list
13 | List combinations = new ArrayList<>();
14 | // Base condition
15 | if (digits == null || digits.isEmpty()) {
16 | return combinations;
17 | }
18 | // Mappings of letters and numbers
19 | String[] lettersAndNumbersMappings = new String[]{
20 | "Anirudh",
21 | "is awesome",
22 | "abc",
23 | "def",
24 | "ghi",
25 | "jkl",
26 | "mno",
27 | "pqrs",
28 | "tuv",
29 | "wxyz"
30 | };
31 | findCombinations(combinations, digits, new StringBuilder(), 0, lettersAndNumbersMappings);
32 | return combinations;
33 | }
34 |
35 | private static void findCombinations(List combinations, String digits, StringBuilder previous, int index, String[] lettersAndNumbersMappings) {
36 | // Base condition for recursion to stop
37 | if (index == digits.length()) {
38 | combinations.add(previous.toString());
39 | return;
40 | }
41 | // Get the letters corresponding to the current index of digits string
42 | String letters = lettersAndNumbersMappings[digits.charAt(index) - '0'];
43 | // Loop through all the characters in the current combination of letters
44 | for (char c : letters.toCharArray()) {
45 | findCombinations(combinations, digits, previous.append(c), index + 1, lettersAndNumbersMappings);
46 | previous.deleteCharAt(previous.length() - 1);
47 | }
48 | }
49 |
50 | public static void main(String[] args) {
51 | System.out.println(letterCombinations("23"));
52 | System.out.println(letterCombinations(""));
53 | System.out.println(letterCombinations("2"));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/LongestCommonPrefix.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class LongestCommonPrefix {
7 |
8 | /**
9 | * @param strs - input array of strings
10 | * @return longest common prefix
11 | */
12 | private static String longestCommonPrefix(String[] strs) {
13 | // Longest common prefix string
14 | StringBuilder longestCommonPrefix = new StringBuilder();
15 | // Base condition
16 | if (strs == null || strs.length == 0) {
17 | return longestCommonPrefix.toString();
18 | }
19 | // Find the minimum length string from the array
20 | int minimumLength = strs[0].length();
21 | for (int i = 1; i < strs.length; i++) {
22 | minimumLength = Math.min(minimumLength, strs[i].length());
23 | }
24 | // Loop for the minimum length
25 | for (int i = 0; i < minimumLength; i++) {
26 | // Get the current character from first string
27 | char current = strs[0].charAt(i);
28 | // Check if this character is found in all other strings or not
29 | for (String str : strs) {
30 | if (str.charAt(i) != current) {
31 | return longestCommonPrefix.toString();
32 | }
33 | }
34 | longestCommonPrefix.append(current);
35 | }
36 | return longestCommonPrefix.toString();
37 | }
38 |
39 | public static void main(String[] args) {
40 | System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
41 | System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/LongestSubstringWithoutRepeatingCharacters.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * @author Anirudh Sharma
8 | *
9 | * Given a string s, find the length of the longest substring without repeating characters.
10 | */
11 | public class LongestSubstringWithoutRepeatingCharacters {
12 |
13 | /**
14 | * @param s - given input string
15 | * @return - length of longest substring without repeating characters
16 | */
17 | private static int lengthOfLongestSubstring(String s) {
18 | // Base condition
19 | if (s == null || s.equals("")) {
20 | return 0;
21 | }
22 | // Starting window index
23 | int start = 0;
24 | // Ending window index
25 | int end = 0;
26 | // Maximum length of substring
27 | int maxLength = 0;
28 | // This set will store the unique characters
29 | Set uniqueCharacters = new HashSet<>();
30 | while (end < s.length()) {
31 | if (uniqueCharacters.add(s.charAt(end))) {
32 | end++;
33 | maxLength = Math.max(maxLength, uniqueCharacters.size());
34 | } else {
35 | uniqueCharacters.remove(s.charAt(start));
36 | start++;
37 | }
38 | }
39 | return maxLength;
40 | }
41 |
42 | public static void main(String[] args) {
43 | String s = "abcabcbb";
44 | System.out.println(lengthOfLongestSubstring(s));
45 |
46 | s = "bbbbb";
47 | System.out.println(lengthOfLongestSubstring(s));
48 |
49 | s = "pwwkew";
50 | System.out.println(lengthOfLongestSubstring(s));
51 |
52 | s = "";
53 | System.out.println(lengthOfLongestSubstring(s));
54 |
55 | s = "aab";
56 | System.out.println(lengthOfLongestSubstring(s));
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class PalindromeNumber {
7 |
8 | private static boolean isPalindrome(int x) {
9 | // Base condition
10 | if (x < 0) {
11 | return false;
12 | }
13 | // Store the number in a variable
14 | int number = x;
15 | // This will store the reverse of the number
16 | int reverse = 0;
17 | while (number > 0) {
18 | reverse = reverse * 10 + number % 10;
19 | number /= 10;
20 | }
21 | return x == reverse;
22 | }
23 |
24 | public static void main(String[] args) {
25 | System.out.println(isPalindrome(121));
26 | System.out.println(isPalindrome(-121));
27 | System.out.println(isPalindrome(10));
28 | System.out.println(isPalindrome(-101));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/RegularExpressionMatching.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class RegularExpressionMatching {
7 |
8 | private static boolean isMatch(String s, String p) {
9 | int rows = s.length();
10 | int columns = p.length();
11 | /// Base conditions
12 | if (rows == 0 && columns == 0) {
13 | return true;
14 | }
15 | if (columns == 0) {
16 | return false;
17 | }
18 | // DP array
19 | boolean[][] dp = new boolean[rows + 1][columns + 1];
20 | // Empty string and empty pattern are a match
21 | dp[0][0] = true;
22 | // Deals with patterns with *
23 | for (int i = 2; i < columns + 1; i++) {
24 | if (p.charAt(i - 1) == '*') {
25 | dp[0][i] = dp[0][i - 2];
26 | }
27 | }
28 | // For remaining characters
29 | for (int i = 1; i < rows + 1; i++) {
30 | for (int j = 1; j < columns + 1; j++) {
31 | if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
32 | dp[i][j] = dp[i - 1][j - 1];
33 | } else if (j > 1 && p.charAt(j - 1) == '*') {
34 | dp[i][j] = dp[i][j - 2];
35 | if (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1)) {
36 | dp[i][j] = dp[i][j] | dp[i - 1][j];
37 | }
38 | }
39 | }
40 | }
41 | return dp[rows][columns];
42 | }
43 |
44 | public static void main(String[] args) {
45 | System.out.println(isMatch("aa", "a"));
46 | System.out.println(isMatch("aa", "a*"));
47 | System.out.println(isMatch("ab", "."));
48 | System.out.println(isMatch("aab", "c*a*b"));
49 | System.out.println(isMatch("mississippi", "mis*is*p*."));
50 | System.out.println(isMatch("", ".*"));
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/RemoveDuplicatesFromSortedArray.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | public class RemoveDuplicatesFromSortedArray {
4 |
5 | private static int removeDuplicates(int[] nums) {
6 | // Length of the updated array
7 | int count = 0;
8 | // Loop for all the elements in the array
9 | for (int i = 0; i < nums.length; i++) {
10 | // If the current element is equal to the next element, we skip
11 | if (i < nums.length - 1 && nums[i] == nums[i + 1]) {
12 | continue;
13 | }
14 | // We will update the array in place
15 | nums[count] = nums[i];
16 | count++;
17 | }
18 | return count;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(removeDuplicates(new int[]{1, 1, 2}));
23 | System.out.println(removeDuplicates(new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/RemoveElement.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class RemoveElement {
7 |
8 | private static int removeElement(int[] nums, int val) {
9 | // Counter for keeping track of elements other than val
10 | int count = 0;
11 | // Loop through all the elements of the array
12 | for (int i = 0; i < nums.length; i++) {
13 | // If the element is not val
14 | if (nums[i] != val) {
15 | nums[count++] = nums[i];
16 | }
17 | }
18 | return count;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(removeElement(new int[]{3, 2, 2, 3}, 3));
23 | System.out.println(removeElement(new int[]{0, 1, 2, 2, 3, 0, 4, 2}, 2));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/RemoveNthNodeFromEndOfList.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class RemoveNthNodeFromEndOfList {
7 |
8 | private static ListNode removeNthFromEnd(ListNode head, int n) {
9 | // Two pointers - fast and slow
10 | ListNode slow = head;
11 | ListNode fast = head;
12 | // Move fast pointer n steps ahead
13 | for (int i = 0; i < n; i++) {
14 | if (fast.next == null) {
15 | // If n is equal to the number of nodes, delete the head node
16 | if (i == n - 1) {
17 | head = head.next;
18 | }
19 | return head;
20 | }
21 | fast = fast.next;
22 | }
23 | // Loop until we reach to the end.
24 | // Now we will move both fast and slow pointers
25 | while (fast.next != null) {
26 | slow = slow.next;
27 | fast = fast.next;
28 | }
29 | // Delink the nth node from last
30 | if (slow.next != null) {
31 | slow.next = slow.next.next;
32 | }
33 | return head;
34 | }
35 |
36 | private static void print(ListNode node) {
37 | while (node != null) {
38 | System.out.print(node.val + " ");
39 | node = node.next;
40 | }
41 | System.out.println();
42 | }
43 |
44 | public static void main(String[] args) {
45 | ListNode head = new ListNode(1);
46 | head.next = new ListNode(2);
47 | head.next.next = new ListNode(3);
48 | head.next.next.next = new ListNode(4);
49 | head.next.next.next.next = new ListNode(5);
50 | print(removeNthFromEnd(head, 2));
51 |
52 | head = new ListNode(1);
53 | print(removeNthFromEnd(head, 1));
54 |
55 | head = new ListNode(1);
56 | head.next = new ListNode(2);
57 | print(removeNthFromEnd(head, 1));
58 | }
59 |
60 | static class ListNode {
61 | int val;
62 | ListNode next;
63 |
64 | ListNode(int val) {
65 | this.val = val;
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ReverseInteger.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class ReverseInteger {
7 |
8 | private static int reverse(int x) {
9 | boolean isNegative = false;
10 | if (x < 0) {
11 | isNegative = true;
12 | x = -x;
13 | }
14 | long reverse = 0;
15 | while (x > 0) {
16 | reverse = reverse * 10 + x % 10;
17 | x /= 10;
18 | }
19 | if (reverse > Integer.MAX_VALUE) {
20 | return 0;
21 | }
22 | return (int) (isNegative ? -reverse : reverse);
23 | }
24 |
25 | public static void main(String[] args) {
26 | System.out.println(reverse(321));
27 | System.out.println(reverse(-45315));
28 | System.out.println(reverse(-450));
29 | System.out.println(reverse(Integer.MAX_VALUE));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/RomanToInteger.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * @author Anirudh Sharma
8 | */
9 | public class RomanToInteger {
10 |
11 | private static int romanToInt(String s) {
12 | // Map to store romans numerals
13 | Map romanMap = new HashMap<>();
14 | // Fill the map
15 | romanMap.put('I', 1);
16 | romanMap.put('V', 5);
17 | romanMap.put('X', 10);
18 | romanMap.put('L', 50);
19 | romanMap.put('C', 100);
20 | romanMap.put('D', 500);
21 | romanMap.put('M', 1000);
22 | // Length of the given string
23 | int n = s.length();
24 | // Variable to store result
25 | int num = romanMap.get(s.charAt(n - 1));
26 | // Loop for each character from right to left
27 | for (int i = n - 2; i >= 0; i--) {
28 | // Check if the character at right of current character is
29 | // bigger or smaller
30 | if (romanMap.get(s.charAt(i)) >= romanMap.get(s.charAt(i + 1))) {
31 | num += romanMap.get(s.charAt(i));
32 | } else {
33 | num -= romanMap.get(s.charAt(i));
34 | }
35 | }
36 | return num;
37 | }
38 |
39 | public static void main(String[] args) {
40 | System.out.println(romanToInt("III"));
41 | System.out.println(romanToInt("IV"));
42 | System.out.println(romanToInt("IX"));
43 | System.out.println(romanToInt("LVIII"));
44 | System.out.println(romanToInt("MCMXCIV"));
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/StringToInteger.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class StringToInteger {
7 |
8 | private static int myAtoi(String str) {
9 | // Base condition
10 | if (str == null || str.length() < 1) {
11 | return 0;
12 | }
13 | // MAX and MIN values for integers
14 | final int INT_MAX = 2147483647;
15 | final int INT_MIN = -2147483648;
16 | // Trimmed string
17 | str = str.replaceAll("^\\s+", "");
18 | // Counter
19 | int i = 0;
20 | // Flag to indicate if the number is negative
21 | boolean isNegative = str.startsWith("-");
22 | // Flag to indicate if the number is positive
23 | boolean isPositive = str.startsWith("+");
24 | if (isNegative) {
25 | i++;
26 | } else if (isPositive) {
27 | i++;
28 | }
29 | // This will store the converted number
30 | double number = 0;
31 | // Loop for each numeric character in the string iff numeric characters are leading
32 | // characters in the string
33 | while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
34 | number = number * 10 + (str.charAt(i) - '0');
35 | i++;
36 | }
37 | // Give back the sign to the converted number
38 | number = isNegative ? -number : number;
39 | if (number < INT_MIN) {
40 | return INT_MIN;
41 | }
42 | if (number > INT_MAX) {
43 | return INT_MAX;
44 | }
45 | return (int) number;
46 | }
47 |
48 | public static void main(String[] args) {
49 | System.out.println(myAtoi("42"));
50 | System.out.println(myAtoi(" -42"));
51 | System.out.println(myAtoi("4193 with words"));
52 | System.out.println(myAtoi("words and 987"));
53 | System.out.println(myAtoi("-91283472332"));
54 | System.out.println(myAtoi("91283472332"));
55 | System.out.println(myAtoi("9223372036854775808"));
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/SwapNodesInPairs.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class SwapNodesInPairs {
7 |
8 | private static ListNode swapPairs(ListNode head) {
9 | // Dummy node
10 | ListNode dummy = new ListNode(0);
11 | // Point the next of dummy node to the head
12 | dummy.next = head;
13 | // This node will be used to traverse the list
14 | ListNode current = dummy;
15 | // Loop until we reach to the second last node
16 | while (current.next != null && current.next.next != null) {
17 | // First node of the pair
18 | ListNode first = current.next;
19 | // Second node of the pair
20 | ListNode second = current.next.next;
21 | // Point the next of first node to the node after second node
22 | first.next = second.next;
23 | // Now the current node's next should be the second node
24 | current.next = second;
25 | // Linking the original second node to the first node
26 | current.next.next = first;
27 | // Move the pointer two nodes ahead
28 | current = current.next.next;
29 | }
30 | return dummy.next;
31 | }
32 |
33 | private static void printList(ListNode head) {
34 | ListNode temp = head;
35 | while (temp != null) {
36 | System.out.print(temp.val + " ");
37 | temp = temp.next;
38 | }
39 | System.out.println();
40 | }
41 |
42 | public static void main(String[] args) {
43 | ListNode head = new ListNode(1);
44 | head.next = new ListNode(2);
45 | head.next.next = new ListNode(3);
46 | head.next.next.next = new ListNode(4);
47 | printList(swapPairs(head));
48 |
49 | printList(swapPairs(null));
50 |
51 | head = new ListNode(1);
52 | printList(swapPairs(head));
53 | }
54 |
55 | static class ListNode {
56 | int val;
57 | ListNode next;
58 |
59 | ListNode(int val) {
60 | this.val = val;
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ThreeSum.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | /**
8 | * @author Anirudh Sharma
9 | */
10 | public class ThreeSum {
11 |
12 | private static List> threeSum(int[] nums) {
13 | // Sort the array
14 | Arrays.sort(nums);
15 | // Length of the array
16 | int n = nums.length;
17 | // Resultant list
18 | List> triplets = new ArrayList<>();
19 | // Loop for each element of the array
20 | for (int i = 0; i < n; i++) {
21 | // Skip the duplicates
22 | if (i > 0 && nums[i] == nums[i - 1]) {
23 | continue;
24 | }
25 | // Left and right pointers
26 | int j = i + 1;
27 | int k = n - 1;
28 | // Loop for all the remaining pairs
29 | while (j < k) {
30 | if (nums[i] + nums[j] + nums[k] == 0) {
31 | triplets.add(Arrays.asList(nums[i], nums[j], nums[k]));
32 | j++;
33 | // Never let j refer to the same value twice (in an output) to avoid duplicates
34 | while (j < k && nums[j] == nums[j - 1]) {
35 | j++;
36 | }
37 | } else if (nums[i] + nums[j] + nums[k] < 0) {
38 | j++;
39 | } else {
40 | k--;
41 | }
42 | }
43 | }
44 | return triplets;
45 | }
46 |
47 | public static void main(String[] args) {
48 | System.out.println(threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
49 | System.out.println(threeSum(new int[]{}));
50 | System.out.println(threeSum(new int[]{0}));
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ThreeSumClosest.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * @author Anirudh Sharma
7 | */
8 | public class ThreeSumClosest {
9 |
10 | private static int threeSumClosest(int[] nums, int target) {
11 | // Sort the array
12 | Arrays.sort(nums);
13 | // Length of the array
14 | int n = nums.length;
15 | // Result
16 | int closest = nums[0] + nums[1] + nums[n - 1];
17 | // Loop for each element of the array
18 | for (int i = 0; i < n - 2; i++) {
19 | // Left and right pointers
20 | int j = i + 1;
21 | int k = n - 1;
22 | // Loop for all other pairs
23 | while (j < k) {
24 | int sum = nums[i] + nums[j] + nums[k];
25 | if (sum <= target) {
26 | j++;
27 | } else {
28 | k--;
29 | }
30 | if (Math.abs(closest - target) > Math.abs(sum - target)) {
31 | closest = sum;
32 | }
33 | }
34 | }
35 | return closest;
36 | }
37 |
38 | public static void main(String[] args) {
39 | int[] nums = new int[]{-1, 2, 1, -4};
40 | int target = 1;
41 | System.out.println(threeSumClosest(nums, target));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/TwoSum.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | /**
8 | * @author Anirudh Sharma
9 | */
10 | public class TwoSum {
11 |
12 | /**
13 | * @param nums - input array of numbers
14 | * @param target - the value of target
15 | * @return - array of indices of two numbers which will add up to target
16 | */
17 | private static int[] twoSum(int[] nums, int target) {
18 | // Array to store result
19 | int[] result = new int[2];
20 | // This map will store the difference and the corresponding index
21 | Map map = new HashMap<>();
22 | // Loop through the entire array
23 | for (int i = 0; i < nums.length; i++) {
24 | // If we have seen the current element before
25 | // It means we have already encountered the other number of the pair
26 | if (map.containsKey(nums[i])) {
27 | // Index of the current element
28 | result[0] = i;
29 | // Index of the other element of the pair
30 | result[1] = map.get(nums[i]);
31 | break;
32 | }
33 | // If we have not seen the current before
34 | // It means we have not yet encountered any number of the pair
35 | else {
36 | // Save the difference of the target and the current element
37 | // with the index of the current element
38 | map.put(target - nums[i], i);
39 | }
40 | }
41 | return result;
42 | }
43 |
44 | public static void main(String[] args) {
45 | int[] nums = new int[]{2, 7, 11, 15};
46 | int target = 9;
47 | System.out.println("The indices of Pair: " + Arrays.toString(twoSum(nums, target)));
48 |
49 | nums = new int[]{3, 2, 4};
50 | target = 6;
51 | System.out.println("The indices of Pair: " + Arrays.toString(twoSum(nums, target)));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | import java.util.Stack;
4 |
5 | /**
6 | * @author Anirudh Sharma
7 | */
8 | public class ValidParentheses {
9 |
10 | private static boolean isValid(String s) {
11 | // Stack to store left symbols
12 | Stack leftSymbols = new Stack<>();
13 | // Loop for each character of the string
14 | for (char c : s.toCharArray()) {
15 | // If left symbol is encountered
16 | if (c == '(' || c == '{' || c == '[') {
17 | leftSymbols.push(c);
18 | }
19 | // If right symbol is encountered
20 | else if (c == ')' && !leftSymbols.isEmpty() && leftSymbols.peek() == '(') {
21 | leftSymbols.pop();
22 | } else if (c == '}' && !leftSymbols.isEmpty() && leftSymbols.peek() == '{') {
23 | leftSymbols.pop();
24 | } else if (c == ']' && !leftSymbols.isEmpty() && leftSymbols.peek() == '[') {
25 | leftSymbols.pop();
26 | }
27 | // If none of the valid symbols is encountered
28 | else {
29 | return false;
30 | }
31 | }
32 | return leftSymbols.isEmpty();
33 | }
34 |
35 | public static void main(String[] args) {
36 | System.out.println(isValid("()"));
37 | System.out.println(isValid("()[]{}"));
38 | System.out.println(isValid("(]"));
39 | System.out.println(isValid("([)]"));
40 | System.out.println(isValid("{[]}"));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/LeetCode/Java/src/main/java/org/redquark/tutorials/leetcode/ZigZagConversion.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | public class ZigZagConversion {
7 |
8 | private static String convert(String s, int numRows) {
9 | // Base conditions
10 | if (s == null || s.isEmpty() || numRows <= 0) {
11 | return "";
12 | }
13 | if (numRows == 1) {
14 | return s;
15 | }
16 | // Resultant string
17 | StringBuilder result = new StringBuilder();
18 | // Step size
19 | int step = 2 * numRows - 2;
20 | // Loop for each row
21 | for (int i = 0; i < numRows; i++) {
22 | // Loop for each character in the row
23 | for (int j = i; j < s.length(); j += step) {
24 | result.append(s.charAt(j));
25 | if (i != 0 && i != numRows - 1 && (j + step - 2 * i) < s.length()) {
26 | result.append(s.charAt(j + step - 2 * i));
27 | }
28 | }
29 | }
30 | return result.toString();
31 | }
32 |
33 | public static void main(String[] args) {
34 | String s = "PAYPALISHIRING";
35 | int numRows = 3;
36 | System.out.println(convert(s, numRows));
37 |
38 | numRows = 4;
39 | System.out.println(convert(s, numRows));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "javascript",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1
5 | }
6 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "javascript",
3 | "version": "1.0.0",
4 | "description": "LeetCode problems and their solutions implemented in JavaScript",
5 | "scripts": {
6 | "test": "echo \"Error: no test specified\" && exit 1"
7 | },
8 | "author": "Anirudh Sharma",
9 | "license": "MIT"
10 | }
11 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/add_two_numbers.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 |
5 | var addTwoNumbers = function (l1, l2) {
6 | // Head of the new linked list - this is the head of the resultant list
7 | let head = null;
8 | // Reference of head which is null at this point
9 | let temp = null;
10 | // Carry
11 | let carry = 0;
12 | // Loop for the two lists
13 | while (l1 !== null || l2 !== null) {
14 | // At the start of each iteration, we should add carry from the last iteration
15 | let sum = carry;
16 | // Since the lengths of the lists may be unequal, we are checking if the
17 | // current node is null for one of the lists
18 | if (l1 != null) {
19 | sum += l1.val;
20 | l1 = l1.next;
21 | }
22 | if (l2 != null) {
23 | sum += l2.val;
24 | l2 = l2.next;
25 | }
26 | // At this point, we will add the total sum % 10 to the new node
27 | // in the resultant list
28 | let node = new ListNode(Math.floor(sum) % 10);
29 | // Carry to be added in the next iteration
30 | carry = Math.floor(sum / 10);
31 | // If this is the first node or head
32 | if (temp == null) {
33 | temp = head = node;
34 | }
35 | // For any other node
36 | else {
37 | temp.next = node;
38 | temp = temp.next;
39 | }
40 | }
41 | // After the last iteration, we will check if there is carry left
42 | // If it's left then we will create a new node and add it
43 | if (carry > 0) {
44 | temp.next = new ListNode(carry);
45 | }
46 | return head;
47 | };
48 |
49 | class ListNode {
50 | constructor(val) {
51 | this.val = val;
52 | this.next = null;
53 | }
54 | }
55 |
56 |
57 | let head1 = new ListNode(2);
58 | head1.next = new ListNode(4);
59 | head1.next.next = new ListNode(3);
60 |
61 | let head2 = new ListNode(5);
62 | head2.next = new ListNode(6);
63 | head2.next.next = new ListNode(4);
64 |
65 | let result = addTwoNumbers(head1, head2);
66 | let s = "";
67 | while (result !== null) {
68 | s += result.val + " ";
69 | result = result.next;
70 | }
71 | console.log(s);
72 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/container_with_most_water.js:
--------------------------------------------------------------------------------
1 | var maxArea = function (height) {
2 | // Maximum area will be stored in this variable
3 | let maximumArea = Number.MIN_SAFE_INTEGER;
4 | // Left and right pointers
5 | let left = 0;
6 | let right = height.length - 1;
7 | // Loop until left and right meet
8 | while (left < right) {
9 | // Shorter pole/vertical line
10 | let shorterLine = Math.min(height[left], height[right]);
11 | // Update maximum area if required
12 | maximumArea = Math.max(maximumArea, shorterLine * (right - left));
13 | // If there is a longer vertical line present
14 | if (height[left] < height[right]) {
15 | left++;
16 | } else {
17 | right--;
18 | }
19 | }
20 | return maximumArea;
21 | };
22 |
23 | console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]));
24 | console.log(maxArea([1, 1]));
25 | console.log(maxArea([4, 3, 2, 1, 4]));
26 | console.log(maxArea([1, 2, 1]));
27 | console.log(maxArea([3, 9, 3, 4, 7, 2, 12, 6]));
28 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/divide_two_integers.js:
--------------------------------------------------------------------------------
1 | var divide = function (dividend, divisor) {
2 | const MAX = 2147483647;
3 | const MIN = -2147483648;
4 | // Check for overflow
5 | if (divisor === 0 || (dividend === MIN && divisor === -1)) {
6 | return MAX;
7 | }
8 | if (divisor === dividend) {
9 | return 1;
10 | }
11 | // Sign of result
12 | const sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) ? -1 : 1;
13 | // Quotient
14 | let quotient = 0;
15 | // Take the absolute value
16 | let absoluteDividend = Math.abs(dividend);
17 | let absoluteDivisor = Math.abs(divisor);
18 | // Loop until the dividend is greater than divisor
19 | while (absoluteDividend >= absoluteDivisor) {
20 | // This represents the number of bits shifted or
21 | // how many times we can double the number
22 | let shift = 0;
23 | let shiftedDivisor = absoluteDivisor;
24 | while (absoluteDividend >= shiftedDivisor) {
25 | shift++;
26 | shiftedDivisor = absoluteDivisor << shift;
27 | // To handle overflow using left shift operator in JS
28 | if (shiftedDivisor < 0) {
29 | break;
30 | }
31 | }
32 | // Add the number of times we shifted to the quotient
33 | quotient += (1 << (shift - 1));
34 | // Update the dividend for the next iteration
35 | absoluteDividend -= absoluteDivisor << (shift - 1);
36 | }
37 | return sign === -1 ? -quotient : quotient;
38 | };
39 |
40 | console.log(divide(10, 3));
41 | console.log(divide(7, -3));
42 | console.log(divide(-2147483648, 1));
43 | console.log(divide(2147483647, 1));
44 | console.log(divide(-2147483648, - 2147483648))
45 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/four_sum.js:
--------------------------------------------------------------------------------
1 | var fourSum = function (nums, target) {
2 | // Resultant list
3 | const quadruplets = [];
4 | // Base condition
5 | if (nums == undefined || nums.length < 4) {
6 | return quadruplets;
7 | }
8 | // Sort the array
9 | nums.sort((a, b) => a - b);
10 | // Length of the array
11 | const n = nums.length;
12 | // Loop for each element of the array
13 | for (let i = 0; i < n - 3; i++) {
14 | // Check for skipping duplicates
15 | if (i > 0 && nums[i] == nums[i - 1]) {
16 | continue;
17 | }
18 | // Reducing to three sum problem
19 | for (let j = i + 1; j < n - 2; j++) {
20 | // Check for skipping duplicates
21 | if (j != i + 1 && nums[j] == nums[j - 1]) {
22 | continue;
23 | }
24 | // Left and right pointers
25 | let k = j + 1;
26 | let l = n - 1;
27 | // Reducing to two sum problem
28 | while (k < l) {
29 | const currentSum = nums[i] + nums[j] + nums[k] + nums[l];
30 | if (currentSum < target) {
31 | k++;
32 | } else if (currentSum > target) {
33 | l--;
34 | } else {
35 | quadruplets.push([nums[i], nums[j], nums[k], nums[l]]);
36 | k++;
37 | l--;
38 | // Check for skipping duplicates
39 | while (k < l && nums[k] == nums[k - 1]) {
40 | k++;
41 | }
42 | while (k < l && nums[l] == nums[l + 1]) {
43 | l--;
44 | }
45 | }
46 | }
47 | }
48 | }
49 | return quadruplets;
50 | };
51 |
52 | console.log(fourSum([1, 0, -1, 0, -2, 2], 0));
53 | console.log(fourSum([], 0));
54 | console.log(fourSum([1, 2, 3, 4], 10));
55 | console.log(fourSum([0, 0, 0, 0], 0));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/generate_parentheses.js:
--------------------------------------------------------------------------------
1 | var generateParenthesis = function (n) {
2 | // Resultant list
3 | const result = [];
4 | // Recursively generate parentheses
5 | generate(result, "", 0, 0, n);
6 | return result;
7 | };
8 |
9 | function generate(result, s, open, close, n) {
10 | // Base condition
11 | if (open === n && close === n) {
12 | result.push(s);
13 | return;
14 | }
15 | // If the number of _open parentheses is less than the given n
16 | if (open < n) {
17 | generate(result, s + "(", open + 1, close, n);
18 | }
19 | // If we need more close parentheses to balance
20 | if (close < open) {
21 | generate(result, s + ")", open, close + 1, n);
22 | }
23 | }
24 |
25 | console.log(generateParenthesis(3));
26 | console.log(generateParenthesis(1));
27 | console.log(generateParenthesis(8));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/implement_strstr.js:
--------------------------------------------------------------------------------
1 | var strStr = function (haystack, needle) {
2 | // Base condition
3 | if (haystack == null || needle == null) {
4 | return -1;
5 | }
6 | // Special case
7 | if (haystack === needle) {
8 | return 0;
9 | }
10 | // length of the needle
11 | const needleLength = needle.length;
12 | // Loop through the haystack and slide the window
13 | for (let i = 0; i < haystack.length - needleLength + 1; i++) {
14 | // Check if the substring equals to the needle
15 | if (haystack.substring(i, i + needleLength) === needle) {
16 | return i;
17 | }
18 | }
19 | return -1;
20 | };
21 |
22 | let haystackString = "hello";
23 | let needleString = "ll";
24 | console.log(strStr(haystackString, needleString));
25 |
26 | haystackString = "aaaaa";
27 | needleString = "bba";
28 | console.log(strStr(haystackString, needleString));
29 |
30 | haystackString = "";
31 | needleString = "";
32 | console.log(strStr(haystackString, needleString));
33 |
34 | haystackString = "abc";
35 | needleString = "c";
36 | console.log(strStr(haystackString, needleString));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/integer_to_roman.js:
--------------------------------------------------------------------------------
1 | var intToRoman = function (num) {
2 | const M = ["", "M", "MM", "MMM"];
3 | const C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
4 | const X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
5 | const I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
6 | return M[Math.floor(num / 1000)] + C[Math.floor((num % 1000) / 100)] + X[Math.floor((num % 100) / 10)] + I[num % 10];
7 | };
8 |
9 | console.log(intToRoman(3));
10 | console.log(intToRoman(4));
11 | console.log(intToRoman(9));
12 | console.log(intToRoman(58));
13 | console.log(intToRoman(1994));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/letter_combinations_of_a_phone_number.js:
--------------------------------------------------------------------------------
1 | var letterCombinations = function (digits) {
2 | // Resultant list
3 | let combinations = [];
4 | // Base condition
5 | if (digits == null || digits.length == 0) {
6 | return combinations;
7 | }
8 | // Mappings of letters and numbers
9 | const lettersAndNumbersMappings = [
10 | "Anirudh",
11 | "is awesome",
12 | "abc",
13 | "def",
14 | "ghi",
15 | "jkl",
16 | "mno",
17 | "pqrs",
18 | "tuv",
19 | "wxyz"
20 | ];
21 | findCombinations(combinations, digits, "", 0, lettersAndNumbersMappings);
22 | return combinations;
23 | };
24 |
25 | function findCombinations(combinations, digits, previous, index, lettersAndNumbersMappings) {
26 | // Base condition for recursion to stop
27 | if (index == digits.length) {
28 | combinations.push(previous);
29 | return;
30 | }
31 | // Get the letters corresponding to the current index of digits string
32 | let letters = lettersAndNumbersMappings[digits[index] - '0'];
33 | // Loop through all the characters in the current combination of letters
34 | for (let i = 0; i < letters.length; i++) {
35 | findCombinations(combinations, digits, previous + letters[i], index + 1, lettersAndNumbersMappings);
36 | }
37 | };
38 |
39 |
40 | console.log(letterCombinations("23"));
41 | console.log(letterCombinations(""));
42 | console.log(letterCombinations("2"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/longest_common_prefix.js:
--------------------------------------------------------------------------------
1 | var longestCommonPrefix = function (strs) {
2 | // Longest common prefix string
3 | let longestCommonPrefix = "";
4 | // Base condition
5 | if (strs == null || strs.length == 0) {
6 | return longestCommonPrefix;
7 | }
8 | // Find the minimum length string from the array
9 | let minimumLength = strs[0].length;
10 | for (let i = 1; i < strs.length; i++) {
11 | minimumLength = Math.min(minimumLength, strs[i].length);
12 | }
13 | // Loop for the minimum length
14 | for (let i = 0; i < minimumLength; i++) {
15 | // Get the current character from first string
16 | let current = strs[0][i];
17 | // Check if this character is found in all other strings or not
18 | for (let j = 0; j < strs.length; j++) {
19 | if (strs[j][i] != current) {
20 | return longestCommonPrefix;
21 | }
22 | }
23 | longestCommonPrefix += current;
24 | }
25 | return longestCommonPrefix;
26 | };
27 |
28 | console.log(longestCommonPrefix(["flower", "flow", "flight"]));
29 | console.log(longestCommonPrefix(["dog", "racecar", "car"]));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/longest_palindromic_substring.js:
--------------------------------------------------------------------------------
1 | var longestPalindrome = function (s) {
2 | // Update the string to put hash "#" at the beginning, end and in between each character
3 | let updatedString = getUpdatedString(s);
4 | // Length of the array that will store the window of palindromic substring
5 | const length = 2 * s.length + 1;
6 | // Array to store the length of each palindrome centered at each element
7 | let p = new Array(length);
8 | p.fill(0);
9 | // Current center of the longest palindromic string
10 | let c = 0;
11 | // Right boundary of the longest palindromic string
12 | let r = 0;
13 | // Maximum length of the substring
14 | let maxLength = 0;
15 | // Position index
16 | let position = -1;
17 | for (let i = 0; i < length; i++) {
18 | // Mirror of the current index
19 | let mirror = 2 * c - i;
20 | // Check if the mirror is outside the left boundary of current longest palindrome
21 | if (i < r) {
22 | p[i] = Math.min(r - i, p[mirror]);
23 | }
24 | // Indices of the characters to be compared
25 | let a = i + (1 + p[i]);
26 | let b = i - (1 + p[i]);
27 | // Expand the window
28 | while (a < length && b >= 0 && updatedString[a] === updatedString[b]) {
29 | p[i]++;
30 | a++;
31 | b--;
32 | }
33 | // If the expanded palindrome is expanding beyond the right boundary of
34 | // the current longest palindrome, then update c and r
35 | if (i + p[i] > r) {
36 | c = i;
37 | r = i + p[i];
38 | }
39 | if (maxLength < p[i]) {
40 | maxLength = p[i];
41 | position = i;
42 | }
43 | }
44 | let offset = p[position];
45 | let result = "";
46 | for (let i = position - offset + 1; i <= position + offset - 1; i++) {
47 | if (updatedString[i] !== '#') {
48 | result += updatedString[i];
49 | }
50 | }
51 | return result;
52 | };
53 |
54 | function getUpdatedString(s) {
55 | let sb = "";
56 | for (let i = 0; i < s.length; i++) {
57 | sb += "#" + s[i];
58 | }
59 | sb += "#";
60 | return sb;
61 | }
62 |
63 | console.log(longestPalindrome("babad"));
64 | console.log(longestPalindrome("cbbd"));
65 | console.log(longestPalindrome("a"));
66 | console.log(longestPalindrome("ac"));
67 | console.log(longestPalindrome("abb"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/longest_substring_without_repeating_characters.js:
--------------------------------------------------------------------------------
1 | var lengthOfLongestSubstring = function (s) {
2 | // Base condition
3 | if (!s) {
4 | return 0;
5 | }
6 | // Starting index of the window
7 | let start = 0;
8 | // Ending index of the window
9 | let end = 0;
10 | // Maximum length of the substring
11 | let maxLength = 0;
12 | // Set to store the unique characters
13 | const uniqueCharacters = new Set();
14 | // Loop for each character in the string
15 | while (end < s.length) {
16 | if (!uniqueCharacters.has(s[end])) {
17 | uniqueCharacters.add(s[end]);
18 | end++;
19 | maxLength = Math.max(maxLength, uniqueCharacters.size);
20 | } else {
21 | uniqueCharacters.delete(s[start]);
22 | start++;
23 | }
24 | }
25 | return maxLength;
26 | };
27 |
28 | let sampleString = "abcabcbb";
29 | console.log(lengthOfLongestSubstring(sampleString));
30 |
31 | sampleString = "bbbb";
32 | console.log(lengthOfLongestSubstring(sampleString));
33 |
34 | sampleString = "pwwkew";
35 | console.log(lengthOfLongestSubstring(sampleString));
36 |
37 | sampleString = "";
38 | console.log(lengthOfLongestSubstring(sampleString));
39 |
40 | sampleString = "aab";
41 | console.log(lengthOfLongestSubstring(sampleString));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/longest_valid_parentheses.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | *
4 | * Given a string containing just the characters '(' and ')', find the length of the
5 | * longest valid (well-formed) parentheses substring.
6 | *
7 | * Constraints:
8 | *
9 | * 0 <= s.length <= 3 * 10^4
10 | * s[i] is '(', or ')'.
11 | */
12 | var longestValidParentheses = function (s) {
13 | // Variable to store the longest valid parentheses
14 | let count = 0;
15 | // Left counter will count the number of '('
16 | let left = 0;
17 | // Right counter will count the number of ')'
18 | let right = 0;
19 | // Loop through the string from left to right.
20 | // This will take care of extra right parentheses
21 | for (let i = 0; i < s.length; i++) {
22 | // Current character
23 | let c = s[i];
24 | if (c === '(') {
25 | left++;
26 | }
27 | if (c === ')') {
28 | right++;
29 | }
30 | // If both left and right are equal,
31 | // it means we have a valid substring
32 | if (left === right) {
33 | count = Math.max(count, left + right);
34 | }
35 | // If right is greater than left,
36 | // it means we need to set both
37 | // counters to zero
38 | if (right > left) {
39 | left = right = 0;
40 | }
41 | }
42 | // Reset left and right
43 | left = right = 0;
44 | // Follow the same approach but now loop the string
45 | // from right to left. This will take care of extra
46 | // left parentheses
47 | for (let i = s.length - 1; i >= 0; i--) {
48 | // Current character
49 | let c = s[i];
50 | if (c === '(') {
51 | left++;
52 | }
53 | if (c === ')') {
54 | right++;
55 | }
56 | // If both left and right are equal,
57 | // it means we have a valid substring
58 | if (left === right) {
59 | count = Math.max(count, left + right);
60 | }
61 | // If right is greater than left,
62 | // it means we need to set both
63 | // counters to zero
64 | if (left > right) {
65 | left = right = 0;
66 | }
67 | }
68 | return count;
69 | };
70 |
71 |
72 | console.log(longestValidParentheses("(()"));
73 | console.log(longestValidParentheses(")()()"));
74 | console.log(longestValidParentheses(""));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/merge_two_sorted_lists.js:
--------------------------------------------------------------------------------
1 | var mergeTwoLists = function (l1, l2) {
2 | // Check if either of the lists is null
3 | if (!l1) {
4 | return l2;
5 | }
6 | if (!l2) {
7 | return l1;
8 | }
9 | // Head of the new linked list - this is the head of the resultant list
10 | let head = null;
11 | // Reference of head which is null at this point
12 | let temp;
13 | // Choose head which is smaller of the two lists
14 | if (l1.val < l2.val) {
15 | temp = head = new ListNode(l1.val);
16 | l1 = l1.next;
17 | } else {
18 | temp = head = new ListNode(l2.val);
19 | l2 = l2.next;
20 | }
21 | // Loop until any of the list becomes null
22 | while (l1 && l2) {
23 | if (l1.val < l2.val) {
24 | temp.next = new ListNode(l1.val);
25 | l1 = l1.next;
26 | temp = temp.next;
27 | } else {
28 | temp.next = new ListNode(l2.val);
29 | l2 = l2.next;
30 | temp = temp.next;
31 | }
32 | }
33 | // Add all the nodes in l1, if remaining
34 | while (l1) {
35 | temp.next = new ListNode(l1.val);
36 | l1 = l1.next;
37 | temp = temp.next;
38 | }
39 | // Add all the nodes in l2, if remaining
40 | while (l2) {
41 | temp.next = new ListNode(l2.val);
42 | l2 = l2.next;
43 | temp = temp.next;
44 | }
45 | return head;
46 | };
47 |
48 | function printList(node) {
49 | let list = [];
50 | while (node != null) {
51 | list.push(node.val);
52 | node = node.next
53 | }
54 | console.log(list.join(" "));
55 | }
56 |
57 | function ListNode(val, next) {
58 | this.val = (val === undefined ? 0 : val)
59 | this.next = (next === undefined ? null : next)
60 | }
61 |
62 | let head1 = new ListNode(1);
63 | head1.next = new ListNode(2);
64 | head1.next.next = new ListNode(4);
65 | let head2 = new ListNode(1);
66 | head2.next = new ListNode(3);
67 | head2.next.next = new ListNode(4);
68 | printList(mergeTwoLists(head1, head2));
69 |
70 | printList(mergeTwoLists(null, null));
71 |
72 | head2 = new ListNode(1);
73 | printList(mergeTwoLists(null, head2));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/next_permutation.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | *
4 | * Implement next permutation, which rearranges numbers into the lexicographically next greater
5 | * permutation of numbers.
6 | *
7 | * If such an arrangement is not possible, it must rearrange it as the lowest possible order
8 | * (i.e., sorted in ascending order).
9 | *
10 | * The replacement must be in place and use only constant extra memory.
11 | *
12 | * Constraints:
13 | *
14 | * 1 <= nums.length <= 100
15 | * 0 <= nums[i] <= 100
16 | */
17 | var nextPermutation = function(nums) {
18 | // Length of the array
19 | const n = nums.length;
20 | // Index of the first element that is smaller than
21 | // the element to its right.
22 | let index = -1;
23 | // Loop from right to left
24 | for (let i = n - 1; i > 0; i--) {
25 | if (nums[i] > nums[i - 1]) {
26 | index = i - 1;
27 | break;
28 | }
29 | }
30 | // Base condition
31 | if (index === -1) {
32 | reverse(nums, 0, n - 1);
33 | return nums;
34 | }
35 | let j = n - 1;
36 | // Again swap from right to left to find first element
37 | // that is greater than the above find element
38 | for (let i = n - 1; i >= index + 1; i--) {
39 | if (nums[i] > nums[index]) {
40 | j = i;
41 | break;
42 | }
43 | }
44 | // Swap the elements
45 | swap(nums, index, j);
46 | // Reverse the elements from index + 1 to the nums.length
47 | reverse(nums, index + 1, n - 1);
48 | return nums;
49 | };
50 |
51 | const reverse = (nums, i, j) => {
52 | while (i < j) {
53 | swap(nums, i, j);
54 | i++;
55 | j--;
56 | }
57 | };
58 |
59 | const swap = (nums, i, index) => {
60 | const temp = nums[index];
61 | nums[index] = nums[i];
62 | nums[i] = temp;
63 | };
64 |
65 |
66 | console.log(nextPermutation([1, 2, 3]));
67 | console.log(nextPermutation([3, 2, 1]));
68 | console.log(nextPermutation([1, 1, 5]));
69 | console.log(nextPermutation([1]));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/palindrome_number.js:
--------------------------------------------------------------------------------
1 | var isPalindrome = function (x) {
2 | // Base condition
3 | if (x < 0) {
4 | return false;
5 | }
6 | // Store the number in a variable
7 | let number = x;
8 | // This will store the reverse of the number
9 | let reverse = 0;
10 | while (number > 0) {
11 | reverse = reverse * 10 + number % 10;
12 | number = parseInt(number / 10);
13 | }
14 | return x === reverse;
15 | };
16 |
17 | console.log(isPalindrome(121));
18 | console.log(isPalindrome(-121));
19 | console.log(isPalindrome(10));
20 | console.log(isPalindrome(-101));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/regular_expression_matching.js:
--------------------------------------------------------------------------------
1 | var isMatch = function (s, p) {
2 | const rows = s.length;
3 | const columns = p.length;
4 | /// Base conditions
5 | if (rows == 0 && columns == 0) {
6 | return true;
7 | }
8 | if (columns == 0) {
9 | return false;
10 | }
11 | // DP array
12 | const dp = Array.from({ length: s.length + 1 }, () => [false]);
13 | // Empty string and empty pattern are a match
14 | dp[0][0] = true;
15 | // Deals with patterns with *
16 | for (let i = 1; i < columns + 1; i++) {
17 | if (p[i - 1] === '*') {
18 | dp[0][i] = dp[0][i - 2];
19 | }
20 | else {
21 | dp[0][i] = false;
22 | };
23 | }
24 | // For remaining characters
25 | for (let i = 1; i < rows + 1; i++) {
26 | for (let j = 1; j < columns + 1; j++) {
27 | if (p[j - 1] === '*') {
28 | if (p[j - 2] === s[i - 1] || p[j - 2] === '.') {
29 | dp[i][j] = dp[i][j - 2] || dp[i - 1][j];
30 | } else {
31 | dp[i][j] = dp[i][j - 2];
32 | }
33 | } else if (p[j - 1] === s[i - 1] || p[j - 1] === '.') {
34 | dp[i][j] = dp[i - 1][j - 1];
35 | } else {
36 | dp[i][j] = false;
37 | }
38 | }
39 | }
40 | return dp[rows][columns];
41 | };
42 |
43 |
44 | console.log(isMatch("aa", "a"));
45 | console.log(isMatch("aa", "a*"));
46 | console.log(isMatch("an", "."));
47 | console.log(isMatch("aab", "c*a*b"));
48 | console.log(isMatch("mississippi", "mis*is*p*."));
49 | console.log(isMatch("", ".*"));
50 | console.log(isMatch("ab", ".*c"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/remove_duplicates_from_sorted_array.js:
--------------------------------------------------------------------------------
1 | var removeDuplicates = function (nums) {
2 | // Length of the updated array
3 | let count = 0;
4 | // Loop for all the elements in the array
5 | for (let i = 0; i < nums.length; i++) {
6 | // If the current element is equal to the next element, we skip
7 | if (i < nums.length - 1 && nums[i] == nums[i + 1]) {
8 | continue;
9 | }
10 | // We will update the array in place
11 | nums[count] = nums[i];
12 | count++;
13 | }
14 | return count;
15 | };
16 |
17 | console.log(removeDuplicates([1, 1, 2]));
18 | console.log(removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/remove_element.js:
--------------------------------------------------------------------------------
1 | var removeElement = function (nums, val) {
2 | // Counter for keeping track of elements other than val
3 | let count = 0;
4 | // Loop through all the elements of the array
5 | for (let i = 0; i < nums.length; i++) {
6 | // If the element is not val
7 | if (nums[i] !== val) {
8 | nums[count++] = nums[i];
9 | }
10 | }
11 | return count;
12 | };
13 |
14 | console.log(removeElement([2,3,3,2], 3));
15 | console.log(removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/remove_nth_node_from_end_of_list.js:
--------------------------------------------------------------------------------
1 | var removeNthFromEnd = function (head, n) {
2 | // Two pointers - fast and slow
3 | let slow = head;
4 | let fast = head;
5 | // Move fast pointer n steps ahead
6 | for (let i = 0; i < n; i++) {
7 | if (fast.next === null) {
8 | // If n is equal to the number of nodes, delete the head node
9 | if (i === n - 1) {
10 | head = head.next;
11 | }
12 | return head;
13 | }
14 | fast = fast.next;
15 | }
16 | // Loop until we reach to the end.
17 | // Now we will move both fast and slow pointers
18 | while (fast.next !== null) {
19 | slow = slow.next;
20 | fast = fast.next;
21 | }
22 | // Delink the nth node from last
23 | if (slow.next !== null) {
24 | slow.next = slow.next.next;
25 | }
26 | return head;
27 | };
28 |
29 | function ListNode(val, next) {
30 | this.val = (val === undefined ? 0 : val)
31 | this.next = (next === undefined ? null : next)
32 | }
33 |
34 | function printList(node) {
35 | let list = [];
36 | while (node != null) {
37 | list.push(node.val);
38 | node = node.next
39 | }
40 | console.log(list.join(" "));
41 | }
42 |
43 | head = new ListNode(1);
44 | head.next = new ListNode(2);
45 | head.next.next = new ListNode(3);
46 | head.next.next.next = new ListNode(4);
47 | head.next.next.next.next = new ListNode(5);
48 | printList(removeNthFromEnd(head, 2));
49 |
50 | head = new ListNode(1);
51 | printList(removeNthFromEnd(head, 1));
52 |
53 | head = new ListNode(1);
54 | head.next = new ListNode(2);
55 | printList(removeNthFromEnd(head, 1));
56 |
57 |
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/reverse_integer.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 | var reverse = function (x) {
5 | let isNegative = false;
6 | if (x < 0) {
7 | isNegative = true;
8 | x = -x;
9 | }
10 | let reverse = 0;
11 | while (x > 0) {
12 | reverse = reverse * 10 + x % 10;
13 | x = parseInt(x / 10);
14 | }
15 | if (reverse >= Math.pow(2, 31) - 1 || reverse <= Math.pow(-2, 31)) {
16 | return 0;
17 | }
18 | return isNegative ? -reverse : reverse;
19 | };
20 |
21 | console.log(reverse(342));
22 | console.log(reverse(-430));
23 | console.log(reverse(242353400));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/roman_to_integer.js:
--------------------------------------------------------------------------------
1 | var romanToInt = function (s) {
2 | // Map to store romans numerals
3 | const romanMap = new Map();
4 | // Fill the map
5 | romanMap.set('I', 1);
6 | romanMap.set('V', 5);
7 | romanMap.set('X', 10);
8 | romanMap.set('L', 50);
9 | romanMap.set('C', 100);
10 | romanMap.set('D', 500);
11 | romanMap.set('M', 1000);
12 | // Length of the given string
13 | const n = s.length;
14 | // Variable to store result
15 | let num = romanMap.get(s[n - 1]);
16 | // Loop for each character from right to left
17 | for (let i = n - 2; i >= 0; i--) {
18 | // Check if the character at right of current character is
19 | // bigger or smaller
20 | if (romanMap.get(s[i]) >= romanMap.get(s[i + 1])) {
21 | num += romanMap.get(s[i]);
22 | } else {
23 | num -= romanMap.get(s[i]);
24 | }
25 | }
26 | return num;
27 | };
28 |
29 |
30 | console.log(romanToInt("III"));
31 | console.log(romanToInt("IV"));
32 | console.log(romanToInt("IX"));
33 | console.log(romanToInt("LVIII"));
34 | console.log(romanToInt("MCMXCIV"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/search_in_rotated_sorted_array.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 | var search = function (nums, target) {
5 | // Special case
6 | if (nums === null || nums.length === 0) {
7 | return -1;
8 | }
9 | // Left and right pointers in the array
10 | let left = 0;
11 | let right = nums.length - 1;
12 | // First step is to find the pivot where the
13 | // array is rotated
14 | while (left < right) {
15 | // Middle pointer
16 | let middle = left + parseInt((right - left) / 2);
17 | // If the element at the mid is greater than
18 | // the element at the right then we can say that
19 | // the array is rotated after middle index
20 | if (nums[middle] > nums[right]) {
21 | left = middle + 1;
22 | }
23 | // Else, the pivot is in the left part
24 | else {
25 | right = middle;
26 | }
27 | }
28 | // After the above loop is completed, then the
29 | // left index will point to the pivot
30 | const pivot = left;
31 | left = 0;
32 | right = nums.length - 1;
33 | // Now we will find in which half of the array,
34 | // our target is present
35 | if (target >= nums[pivot] && target <= nums[right]) {
36 | left = pivot;
37 | } else {
38 | right = pivot;
39 | }
40 | // Now perform normal binary search
41 | while (left <= right) {
42 | let middle = left + parseInt((right - left) / 2);
43 | if (nums[middle] === target) {
44 | return middle;
45 | } else if (target < nums[middle]) {
46 | right = middle - 1;
47 | } else {
48 | left = middle + 1;
49 | }
50 | }
51 | return -1;
52 | };
53 |
54 |
55 | let numbers = [4, 5, 6, 7, 0, 1, 2];
56 | let targetValue = 0;
57 | console.log(search(numbers, targetValue));
58 |
59 | numbers = [4, 5, 6, 7, 0, 1, 2];
60 | targetValue = 3;
61 | console.log(search(numbers, targetValue));
62 |
63 | numbers = [1];
64 | targetValue = 0;
65 | console.log(search(numbers, targetValue));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/string_to_integer.js:
--------------------------------------------------------------------------------
1 | var myAtoi = function (str) {
2 | // Base condition
3 | if (!str) {
4 | return 0;
5 | }
6 | // MAX and MIN values for integers
7 | const INT_MAX = 2147483647;
8 | const INT_MIN = -2147483648;
9 | // Trimmed string
10 | str = str.trim();
11 | // Counter
12 | let i = 0;
13 | // Flag to indicate if the number is negative
14 | const isNegative = str[0] === '-';
15 | // Flag to indicate if the number is positive
16 | const isPositive = str[0] === '+';
17 | if (isNegative) {
18 | i++;
19 | } else if (isPositive) {
20 | i++;
21 | }
22 | // This will store the converted number
23 | let number = 0;
24 | // Loop for each numeric character in the string iff numeric characters are leading
25 | // characters in the string
26 | while (i < str.length && str[i] >= '0' && str[i] <= '9') {
27 | number = number * 10 + (str[i] - '0');
28 | i++;
29 | }
30 | // Give back the sign to the converted number
31 | number = isNegative ? -number : number;
32 | if (number < INT_MIN) {
33 | return INT_MIN;
34 | }
35 | if (number > INT_MAX) {
36 | return INT_MAX;
37 | }
38 | return number;
39 | };
40 |
41 | console.log(myAtoi("42"));
42 | console.log(myAtoi(" -42"));
43 | console.log(myAtoi("4193 with words"));
44 | console.log(myAtoi("words and 987"));
45 | console.log(myAtoi("-91283472332"));
46 | console.log(myAtoi("91283472332"));
47 | console.log(myAtoi("9223372036854775808"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/swap_nodes_in_pairs.js:
--------------------------------------------------------------------------------
1 | var swapPairs = function (head) {
2 | // Dummy node
3 | const dummy = new ListNode(0);
4 | // Point the next of dummy node to the head
5 | dummy.next = head;
6 | // This node will be used to traverse the list
7 | let current = dummy;
8 | // Loop until we reach to the second last node
9 | while (current.next !== null && current.next !== undefined && current.next.next !== null) {
10 | // First node of the pair
11 | let first = current.next;
12 | // Second node of the pair
13 | let second = current.next.next;
14 | // Point the next of first node to the node after second node
15 | first.next = second.next;
16 | // Now the current node's next should be the second node
17 | current.next = second;
18 | // Linking the original second node to the first node
19 | current.next.next = first;
20 | // Move the pointer two nodes ahead
21 | current = current.next.next;
22 | }
23 | return dummy.next;
24 | };
25 |
26 | function ListNode(val, next) {
27 | this.val = (val === undefined ? 0 : val)
28 | this.next = (next === undefined ? null : next)
29 | }
30 |
31 | function printList(node) {
32 | let list = [];
33 | while (node != null) {
34 | list.push(node.val);
35 | node = node.next
36 | }
37 | console.log(list.join(" "));
38 | }
39 |
40 | let headNode = new ListNode(1);
41 | headNode.next = new ListNode(2);
42 | headNode.next.next = new ListNode(3);
43 | headNode.next.next.next = new ListNode(4);
44 | printList(swapPairs(headNode));
45 |
46 | headNode = undefined;
47 | printList(swapPairs(headNode));
48 |
49 | headNode = new ListNode(1);
50 | printList(swapPairs(headNode));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/three_sum.js:
--------------------------------------------------------------------------------
1 | var threeSum = function (nums) {
2 | // Sort the array
3 | nums.sort((a, b) => a - b);
4 | // Length of the array
5 | const n = nums.length;
6 | // Resultant list
7 | const triplets = [];
8 | // Loop for each element of the array
9 | for (let i = 0; i < n; i++) {
10 | // Skip the duplicates
11 | if (i > 0 && nums[i] === nums[i - 1]) {
12 | continue;
13 | }
14 | // Left and right pointers
15 | let j = i + 1;
16 | let k = n - 1;
17 | // Loop for all the remaining pairs
18 | while (j < k) {
19 | if (nums[i] + nums[j] + nums[k] === 0) {
20 | triplets.push([nums[i], nums[j], nums[k]]);
21 | j++;
22 | // Never let j refer to the same value twice (in an output) to avoid duplicates
23 | while (j < k && nums[j] === nums[j - 1]) {
24 | j++;
25 | }
26 | } else if (nums[i] + nums[j] + nums[k] < 0) {
27 | j++;
28 | } else {
29 | k--;
30 | }
31 | }
32 | }
33 | return triplets;
34 | };
35 |
36 | console.log(threeSum([-1, 0, 1, 2, -1, -4]));
37 | console.log(threeSum([]));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/three_sum_closest.js:
--------------------------------------------------------------------------------
1 | var threeSumClosest = function (nums, target) {
2 | // Sort the array
3 | nums.sort((a, b) => a - b);
4 | // Length of the array
5 | const n = nums.length;
6 | // Result
7 | let closest = nums[0] + nums[1] + nums[n - 1];
8 | // Loop for each element of the array
9 | for (let i = 0; i < n - 2; i++) {
10 | // Left and right pointers
11 | let j = i + 1;
12 | let k = n - 1;
13 | // Loop for all other pairs
14 | while (j < k) {
15 | let sum = nums[i] + nums[j] + nums[k];
16 | if (sum <= target) {
17 | j++;
18 | } else {
19 | k--;
20 | }
21 | if (Math.abs(closest - target) > Math.abs(sum - target)) {
22 | closest = sum;
23 | }
24 | }
25 | }
26 | return closest;
27 | };
28 |
29 |
30 | console.log(threeSumClosest([-1, 2, 1, -4], 1));
31 | console.log(threeSumClosest([2, 3, 7, 1, 5, 7, 1, 8, -1, -4, -4, 3], 12))
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/two_sum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 |
5 | var twoSum = function (nums, target) {
6 | // Array to store the result
7 | result = [];
8 | // Map to store the difference and its index
9 | index_map = new Map();
10 | // Loop for each element in the array
11 | for (let i = 0; i < nums.length; i++) {
12 | let difference = target - nums[i];
13 | if (index_map.has(difference)) {
14 | result[0] = i;
15 | result[1] = index_map.get(difference);
16 | break;
17 | } else {
18 | index_map.set(nums[i], i);
19 | }
20 | }
21 | return result;
22 | };
23 |
24 | let nums = [2, 7, 11, 15];
25 | let target = 9;
26 | console.log(twoSum(nums, target));
27 |
28 | nums = [3, 2, 4];
29 | target = 6;
30 | console.log(twoSum(nums, target));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/valid_parentheses.js:
--------------------------------------------------------------------------------
1 | var isValid = function (s) {
2 | // Stack to store left symbols
3 | const leftSymbols = [];
4 | // Loop for each character of the string
5 | for (let i = 0; i < s.length; i++) {
6 | // If left symbol is encountered
7 | if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
8 | leftSymbols.push(s[i]);
9 | }
10 | // If right symbol is encountered
11 | else if (s[i] === ')' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '(') {
12 | leftSymbols.pop();
13 | } else if (s[i] === '}' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '{') {
14 | leftSymbols.pop();
15 | } else if (s[i] === ']' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '[') {
16 | leftSymbols.pop();
17 | }
18 | // If none of the valid symbols is encountered
19 | else {
20 | return false;
21 | }
22 | }
23 | return leftSymbols.length === 0;
24 | };
25 |
26 | console.log(isValid("()"));
27 | console.log(isValid("()[]{}"));
28 | console.log(isValid("(]"));
29 | console.log(isValid("([)]"));
30 | console.log(isValid("{[]}"));
--------------------------------------------------------------------------------
/LeetCode/JavaScript/src/zigzag_conversion.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Anirudh Sharma
3 | */
4 | var convert = function (s, numRows) {
5 | // Base conditions
6 | if (s === null || numRows <= 0) {
7 | return "";
8 | }
9 | if (numRows === 1) {
10 | return s;
11 | }
12 | // Resultant String
13 | let result = ""
14 | // Step size
15 | const step = 2 * numRows - 2;
16 | // Loop for each row
17 | for (let i = 0; i < numRows; i++) {
18 | // Loop for each character in the row
19 | for (let j = i; j < s.length; j += step) {
20 | result += s[j];
21 | if (i != 0 && i != numRows - 1 && (j + step - 2 * i) < s.length) {
22 | result += s[j + step - 2 * i];
23 | }
24 | }
25 | }
26 | return result;
27 | };
28 |
29 | let s = "PAYPALISHIRING"
30 | let numRows = 3;
31 | console.log(convert(s, numRows));
32 |
33 | numRows = 4;
34 | console.log(convert(s, numRows));
35 |
36 | s = "ANIRUDHSHARMAISGREAT";
37 | numRows = 5;
38 | console.log(convert(s, numRows));
--------------------------------------------------------------------------------
/LeetCode/Kotlin/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
2 |
3 | plugins {
4 | kotlin("jvm") version "1.4.10"
5 | application
6 | }
7 | group = "org.redquark.tutorials.leetcode"
8 | version = "1.0-SNAPSHOT"
9 |
10 | repositories {
11 | mavenCentral()
12 | }
13 | dependencies {
14 | testImplementation(kotlin("test-junit5"))
15 | }
16 | tasks.withType() {
17 | kotlinOptions.jvmTarget = "13"
18 | }
19 | application {
20 | mainClassName = "MainKt"
21 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/LeetCode/Kotlin/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "Kotlin"
3 |
4 |
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/AddTwoNumbers.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | private fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
7 | var head1 = l1
8 | var head2 = l2
9 | // Head of the new linked list - this is the head of the resultant list
10 | var head: ListNode? = null
11 | // Reference of head which is null at this point
12 | var temp: ListNode? = null
13 | // Carry
14 | var carry = 0
15 | // Loop for the two lists
16 | while (head1 != null || head2 != null) {
17 | // At the start of each iteration, we should add carry from the last iteration
18 | var sum = carry
19 | // Since the lengths of the lists may be unequal, we are checking if the
20 | // current node is null for one of the lists
21 | if (head1 != null) {
22 | sum += head1.`val`
23 | head1 = head1.next
24 | }
25 | if (head2 != null) {
26 | sum += head2.`val`
27 | head2 = head2.next
28 | }
29 | // At this point, we will add the total sum % 10 to the new node
30 | // in the resultant list
31 | val node = ListNode(sum % 10)
32 | // Carry to be added in the next iteration
33 | carry = sum / 10
34 | // If this is the first node or head
35 | if (temp == null) {
36 | head = node
37 | temp = head
38 | } else {
39 | temp.next = node
40 | temp = temp.next
41 | }
42 | }
43 | // After the last iteration, we will check if there is carry left
44 | // If it's left then we will create a new node and add it
45 | if (carry > 0) {
46 | temp!!.next = ListNode(carry)
47 | }
48 | return head
49 | }
50 |
51 | fun main() {
52 | val head1 = ListNode(2)
53 | head1.next = ListNode(4)
54 | head1.next!!.next = ListNode(3)
55 |
56 | val head2 = ListNode(5)
57 | head2.next = ListNode(6)
58 | head2.next!!.next = ListNode(4)
59 |
60 | var result = addTwoNumbers(head1, head2)
61 |
62 | while (result != null) {
63 | print(result.`val`.toString() + " ")
64 | result = result.next
65 | }
66 | }
67 |
68 | /**
69 | * This class represents each node in the linked list
70 | */
71 | internal class ListNode(val `val`: Int) {
72 | var next: ListNode? = null
73 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ContainerWithMostWater.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun maxArea(height: IntArray): Int {
4 | // Maximum area will be stored in this variable
5 | var maximumArea = Int.MIN_VALUE
6 | // Left and right pointers
7 | var left = 0
8 | var right = height.size - 1
9 | // Loop until left and right meet
10 | while (left < right) {
11 | // Shorter pole/vertical line
12 | val shorterLine = height[left].coerceAtMost(height[right])
13 | // Update maximum area if required
14 | maximumArea = maximumArea.coerceAtLeast(shorterLine * (right - left))
15 | // If there is a longer vertical line present
16 | if (height[left] < height[right]) {
17 | left++
18 | } else {
19 | right--
20 | }
21 | }
22 | return maximumArea
23 | }
24 |
25 | fun main() {
26 | println(maxArea(intArrayOf(1, 8, 6, 2, 5, 4, 8, 3, 7)))
27 | println(maxArea(intArrayOf(1, 1)))
28 | println(maxArea(intArrayOf(4, 3, 2, 1, 4)))
29 | println(maxArea(intArrayOf(1, 2, 1)))
30 | println(maxArea(intArrayOf(3, 9, 3, 4, 7, 2, 12, 6)))
31 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/DivideTwoIntegers.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class DivideTwoIntegers {
4 |
5 | fun divide(dividend: Int, divisor: Int): Int {
6 | // Check for overflow
7 | if (divisor == 0 || dividend == Int.MIN_VALUE && divisor == -1) {
8 | return Int.MAX_VALUE
9 | }
10 | // Sign of result
11 | val sign = if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0) -1 else 1
12 | // Quotient
13 | var quotient = 0
14 | // Take the absolute value
15 | var absoluteDividend = Math.abs(dividend.toLong())
16 | val absoluteDivisor = Math.abs(divisor.toLong())
17 | // Loop until the dividend is greater than divisor
18 | while (absoluteDividend >= absoluteDivisor) {
19 | // This represents the number of bits shifted or
20 | // how many times we can double the number
21 | var shift = 0
22 | while (absoluteDividend >= absoluteDivisor shl shift) {
23 | shift++
24 | }
25 | // Add the number of times we shifted to the quotient
26 | quotient += 1 shl shift - 1
27 | // Update the dividend for the next iteration
28 | absoluteDividend -= absoluteDivisor shl shift - 1
29 | }
30 | return if (sign == -1) -quotient else quotient
31 | }
32 | }
33 |
34 | fun main() {
35 | val d = DivideTwoIntegers()
36 | println(d.divide(10, 3))
37 | println(d.divide(7, -3))
38 | println(d.divide(0, 1))
39 | println(d.divide(1, 1))
40 | println(d.divide(Int.MAX_VALUE, 1))
41 | println(d.divide(Int.MIN_VALUE, 1))
42 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/FourSum.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | import java.util.*
4 | import kotlin.collections.ArrayList
5 |
6 |
7 | fun fourSum(nums: IntArray, target: Int): List> {
8 | // Resultant list
9 | val quadruplets: MutableList> = ArrayList()
10 | // Base condition
11 | if (nums.size < 4) {
12 | return quadruplets
13 | }
14 | // Sort the array
15 | Arrays.sort(nums)
16 | // Length of the array
17 | val n = nums.size
18 | // Loop for each element in the array
19 | for (i in 0 until n - 3) {
20 | // Check for skipping duplicates
21 | if (i > 0 && nums[i] == nums[i - 1]) {
22 | continue
23 | }
24 | // Reducing problem to 3Sum problem
25 | for (j in i + 1 until n - 2) {
26 | // Check for skipping duplicates
27 | if (j != i + 1 && nums[j] == nums[j - 1]) {
28 | continue
29 | }
30 | // Left and right pointers
31 | var k = j + 1
32 | var l = n - 1
33 | // Reducing to two sum problem
34 | while (k < l) {
35 | val currentSum = nums[i] + nums[j] + nums[k] + nums[l]
36 | when {
37 | currentSum < target -> {
38 | k++
39 | }
40 | currentSum > target -> {
41 | l--
42 | }
43 | else -> {
44 | quadruplets.add(listOf(nums[i], nums[j], nums[k], nums[l]))
45 | k++
46 | l--
47 | // Check for skipping duplicates
48 | while (k < l && nums[k] == nums[k - 1]) {
49 | k++
50 | }
51 | while (k < l && nums[l] == nums[l + 1]) {
52 | l--
53 | }
54 | }
55 | }
56 | }
57 | }
58 | }
59 | return quadruplets
60 | }
61 |
62 | fun main() {
63 | println(fourSum(intArrayOf(1, 0, -1, 0, -2, 2), 0))
64 | println(fourSum(intArrayOf(), 0))
65 | println(fourSum(intArrayOf(1, 2, 3, 4), 10))
66 | println(fourSum(intArrayOf(0, 0, 0, 0), 0))
67 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/GenerateParentheses.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun generateParenthesis(n: Int): List {
4 | // Resultant list
5 | val result: MutableList = ArrayList()
6 | /// Recursively generate parentheses
7 | generateParenthesis(result, "", 0, 0, n)
8 | return result
9 | }
10 |
11 | fun generateParenthesis(result: MutableList, s: String, open: Int, close: Int, n: Int) {
12 | // Base case
13 | if (open == n && close == n) {
14 | result.add(s)
15 | return
16 | }
17 | // If the number of open parentheses is less than the given n
18 | if (open < n) {
19 | generateParenthesis(result, "$s(", open + 1, close, n)
20 | }
21 | // If we need more close parentheses to balance
22 | if (close < open) {
23 | generateParenthesis(result, "$s)", open, close + 1, n)
24 | }
25 | }
26 |
27 | fun main() {
28 | println(generateParenthesis(3))
29 | println(generateParenthesis(1))
30 | println(generateParenthesis(8))
31 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ImplementStrStr.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class ImplementStrStr {
4 | fun strStr(haystack: String, needle: String): Int {
5 | // Special case
6 | if (haystack == needle) {
7 | return 0
8 | }
9 | // length of the needle
10 | val needleLength = needle.length
11 | // Loop through the haystack and slide the window
12 | for (i in 0 until haystack.length - needleLength + 1) {
13 | // Check if the substring equals to the needle
14 | if (haystack.substring(i, i + needleLength) == needle) {
15 | return i
16 | }
17 | }
18 | return -1
19 | }
20 | }
21 |
22 | fun main() {
23 | val i = ImplementStrStr()
24 | var haystack = "hello"
25 | var needle = "ll"
26 | println(i.strStr(haystack, needle))
27 | haystack = "aaaaa"
28 | needle = "bba"
29 | println(i.strStr(haystack, needle))
30 | haystack = ""
31 | needle = ""
32 | println(i.strStr(haystack, needle))
33 | haystack = "abc"
34 | needle = "c"
35 | println(i.strStr(haystack, needle))
36 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/IntegerToRoman.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun intToRoman(num: Int): String? {
4 | val M = arrayOf("", "M", "MM", "MMM")
5 | val C = arrayOf("", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM")
6 | val X = arrayOf("", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC")
7 | val I = arrayOf("", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX")
8 | return M[num / 1000] + C[num % 1000 / 100] + X[num % 100 / 10] + I[num % 10]
9 | }
10 |
11 | fun main() {
12 | println(intToRoman(3))
13 | println(intToRoman(4))
14 | println(intToRoman(9))
15 | println(intToRoman(58))
16 | println(intToRoman(1994))
17 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LetterCombinationsOfAPhoneNumber.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun letterCombinations(digits: String): List {
4 | // Resultant list
5 | val combinations: MutableList = mutableListOf()
6 | // Base condition
7 | if (digits.isEmpty()) {
8 | return combinations
9 | }
10 | // Mappings of letters and numbers
11 | val lettersAndNumbersMappings = arrayOf(
12 | "Anirudh",
13 | "is awesome",
14 | "abc",
15 | "def",
16 | "ghi",
17 | "jkl",
18 | "mno",
19 | "pqrs",
20 | "tuv",
21 | "wxyz"
22 | )
23 | findCombinations(combinations, digits, StringBuilder(), 0, lettersAndNumbersMappings)
24 | return combinations
25 | }
26 |
27 | fun findCombinations(combinations: MutableList, digits: String, previous: StringBuilder, index: Int, lettersAndNumbersMappings: Array) {
28 | // Base condition for recursion to stop
29 | if (index == digits.length) {
30 | combinations.add(previous.toString())
31 | return
32 | }
33 | // Get the letters corresponding to the current index of digits string
34 | val letters = lettersAndNumbersMappings[digits[index] - '0']
35 | // Loop through all the characters in the current combination of letters
36 | for (c in letters.toCharArray()) {
37 | findCombinations(combinations, digits, previous.append(c), index + 1, lettersAndNumbersMappings)
38 | previous.deleteCharAt(previous.length - 1)
39 | }
40 | }
41 |
42 | fun main() {
43 | println(letterCombinations("23"))
44 | println(letterCombinations(""))
45 | println(letterCombinations("2"))
46 | }
47 |
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LongestCommonPrefix.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun longestCommonPrefix(strs: Array): String {
4 | // Longest common prefix string
5 | val longestCommonPrefix = StringBuilder()
6 | // Base condition
7 | if (strs.isEmpty()) {
8 | return longestCommonPrefix.toString()
9 | }
10 | // Find the minimum length string from the array
11 | var minimumLength = strs[0].length
12 | for (i in 1 until strs.size) {
13 | minimumLength = minimumLength.coerceAtMost(strs[i].length)
14 | }
15 | // Loop for the minimum length
16 | for (i in 0 until minimumLength) {
17 | // Get the current character from first string
18 | val current = strs[0][i]
19 | // Check if this character is found in all other strings or not
20 | for (str in strs) {
21 | if (str[i] != current) {
22 | return longestCommonPrefix.toString()
23 | }
24 | }
25 | longestCommonPrefix.append(current)
26 | }
27 | return longestCommonPrefix.toString()
28 | }
29 |
30 | fun main() {
31 | println(longestCommonPrefix(arrayOf("flower", "flow", "flight")))
32 | println(longestCommonPrefix(arrayOf("dog", "racecar", "car")))
33 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LongestSubstringWithoutRepeatingCharacters.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 |
4 | private fun lengthOfLongestSubstring(s: String): Int {
5 | // Base condition
6 | if (s == "") {
7 | return 0
8 | }
9 | // Starting window index
10 | var start = 0
11 | // Ending window index
12 | var end = 0
13 | // Maximum length of substring
14 | var maxLength = 0
15 | // This set will store the unique characters
16 | val uniqueCharacters: MutableSet = HashSet()
17 | while (end < s.length) {
18 | if (uniqueCharacters.add(s[end])) {
19 | end++
20 | maxLength = maxLength.coerceAtLeast(uniqueCharacters.size)
21 | } else {
22 | uniqueCharacters.remove(s[start])
23 | start++
24 | }
25 | }
26 | return maxLength
27 | }
28 |
29 | fun main() {
30 | var s = "abcabcbb"
31 | println(lengthOfLongestSubstring(s))
32 |
33 | s = "bbbbb"
34 | println(lengthOfLongestSubstring(s))
35 |
36 | s = "pwwkew"
37 | println(lengthOfLongestSubstring(s))
38 |
39 | s = ""
40 | println(lengthOfLongestSubstring(s))
41 |
42 | s = "aab"
43 | println(lengthOfLongestSubstring(s))
44 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/LongestValidParentheses.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun longestValidParentheses(s: String): Int {
4 | // Variable to store the longest valid parentheses
5 | var count = 0
6 | // Left counter will count the number of '('
7 | var left = 0
8 | // Right counter will count the number of ')'
9 | var right = 0
10 | // Loop through the string from left to right.
11 | // This will take care of extra right parentheses
12 | for (element in s) {
13 | // Current character
14 | if (element == '(') {
15 | left++
16 | }
17 | if (element == ')') {
18 | right++
19 | }
20 | // If both left and right are equal,
21 | // it means we have a valid substring
22 | if (left == right) {
23 | count = count.coerceAtLeast(left + right)
24 | }
25 | // If right is greater than left,
26 | // it means we need to set both
27 | // counters to zero
28 | if (right > left) {
29 | right = 0
30 | left = right
31 | }
32 | }
33 | // Reset left and right
34 | right = 0
35 | left = right
36 | // Follow the same approach but now loop the string
37 | // from right to left. This will take care of extra
38 | // left parentheses
39 | for (i in s.length - 1 downTo 0) {
40 | // Current character
41 | val c = s[i]
42 | if (c == '(') {
43 | left++
44 | }
45 | if (c == ')') {
46 | right++
47 | }
48 | // If both left and right are equal,
49 | // it means we have a valid substring
50 | if (left == right) {
51 | count = count.coerceAtLeast(left + right)
52 | }
53 | // If right is greater than left,
54 | // it means we need to set both
55 | // counters to zero
56 | if (left > right) {
57 | right = 0
58 | left = right
59 | }
60 | }
61 | return count
62 | }
63 |
64 | fun main() {
65 | var s = "(()"
66 | println(longestValidParentheses(s))
67 |
68 | s = ")()())"
69 | println(longestValidParentheses(s))
70 |
71 | s = ""
72 | println(longestValidParentheses(s))
73 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/NextPermutation.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class NextPermutation {
4 |
5 | fun nextPermutation(nums: IntArray): IntArray {
6 | // Length of the array
7 | val n = nums.size
8 | // Index of the first element that is smaller than
9 | // the element to its right.
10 | var index = -1
11 | // Loop from right to left
12 | for (i in n - 1 downTo 1) {
13 | if (nums[i] > nums[i - 1]) {
14 | index = i - 1
15 | break
16 | }
17 | }
18 | // Base condition
19 | if (index == -1) {
20 | reverse(nums, 0, n - 1)
21 | return nums
22 | }
23 | var j = n - 1
24 | // Again swap from right to left to find first element
25 | // that is greater than the above find element
26 | for (i in n - 1 downTo index + 1) {
27 | if (nums[i] > nums[index]) {
28 | j = i
29 | break
30 | }
31 | }
32 | // Swap the elements
33 | swap(nums, index, j)
34 | // Reverse the elements from index + 1 to the nums.length
35 | reverse(nums, index + 1, n - 1)
36 | return nums
37 | }
38 |
39 | private fun reverse(nums: IntArray, i: Int, j: Int) {
40 | var iIndex = i
41 | var jIndex = j
42 | while (iIndex < jIndex) {
43 | swap(nums, iIndex, jIndex)
44 | iIndex++
45 | jIndex--
46 | }
47 | }
48 |
49 | private fun swap(nums: IntArray, i: Int, index: Int) {
50 | val temp = nums[index]
51 | nums[index] = nums[i]
52 | nums[i] = temp
53 | }
54 | }
55 |
56 | fun main() {
57 | val n = NextPermutation()
58 | println(n.nextPermutation(intArrayOf(1, 2, 3)).contentToString())
59 | println(n.nextPermutation(intArrayOf(3, 2, 1)).contentToString())
60 | println(n.nextPermutation(intArrayOf(1, 1, 5)).contentToString())
61 | println(n.nextPermutation(intArrayOf(1)).contentToString())
62 | println(n.nextPermutation(intArrayOf(4, 5, 3, 2, 1)).contentToString())
63 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/PalindromeNumber.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun isPalindrome(x: Int): Boolean {
4 | // Base condition
5 | if (x < 0) {
6 | return false
7 | }
8 | // Store the number in a variable
9 | var number = x
10 | // This will store the reverse of the number
11 | var reverse = 0
12 | while (number > 0) {
13 | reverse = reverse * 10 + number % 10
14 | number /= 10
15 | }
16 | return x == reverse
17 | }
18 |
19 | fun main() {
20 | println(isPalindrome(121))
21 | println(isPalindrome(-121))
22 | println(isPalindrome(10))
23 | println(isPalindrome(-101))
24 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RegularExpressionMatching.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun isMatch(s: String, p: String): Boolean {
4 | val rows = s.length
5 | val columns = p.length
6 | /// Base conditions
7 | if (rows == 0 && columns == 0) {
8 | return true
9 | }
10 | if (columns == 0) {
11 | return false
12 | }
13 | // DP array
14 | val dp = Array(rows + 1) { BooleanArray(columns + 1) }
15 | // Empty string and empty pattern are a match
16 | dp[0][0] = true
17 | // Deals with patterns with *
18 | for (i in 2 until columns + 1) {
19 | if (p[i - 1] == '*') {
20 | dp[0][i] = dp[0][i - 2]
21 | }
22 | }
23 | // For remaining characters
24 | for (i in 1 until rows + 1) {
25 | for (j in 1 until columns + 1) {
26 | if (s[i - 1] == p[j - 1] || p[j - 1] == '.') {
27 | dp[i][j] = dp[i - 1][j - 1]
28 | } else if (j > 1 && p[j - 1] == '*') {
29 | dp[i][j] = dp[i][j - 2]
30 | if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) {
31 | dp[i][j] = dp[i][j] or dp[i - 1][j]
32 | }
33 | }
34 | }
35 | }
36 | return dp[rows][columns]
37 | }
38 |
39 | fun main() {
40 | println(isMatch("aa", "a"))
41 | println(isMatch("aa", "a*"))
42 | println(isMatch("ab", "."))
43 | println(isMatch("aab", "c*a*b"))
44 | println(isMatch("mississippi", "mis*is*p*."))
45 | println(isMatch("", ".*"))
46 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RemoveDuplicatesFromSortedArray.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class RemoveDuplicatesFromSortedArray {
4 |
5 | fun removeDuplicates(nums: IntArray): Int {
6 | // Length of the updated array
7 | var count = 0
8 | // Loop for all the elements in the array
9 | for (i in nums.indices) {
10 | // If the current element is equal to the next element, we skip
11 | if (i < nums.size - 1 && nums[i] == nums[i + 1]) {
12 | continue
13 | }
14 | // We will update the array in place
15 | nums[count] = nums[i]
16 | count++
17 | }
18 | return count
19 | }
20 | }
21 |
22 | fun main() {
23 | val r = RemoveDuplicatesFromSortedArray()
24 | println(r.removeDuplicates(intArrayOf(1, 1, 2)))
25 | println(r.removeDuplicates(intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4)))
26 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RemoveElement.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class RemoveElement {
4 | fun removeElement(nums: IntArray, `val`: Int): Int {
5 | // Counter for keeping track of elements other than val
6 | var count = 0
7 | // Loop through all the elements of the array
8 | for (i in nums.indices) {
9 | // If the element is not val
10 | if (nums[i] != `val`) {
11 | nums[count++] = nums[i]
12 | }
13 | }
14 | return count
15 | }
16 | }
17 |
18 | fun main() {
19 | val r = RemoveElement()
20 | println(r.removeElement(intArrayOf(3, 2, 2, 3), 3))
21 | println(r.removeElement(intArrayOf(0, 1, 2, 2, 3, 0, 4, 2), 2))
22 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RemoveNthNodeFromEndOfList.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | private fun removeNthFromEnd(head: ListNode19?, n: Int): ListNode19? {
4 | // Two pointers - fast and slow
5 | var newHead: ListNode19? = head
6 | var slow = newHead
7 | var fast = newHead
8 | // Move fast pointer n steps ahead
9 | for (i in 0 until n) {
10 | if (fast?.next == null) {
11 | // If n is equal to the number of nodes, delete the head node
12 | if (i == n - 1) {
13 | newHead = newHead!!.next
14 | }
15 | return newHead
16 | }
17 | fast = fast.next
18 | }
19 | // Loop until we reach to the end.
20 | // Now we will move both fast and slow pointers
21 | while (fast?.next != null) {
22 | slow = slow!!.next
23 | fast = fast.next
24 | }
25 | // Delink the nth node from last
26 | if (slow?.next != null) {
27 | slow.next = slow.next!!.next
28 | }
29 | return newHead
30 | }
31 |
32 | private fun printList(node: ListNode19?) {
33 | var newNode = node
34 | while (newNode != null) {
35 | print(newNode.`val`.toString() + " ")
36 | newNode = newNode.next
37 | }
38 | println()
39 | }
40 |
41 | fun main() {
42 | var head = ListNode19(1)
43 | head.next = ListNode19(2)
44 | head.next!!.next = ListNode19(3)
45 | head.next!!.next!!.next = ListNode19(4)
46 | head.next!!.next!!.next!!.next = ListNode19(5)
47 | printList(removeNthFromEnd(head, 2))
48 |
49 | head = ListNode19(1)
50 | printList(removeNthFromEnd(head, 1))
51 |
52 | head = ListNode19(1)
53 | head.next = ListNode19(2)
54 | printList(removeNthFromEnd(head, 1))
55 | }
56 |
57 | /**
58 | * This class represents each node in the linked list
59 | */
60 | internal class ListNode19(val `val`: Int) {
61 | var next: ListNode19? = null
62 | }
63 |
64 |
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ReverseInteger.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun reverse(x: Int): Int {
4 | var num = x
5 | var isNegative = false
6 | if (num < 0) {
7 | isNegative = true
8 | num = -num
9 | }
10 | var reverse: Long = 0
11 | while (num > 0) {
12 | reverse = reverse * 10 + num % 10
13 | num /= 10
14 | }
15 | return if (reverse > Int.MAX_VALUE) {
16 | 0
17 | } else (if (isNegative) -reverse else reverse).toInt()
18 | }
19 |
20 | fun main() {
21 | println(reverse(321))
22 | println(reverse(-45315))
23 | println(reverse(-450))
24 | println(reverse(Int.MAX_VALUE))
25 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/RomanToInteger.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun romanToInt(s: String): Int {
4 | // Map to store romans numerals
5 | val romanMap: MutableMap = HashMap()
6 | // Fill the map
7 | romanMap['I'] = 1
8 | romanMap['V'] = 5
9 | romanMap['X'] = 10
10 | romanMap['L'] = 50
11 | romanMap['C'] = 100
12 | romanMap['D'] = 500
13 | romanMap['M'] = 1000
14 | // Length of the given string
15 | val n = s.length
16 | // Variable to store result
17 | var num = romanMap[s[n - 1]]!!
18 | // Loop for each character from right to left
19 | for (i in n - 2 downTo 0) {
20 | // Check if the character at right of current character is
21 | // bigger or smaller
22 | if (romanMap[s[i]]!! >= romanMap[s[i + 1]]!!) {
23 | num += romanMap[s[i]]!!
24 | } else {
25 | num -= romanMap[s[i]]!!
26 | }
27 | }
28 | return num
29 | }
30 |
31 | fun main() {
32 | println(romanToInt("III"))
33 | println(romanToInt("IV"))
34 | println(romanToInt("IX"))
35 | println(romanToInt("LVIII"))
36 | println(romanToInt("MCMXCIV"))
37 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/SearchInRotatedSortedArray.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | fun search(nums: IntArray, target: Int): Int {
7 | // Special case
8 | if (nums.isEmpty()) {
9 | return -1
10 | }
11 | // Left and right pointers in the array
12 | var left = 0
13 | var right = nums.size - 1
14 | // First step is to find the pivot where the
15 | // array is rotated
16 | while (left < right) {
17 | // Middle pointer
18 | val middle = left + (right - left) / 2
19 | // If the element at the mid is greater than
20 | // the element at the right then we can say that
21 | // the array is rotated after middle index
22 | if (nums[middle] > nums[right]) {
23 | left = middle + 1
24 | } else {
25 | right = middle
26 | }
27 | }
28 | // After the above loop is completed, then the
29 | // left index will point to the pivot
30 | val pivot = left
31 | left = 0
32 | right = nums.size - 1
33 | // Now we will find in which half of the array,
34 | // our target is present
35 | if (target >= nums[pivot] && target <= nums[right]) {
36 | left = pivot
37 | } else {
38 | right = pivot
39 | }
40 | // Now perform normal binary search
41 | while (left <= right) {
42 | val middle = left + (right - left) / 2
43 | if (nums[middle] == target) {
44 | return middle
45 | } else if (target < nums[middle]) {
46 | right = middle - 1
47 | } else {
48 | left = middle + 1
49 | }
50 | }
51 | return -1
52 | }
53 |
54 | fun main() {
55 | var nums = intArrayOf(4, 5, 6, 7, 0, 1, 2)
56 | var target = 0
57 | println(search(nums, target))
58 | nums = intArrayOf(4, 5, 6, 7, 0, 1, 2)
59 | target = 3
60 | println(search(nums, target))
61 | nums = intArrayOf(1)
62 | target = 0
63 | println(search(nums, target))
64 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/StringToInteger.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | fun myAtoi(s: String): Int {
4 | var str = s
5 | // Base condition
6 | if (str.isEmpty()) {
7 | return 0
8 | }
9 | // MAX and MIN values for integers
10 | val max = 2147483647
11 | val min = -2147483648
12 | // Trimmed string
13 | str = str.replace("^\\s+".toRegex(), "")
14 | // Counter
15 | var i = 0
16 | // Flag to indicate if the number is negative
17 | val isNegative: Boolean = str.startsWith("-")
18 | // Flag to indicate if the number is positive
19 | val isPositive: Boolean = str.startsWith("+")
20 | if (isNegative) {
21 | i++
22 | } else if (isPositive) {
23 | i++
24 | }
25 | // This will store the converted number
26 | var number = 0.0
27 | // Loop for each numeric character in the string iff numeric characters are leading
28 | // characters in the string
29 | while (i < str.length && str[i] >= '0' && str[i] <= '9') {
30 | number = number * 10 + (str.get(i) - '0')
31 | i++
32 | }
33 | // Give back the sign to the converted number
34 | number = if (isNegative) -number else number
35 | if (number < min) {
36 | return min
37 | }
38 | return if (number > max) {
39 | max
40 | } else number.toInt()
41 | }
42 |
43 |
44 | fun main() {
45 | println(myAtoi("42"))
46 | println(myAtoi(" -42"))
47 | println(myAtoi("4193 with words"))
48 | println(myAtoi("words and 987"))
49 | println(myAtoi("-91283472332"))
50 | println(myAtoi("91283472332"))
51 | println(myAtoi("9223372036854775808"))
52 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/SwapNodesInPairs.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | class SwapNodesInPairs {
4 |
5 | internal fun swapPairs(head: ListNode?): ListNode? {
6 | // Dummy node
7 | val dummy = ListNode(0)
8 | // Point the next of dummy node to the head
9 | dummy.next = head
10 | // This node will be used to traverse the list
11 | var current: ListNode? = dummy
12 | // Loop until we reach to the second last node
13 | while (current!!.next != null && current.next!!.next != null) {
14 | // First node of the pair
15 | val first = current.next
16 | // Second node of the pair
17 | val second = current.next!!.next
18 | // Point the next of first node to the node after second node
19 | first!!.next = second!!.next
20 | // Now the current node's next should be the second node
21 | current.next = second
22 | // Linking the original second node to the first node
23 | current.next!!.next = first
24 | // Move the pointer two nodes ahead
25 | current = current.next!!.next
26 | }
27 | return dummy.next
28 | }
29 |
30 | internal fun printList(head: ListNode?) {
31 | var temp = head
32 | while (temp != null) {
33 | print(temp.`val`.toString() + " ")
34 | temp = temp.next
35 | }
36 | println()
37 | }
38 |
39 | internal class ListNode(var `val`: Int) {
40 | var next: ListNode? = null
41 | }
42 | }
43 |
44 | fun main() {
45 | val s = SwapNodesInPairs()
46 | var head = SwapNodesInPairs.ListNode(1)
47 | head.next = SwapNodesInPairs.ListNode(2)
48 | head.next!!.next = SwapNodesInPairs.ListNode(3)
49 | head.next!!.next!!.next = SwapNodesInPairs.ListNode(4)
50 | s.printList(s.swapPairs(head))
51 |
52 | s.printList(s.swapPairs(null))
53 |
54 | head = SwapNodesInPairs.ListNode(1)
55 | s.printList(s.swapPairs(head))
56 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ThreeSum.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | import java.util.*
4 | import kotlin.collections.ArrayList
5 |
6 |
7 | fun threeSum(nums: IntArray): List> {
8 | // Sort the array
9 | Arrays.sort(nums)
10 | // Length of the array
11 | val n = nums.size
12 | // Resultant list
13 | val triplets: MutableList> = ArrayList()
14 | // Loop for each element of the array
15 | for (i in 0 until n) {
16 | // Skip the duplicates
17 | if (i > 0 && nums[i] == nums[i - 1]) {
18 | continue
19 | }
20 | // Left and right pointers
21 | var j = i + 1
22 | var k = n - 1
23 | // Loop for all the remaining pairs
24 | while (j < k) {
25 | when {
26 | nums[i] + nums[j] + nums[k] == 0 -> {
27 | triplets.add(listOf(nums[i], nums[j], nums[k]))
28 | j++
29 | // Never let j refer to the same value twice (in an output) to avoid duplicates
30 | while (j < k && nums[j] == nums[j - 1]) {
31 | j++
32 | }
33 | }
34 | nums[i] + nums[j] + nums[k] < 0 -> {
35 | j++
36 | }
37 | else -> {
38 | k--
39 | }
40 | }
41 | }
42 | }
43 | return triplets
44 | }
45 |
46 | fun main() {
47 | println(threeSum(intArrayOf(-1, 0, 1, 2, -1, -4)))
48 | println(threeSum(intArrayOf()))
49 | println(threeSum(intArrayOf(0)))
50 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ThreeSumClosest.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | import java.util.*
4 | import kotlin.math.abs
5 |
6 | fun threeSumClosest(nums: IntArray, target: Int): Int {
7 | // Sort the array
8 | Arrays.sort(nums)
9 | // Length of the array
10 | val n = nums.size
11 | // Result
12 | var closest = nums[0] + nums[1] + nums[n - 1]
13 | // Loop for each element of the array
14 | for (i in 0 until n - 2) {
15 | // Left and right pointers
16 | var j = i + 1
17 | var k = n - 1
18 | // Loop for all other pairs
19 | while (j < k) {
20 | val sum = nums[i] + nums[j] + nums[k]
21 | if (sum <= target) {
22 | j++
23 | } else {
24 | k--
25 | }
26 | if (abs(closest - target) > abs(sum - target)) {
27 | closest = sum
28 | }
29 | }
30 | }
31 | return closest
32 | }
33 |
34 | fun main() {
35 | val nums = intArrayOf(-1, 2, 1, -4)
36 | val target = 1
37 | println(threeSumClosest(nums, target))
38 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/TwoSum.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | /**
4 | * @param nums - input array of numbers
5 | * @param target - the value of target
6 | * @return - array of indices of two numbers which will add up to target
7 | */
8 | fun twoSum(nums: IntArray, target: Int): IntArray {
9 | // Array to store result
10 | val result = IntArray(2)
11 | // This map will store the difference and the corresponding index
12 | val map: MutableMap = HashMap()
13 | // Loop through the entire array
14 | for (i in nums.indices) {
15 | // If we have seen the current element before
16 | // It means we have already encountered the other number of the pair
17 | if (map.containsKey(nums[i])) {
18 | // Index of the current element
19 | result[0] = i
20 | // Index of the other element of the pair
21 | result[1] = map[nums[i]]!!
22 | break
23 | } else {
24 | // Save the difference of the target and the current element
25 | // with the index of the current element
26 | map[target - nums[i]] = i
27 | }
28 | }
29 | return result
30 | }
31 |
32 | fun main() {
33 | var nums = intArrayOf(2, 7, 11, 15)
34 | var target = 9
35 | println(twoSum(nums, target).contentToString())
36 |
37 | nums = intArrayOf(3, 2, 4)
38 | target = 6
39 | println(twoSum(nums, target).contentToString())
40 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ValidParentheses.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | import java.util.*
4 |
5 | fun isValid(s: String): Boolean {
6 | // Stack to store left symbols
7 | val leftSymbols = Stack()
8 | // Loop for each character of the string
9 | for (c in s.toCharArray()) {
10 | // If left symbol is encountered
11 | if (c == '(' || c == '{' || c == '[') {
12 | leftSymbols.push(c)
13 | }
14 | // If right symbol is encountered
15 | else if (c == ')' && !leftSymbols.isEmpty() && leftSymbols.peek() == '(') {
16 | leftSymbols.pop()
17 | } else if (c == '}' && !leftSymbols.isEmpty() && leftSymbols.peek() == '{') {
18 | leftSymbols.pop()
19 | } else if (c == ']' && !leftSymbols.isEmpty() && leftSymbols.peek() == '[') {
20 | leftSymbols.pop()
21 | }
22 | // If none of the valid symbols is encountered
23 | else {
24 | return false
25 | }
26 | }
27 | return leftSymbols.isEmpty()
28 | }
29 |
30 | fun main() {
31 | println(isValid("()"))
32 | println(isValid("()[]{}"))
33 | println(isValid("(]"))
34 | println(isValid("([)]"))
35 | println(isValid("{[]}"))
36 | }
--------------------------------------------------------------------------------
/LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/ZigZagConversion.kt:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.leetcode
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | */
6 | private fun convert(s: String?, numRows: Int): String {
7 | // Base conditions
8 | if (s == null || s.isEmpty() || numRows <= 0) {
9 | return ""
10 | }
11 | if (numRows == 1) {
12 | return s
13 | }
14 | // Resultant string
15 | val result = StringBuilder()
16 | // Step size
17 | val step = 2 * numRows - 2
18 | // Loop for each row
19 | for (i in 0 until numRows) {
20 | // Loop for each character in the row
21 | var j = i
22 | while (j < s.length) {
23 | result.append(s[j])
24 | if (i != 0 && i != numRows - 1 && j + step - 2 * i < s.length) {
25 | result.append(s[j + step - 2 * i])
26 | }
27 | j += step
28 | }
29 | }
30 | return result.toString()
31 | }
32 |
33 | fun main() {
34 | var s = "PAYPALISHIRING"
35 | var numRows = 3
36 | println(convert(s, numRows))
37 | numRows = 4
38 | println(convert(s, numRows))
39 |
40 | s = "ANIRUDHSHARMAISGREAT"
41 | println(convert(s, numRows))
42 | }
43 |
--------------------------------------------------------------------------------
/LeetCode/Python/setup.py:
--------------------------------------------------------------------------------
1 | project_info = ["name - LeetCode",
2 | "version = 1.0",
3 | "description = LeetCode problems and their solutions in python",
4 | "author = Anirudh Sharma",
5 | "author_email = anirudh03sharma@gmail.com",
6 | "repo = https://github.com/ani03sha/RedQuarkTutorials/LeetCode/Python",
7 | ]
8 |
9 | print(project_info)
--------------------------------------------------------------------------------
/LeetCode/Python/src/Add_Two_Numbers.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class ListNode:
7 | def __init__(self, val):
8 | self.val = val
9 | self.next = None
10 |
11 |
12 | def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
13 | # Head of the new linked list - this is the head of the resultant list
14 | head = None
15 | # Reference of head which is null at this point
16 | temp = None
17 | # Carry
18 | carry = 0
19 | # Loop for the two lists
20 | while l1 is not None or l2 is not None:
21 | # At the start of each iteration, we should add carry from the last iteration
22 | sum_value = carry
23 | # Since the lengths of the lists may be unequal, we are checking if the
24 | # current node is null for one of the lists
25 | if l1 is not None:
26 | sum_value += l1.val
27 | l1 = l1.next
28 | if l2 is not None:
29 | sum_value += l2.val
30 | l2 = l2.next
31 | # At this point, we will add the total sum_value % 10 to the new node
32 | # in the resultant list
33 | node = ListNode(sum_value % 10)
34 | # Carry to be added in the next iteration
35 | carry = sum_value // 10
36 | # If this is the first node or head
37 | if temp is None:
38 | temp = head = node
39 | # for any other node
40 | else:
41 | temp.next = node
42 | temp = temp.next
43 | # After the last iteration, we will check if there is carry left
44 | # If it's left then we will create a new node and add it
45 | if carry > 0:
46 | temp.next = ListNode(carry)
47 | return head
48 |
49 |
50 | head1 = ListNode(2)
51 | head1.next = ListNode(4)
52 | head1.next.next = ListNode(3)
53 |
54 | head2 = ListNode(5)
55 | head2.next = ListNode(6)
56 | head2.next.next = ListNode(4)
57 |
58 | result = addTwoNumbers(head1, head2)
59 | while result is not None:
60 | print(str(result.val), end=" ")
61 | result = result.next
62 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Container_With_Most_Water.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from sys import maxsize
5 | from typing import List
6 |
7 |
8 | def maxArea(height: List[int]) -> int:
9 | # This variable will store the maximum area
10 | max_area = -maxsize
11 | # Left and right pointers
12 | left = 0
13 | right = len(height) - 1
14 | # Loop until the two pointers meet
15 | while left < right:
16 | # Shorter of the two lines
17 | shorter_line = min(height[left], height[right])
18 | max_area = max(max_area, shorter_line * (right - left))
19 | # If there is a longer vertical line present
20 | if height[left] < height[right]:
21 | left += 1
22 | else:
23 | right -= 1
24 | return max_area
25 |
26 |
27 | if __name__ == '__main__':
28 | print(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))
29 | print(maxArea([1, 1]))
30 | print(maxArea([4, 3, 2, 1, 4]))
31 | print(maxArea([1, 2, 3]))
32 | print(maxArea([3, 9, 3, 4, 7, 2, 12, 6]))
33 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Divide_Two_Integers.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class DivideTwoIntegers:
7 | @staticmethod
8 | def divide(dividend: int, divisor: int) -> int:
9 | # MAX and MIN values for integer
10 | MAX = 2147483647
11 | MIN = -2147483648
12 | # Check for overflow
13 | if divisor == 0 or (dividend == MIN and divisor == -1):
14 | return MAX
15 | # Sign of result`
16 | sign = -1 if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0) else 1
17 | # Quotient
18 | quotient = 0
19 | # Take the absolute value
20 | absoluteDividend = abs(dividend)
21 | absoluteDivisor = abs(divisor)
22 | # Loop until the dividend is greater than divisor
23 | while absoluteDividend >= absoluteDivisor:
24 | # This represents the number of bits shifted or
25 | # how many times we can double the number
26 | shift = 0
27 | while absoluteDividend >= (absoluteDivisor << shift):
28 | shift += 1
29 | # Add the number of times we shifted to the quotient
30 | quotient += (1 << (shift - 1))
31 | # Update the dividend for the next iteration
32 | absoluteDividend -= absoluteDivisor << (shift - 1)
33 | return -quotient if sign == -1 else quotient
34 |
35 |
36 | if __name__ == '__main__':
37 | d = DivideTwoIntegers()
38 | print(d.divide(10, 3))
39 | print(d.divide(7, -2))
40 | print(d.divide(2147483647, 1))
41 | print(d.divide(-2147483648, 1))
42 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Find_First_And_Last_Position_Of_Element_In_Sorted_Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @author Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def findFirstOccurrence(nums, target):
8 | # Left snd right pointers
9 | left, right = 0, len(nums) - 1
10 | # Index of first occurrence
11 | firstOccurrence = -1
12 | # Loop until the two pointers meet
13 | while left <= right:
14 | # Middle index
15 | middle = left + (right - left) // 2
16 | # Check if we have found the value
17 | if target == nums[middle]:
18 | firstOccurrence = middle
19 | right = middle - 1
20 | # If the target is less than the element
21 | # at the middle index
22 | elif target < nums[middle]:
23 | right = middle - 1
24 | # If the target is greater than the element
25 | # at the middle index
26 | else:
27 | left = middle + 1
28 | return firstOccurrence
29 |
30 |
31 | def findLastOccurrence(nums, target):
32 | # Left snd right pointers
33 | left, right = 0, len(nums) - 1
34 | # Index of first occurrence
35 | lastOccurrence = -1
36 | # Loop until the two pointers meet
37 | while left <= right:
38 | # Middle index
39 | middle = left + (right - left) // 2
40 | # Check if we have found the value
41 | if target == nums[middle]:
42 | lastOccurrence = middle
43 | left = middle + 1
44 | # If the target is less than the element
45 | # at the middle index
46 | elif target < nums[middle]:
47 | right = middle - 1
48 | # If the target is greater than the element
49 | # at the middle index
50 | else:
51 | left = middle + 1
52 | return lastOccurrence
53 |
54 |
55 | def searchRange(nums: List[int], target: int) -> List[int]:
56 | return [findFirstOccurrence(nums, target), findLastOccurrence(nums, target)]
57 |
58 |
59 | if __name__ == '__main__':
60 | nums = [5, 7, 7, 8, 8, 10]
61 | target = 8
62 | print(searchRange(nums, target))
63 |
64 | nums = [5, 7, 7, 8, 8, 10]
65 | target = 6
66 | print(searchRange(nums, target))
67 |
68 | nums = []
69 | target = 0
70 | print(searchRange(nums, target))
71 |
72 | nums = [5, 7, 7, 8, 8, 8, 8, 10]
73 | target = 8
74 | print(searchRange(nums, target))
75 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Four_Sum.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def fourSum(nums: List[int], target: int) -> List[List[int]]:
8 | # Resultant list
9 | quadruplets = list()
10 | # Base condition
11 | if nums is None or len(nums) < 4:
12 | return quadruplets
13 | # Sort the array
14 | nums.sort()
15 | # Length of the array
16 | n = len(nums)
17 | # Loop for each element of the array
18 | for i in range(0, n - 3):
19 | # Check for skipping duplicates
20 | if i > 0 and nums[i] == nums[i - 1]:
21 | continue
22 | # Reducing to three sum problem
23 | for j in range(i + 1, n - 2):
24 | # Check for skipping duplicates
25 | if j != i + 1 and nums[j] == nums[j - 1]:
26 | continue
27 | # Left and right pointers
28 | k = j + 1
29 | l = n - 1
30 | # Reducing to two sum problem
31 | while k < l:
32 | current_sum = nums[i] + nums[j] + nums[k] + nums[l]
33 | if current_sum < target:
34 | k += 1
35 | elif current_sum > target:
36 | l -= 1
37 | else:
38 | quadruplets.append([nums[i], nums[j], nums[k], nums[l]])
39 | k += 1
40 | l -= 1
41 | while k < l and nums[k] == nums[k - 1]:
42 | k += 1
43 | while k < l and nums[l] == nums[l + 1]:
44 | l -= 1
45 | return quadruplets
46 |
47 |
48 | if __name__ == '__main__':
49 | print(fourSum([1, 0, -1, 0, -2, 2], 0))
50 | print(fourSum([], 0))
51 | print(fourSum([1, 2, 3, 4], 10))
52 | print(fourSum([0, 0, 0, 0], 0))
53 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Generate_Parentheses.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def generate(result: List[str], s: str, _open: int, close: int, n: int):
8 | # Base condition
9 | if _open == n and close == n:
10 | result.append(s)
11 | return
12 | # If the number of _open parentheses is less than the given n
13 | if _open < n:
14 | generate(result, s + "(", _open + 1, close, n)
15 | # If we need more close parentheses to balance
16 | if close < _open:
17 | generate(result, s + ")", _open, close + 1, n)
18 |
19 |
20 | def generateParenthesis(n: int) -> List[str]:
21 | # Resultant list
22 | result = []
23 | # Recursively generate parentheses
24 | generate(result, "", 0, 0, n)
25 | return result
26 |
27 |
28 | if __name__ == '__main__':
29 | print(generateParenthesis(3))
30 | print(generateParenthesis(1))
31 | print(generateParenthesis(8))
32 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Implement_StrStr.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class ImplementStrStr:
7 | @staticmethod
8 | def strStr(haystack: str, needle: str) -> int:
9 | # Base conditions
10 | if haystack is None or needle is None:
11 | return -1
12 | # Special case
13 | if haystack == needle:
14 | return 0
15 | # Length of the needle
16 | needleLength = len(needle)
17 | # Loop through the haystack and slide the window
18 | for i in range(len(haystack) - needleLength + 1):
19 | if haystack[i:i + needleLength] == needle:
20 | return i
21 | return -1
22 |
23 |
24 | if __name__ == '__main__':
25 | im = ImplementStrStr()
26 | print(im.strStr("hello", "ll"))
27 | print(im.strStr("aaaaa", "bba"))
28 | print(im.strStr("", ""))
29 | print(im.strStr("abc", "c"))
30 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Integer_To_Roman.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def intToRoman(num: int) -> str:
7 | M = ["", "M", "MM", "MMM"]
8 | C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
9 | X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
10 | I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
11 | return M[num // 1000] + C[(num % 1000) // 100] + X[(num % 100) // 10] + I[num % 10]
12 |
13 |
14 | if __name__ == '__main__':
15 | print(intToRoman(3))
16 | print(intToRoman(4))
17 | print(intToRoman(9))
18 | print(intToRoman(58))
19 | print(intToRoman(1994))
20 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Letter_Combinations_Of_A_Phone_Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def findCombinations(combinations, digits, previous, index, lettersAndNumbersMapping):
8 | # Base condition to stop recursion
9 | if index == len(digits):
10 | combinations.append(previous)
11 | return
12 | # Get the letters corresponding to the current index of digits string
13 | letters = lettersAndNumbersMapping[int(digits[index])]
14 | # Loop through all the characters in the current combination of letters
15 | for i in range(0, len(letters)):
16 | findCombinations(combinations, digits, previous + letters[i], index + 1, lettersAndNumbersMapping)
17 |
18 |
19 | def letterCombinations(digits: str) -> List[str]:
20 | # Resultant list
21 | combinations = []
22 | # Base condition
23 | if digits is None or len(digits) == 0:
24 | return combinations
25 | # Mappings of letters and numbers
26 | lettersAndNumbersMapping = [
27 | "Anirudh",
28 | "is awesome",
29 | "abc",
30 | "def",
31 | "ghi",
32 | "jkl",
33 | "mno",
34 | "pqrs",
35 | "tuv",
36 | "wxyz"
37 | ]
38 | findCombinations(combinations, digits, "", 0, lettersAndNumbersMapping)
39 | return combinations
40 |
41 |
42 | if __name__ == '__main__':
43 | print(letterCombinations("23"))
44 | print(letterCombinations(""))
45 | print(letterCombinations("2"))
46 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Longest_Common_Prefix.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def longestCommonPrefix(strs: List[str]) -> str:
8 | # Longest common prefix string
9 | lcp = ""
10 | # Base condition
11 | if strs is None or len(strs) == 0:
12 | return lcp
13 | # Find the minimum length string from the array
14 | minimumLength = len(strs[0])
15 | for i in range(1, len(strs)):
16 | minimumLength = min(minimumLength, len(strs[i]))
17 | # Loop until the minimum length
18 | for i in range(0, minimumLength):
19 | # Get the current character from the first string
20 | current = strs[0][i]
21 | # Check if this character is found in all other strings or not
22 | for j in range(0, len(strs)):
23 | if strs[j][i] != current:
24 | return lcp
25 | lcp += current
26 | return lcp
27 |
28 |
29 | if __name__ == '__main__':
30 | print(longestCommonPrefix(["flower", "flow", "flight"]))
31 | print(longestCommonPrefix(["dog", "racecar", "car"]))
32 | print(longestCommonPrefix(["ab", "a"]))
33 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Longest_Palindromic_Substring.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def get_updated_string(s):
7 | sb = ''
8 | for i in range(0, len(s)):
9 | sb += '#' + s[i]
10 | sb += '#'
11 | return sb
12 |
13 |
14 | def longestPalindrome(s: str) -> str:
15 | # Update the string to put hash "#" at the beginning, end and in between each character
16 | updated_string = get_updated_string(s)
17 | # Length of the array that will store the window of palindromic substring
18 | length = 2 * len(s) + 1
19 | # List to store the length of each palindrome centered at each element
20 | p = [0] * length
21 | # Current center of the longest palindromic string
22 | c = 0
23 | # Right boundary of the longest palindromic string
24 | r = 0
25 | # Maximum length of the substring
26 | maxLength = 0
27 | # Position index
28 | position = -1
29 | for i in range(0, length):
30 | # Mirror of the current index
31 | mirror = 2 * c - i
32 | # Check if the mirror is outside the left boundary of current longest palindrome
33 | if i < r:
34 | p[i] = min(r - i, p[mirror])
35 | # Indices of the characters to be compared
36 | a = i + (1 + p[i])
37 | b = i - (1 + p[i])
38 | # Expand the window
39 | while a < length and b >= 0 and updated_string[a] == updated_string[b]:
40 | p[i] += 1
41 | a += 1
42 | b -= 1
43 | # If the expanded palindrome is expanding beyond the right boundary of
44 | # the current longest palindrome, then update c and r
45 | if i + p[i] > r:
46 | c = i
47 | r = i + p[i]
48 | if maxLength < p[i]:
49 | maxLength = p[i]
50 | position = i
51 | offset = p[position]
52 | result = ''
53 | for i in range(position - offset + 1, position + offset):
54 | if updated_string[i] != '#':
55 | result += updated_string[i]
56 | return result
57 |
58 |
59 | if __name__ == '__main__':
60 | print(longestPalindrome('babad'))
61 | print(longestPalindrome('cbbd'))
62 | print(longestPalindrome('a'))
63 | print(longestPalindrome('ac'))
64 | print(longestPalindrome('abb'))
65 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Longest_Substring_Without_Repeating_Characters.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def lengthOfLongestSubstring(s: str) -> int:
7 | # Base condition
8 | if s == "":
9 | return 0
10 | # Starting index of window
11 | start = 0
12 | # Ending index of window
13 | end = 0
14 | # Maximum length of substring without repeating characters
15 | maxLength = 0
16 | # Set to store unique characters
17 | unique_characters = set()
18 | # Loop for each character in the string
19 | while end < len(s):
20 | if s[end] not in unique_characters:
21 | unique_characters.add(s[end])
22 | end += 1
23 | maxLength = max(maxLength, len(unique_characters))
24 | else:
25 | unique_characters.remove(s[start])
26 | start += 1
27 | return maxLength
28 |
29 |
30 | sample_string = "abcabcbb"
31 | print(lengthOfLongestSubstring(sample_string))
32 |
33 | sample_string = "bbbbb"
34 | print(lengthOfLongestSubstring(sample_string))
35 |
36 | sample_string = "pwwkew"
37 | print(lengthOfLongestSubstring(sample_string))
38 |
39 | sample_string = ""
40 | print(lengthOfLongestSubstring(sample_string))
41 |
42 | sample_string = "aab"
43 | print(lengthOfLongestSubstring(sample_string))
44 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Longest_Valid_Parentheses.py:
--------------------------------------------------------------------------------
1 | """
2 | @author Anirudh Sharma
3 |
4 | Given a string containing just the characters '(' and ')', find the length of the
5 | longest valid (well-formed) parentheses substring.
6 |
7 | Constraints:
8 |
9 | 0 <= s.length <= 310^4
10 | s[i] is '(', or ')'.
11 | """
12 |
13 |
14 | def longestValidParentheses(s: str) -> int:
15 | # Variable to store the longest valid parentheses
16 | count = 0
17 | # Left counter will count the number of '('
18 | left = 0
19 | # Right counter will count the number of ')'
20 | right = 0
21 | # Loop through the string from left to right.
22 | # This will take care of extra right parentheses
23 | for i in range(len(s)):
24 | # Current character
25 | c = s[i]
26 | if c == '(':
27 | left += 1
28 | if c == ')':
29 | right += 1
30 | # If both left and right are equal,
31 | # it means we have a valid substring
32 | if left == right:
33 | count = max(count, left + right)
34 | # If right is greater than left,
35 | # it means we need to set both
36 | # counters to zero
37 | if right > left:
38 | left = right = 0
39 | # Reset left and right
40 | left = right = 0
41 | # Follow the same approach but now loop the string
42 | # from right to left. This will take care of extra
43 | # left parentheses
44 | for i in range(len(s) - 1, -1, -1):
45 | # Current character
46 | c = s[i]
47 | if c == '(':
48 | left += 1
49 | if c == ')':
50 | right += 1
51 | # If both left and right are equal,
52 | # it means we have a valid substring
53 | if left == right:
54 | count = max(count, left + right)
55 | # If right is greater than left,
56 | # it means we need to set both
57 | # counters to zero
58 | if left > right:
59 | left = right = 0
60 | return count
61 |
62 |
63 | if __name__ == '__main__':
64 | print(longestValidParentheses("(()"))
65 | print(longestValidParentheses(")()()"))
66 | print(longestValidParentheses(""))
67 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Merge_Two_Sorted_Lists.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class ListNode:
7 | def __init__(self, val=0, nextNode=None):
8 | self.val = val
9 | self.next = nextNode
10 |
11 |
12 | def printList(node: ListNode):
13 | while node is not None:
14 | print(str(node.val), end=" ")
15 | node = node.next
16 | print()
17 |
18 |
19 | def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
20 | # Check if either of the lists is null
21 | if l1 is None:
22 | return l2
23 | if l2 is None:
24 | return l1
25 | # Choose head which is smaller of the two lists
26 | if l1.val < l2.val:
27 | temp = head = ListNode(l1.val)
28 | l1 = l1.next
29 | else:
30 | temp = head = ListNode(l2.val)
31 | l2 = l2.next
32 | # Loop until any of the list becomes null
33 | while l1 is not None and l2 is not None:
34 | if l1.val < l2.val:
35 | temp.next = ListNode(l1.val)
36 | l1 = l1.next
37 | else:
38 | temp.next = ListNode(l2.val)
39 | l2 = l2.next
40 | temp = temp.next
41 | # Add all the nodes in l1, if remaining
42 | while l1 is not None:
43 | temp.next = ListNode(l1.val)
44 | l1 = l1.next
45 | temp = temp.next
46 | # Add all the nodes in l2, if remaining
47 | while l2 is not None:
48 | temp.next = ListNode(l2.val)
49 | l2 = l2.next
50 | temp = temp.next
51 | return head
52 |
53 |
54 | if __name__ == '__main__':
55 | head1 = ListNode(1)
56 | head1.next = ListNode(2)
57 | head1.next.next = ListNode(4)
58 | head2 = ListNode(1)
59 | head2.next = ListNode(3)
60 | head2.next.next = ListNode(4)
61 | printList(mergeTwoLists(head1, head2))
62 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Next_Permutation.py:
--------------------------------------------------------------------------------
1 | """"
2 | @author Anirudh Sharma
3 | Implement next permutation, which rearranges numbers into the lexicographically next greater
4 | permutation of numbers.
5 | If such an arrangement is not possible, it must rearrange it as the lowest possible order
6 | (i.e., sorted in ascending order).
7 | The replacement must be in place and use only constant extra memory.
8 | Constraints:
9 | 1 <= nums.length <= 100
10 | 0 <= nums[i] <= 100
11 | """
12 | from typing import List
13 |
14 |
15 | def reverse(nums, i, j):
16 | while i < j:
17 | nums[i], nums[j] = nums[j], nums[i]
18 | i += 1
19 | j -= 1
20 |
21 |
22 | def nextPermutation(nums: List[int]):
23 | # Length of the array
24 | n = len(nums)
25 | # Index of the first element that is smaller than
26 | # the element to its right.
27 | index = -1
28 | # Loop from right to left
29 | for i in range(n - 1, 0, -1):
30 | if nums[i] > nums[i - 1]:
31 | index = i - 1
32 | break
33 | # Base condition
34 | if index == -1:
35 | reverse(nums, 0, n - 1)
36 | return nums
37 | j = n - 1
38 | # Again swap from right to left to find first element
39 | # that is greater than the above find element
40 | for i in range(n - 1, index, -1):
41 | if nums[i] > nums[index]:
42 | j = i
43 | break
44 | # Swap the elements
45 | nums[index], nums[j] = nums[j], nums[index]
46 | # Reverse the elements from index + 1 to the nums.length
47 | reverse(nums, index + 1, n - 1)
48 | return nums
49 |
50 |
51 | if __name__ == "__main__":
52 | print(nextPermutation([1, 2, 3]))
53 | print(nextPermutation([3, 2, 1]))
54 | print(nextPermutation([1, 1, 5]))
55 | print(nextPermutation([1]))
56 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Palindrome_Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def isPalindrome(x: int) -> bool:
7 | # Base condition
8 | if x < 0:
9 | return False
10 | # Store the number in a variable
11 | number = x
12 | # This will store the reverse of the number
13 | reverse = 0
14 | while number:
15 | reverse = reverse * 10 + number % 10
16 | number //= 10
17 | return x == reverse
18 |
19 |
20 | if __name__ == '__main__':
21 | print(isPalindrome(121))
22 | print(isPalindrome(-121))
23 | print(isPalindrome(10))
24 | print(isPalindrome(-101))
25 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Regular_Expression_Matching.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def isMatch(s: str, p: str) -> bool:
7 | rows, columns = (len(s), len(p))
8 | # Base conditions
9 | if rows == 0 and columns == 0:
10 | return True
11 | if columns == 0:
12 | return False
13 | # DP array
14 | dp = [[False for j in range(columns + 1)] for i in range(rows + 1)]
15 | # Since empty string and empty pattern are a match
16 | dp[0][0] = True
17 | # Deals with patterns containing *
18 | for i in range(2, columns + 1):
19 | if p[i - 1] == '*':
20 | dp[0][i] = dp[0][i - 2]
21 | # For remaining characters
22 | for i in range(1, rows + 1):
23 | for j in range(1, columns + 1):
24 | if s[i - 1] == p[j - 1] or p[j - 1] == '.':
25 | dp[i][j] = dp[i - 1][j - 1]
26 | elif j > 1 and p[j - 1] == '*':
27 | dp[i][j] = dp[i][j - 2]
28 | if p[j - 2] == '.' or p[j - 2] == s[i - 1]:
29 | dp[i][j] = dp[i][j] or dp[i - 1][j]
30 | return dp[rows][columns]
31 |
32 |
33 | if __name__ == '__main__':
34 | print(isMatch("aa", "a"))
35 | print(isMatch("aa", "a*"))
36 | print(isMatch("ab", "."))
37 | print(isMatch("aab", "c*a*b"))
38 | print(isMatch("mississippi", "mis*is*p*."))
39 | print(isMatch("", ".*"))
40 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Remove_Duplicates_From_Sorted_Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | class RemoveDuplicatesFromSortedArray:
8 | def removeDuplicates(self, nums: List[int]) -> int:
9 | # Length of the update array
10 | count = 0
11 | # Loop for all the elements in the array
12 | for i in range(len(nums)):
13 | # If the current element is equal to the next element, we skip
14 | if i < len(nums) - 2 and nums[i] == nums[i + 1]:
15 | continue
16 | # We will update the array in place
17 | nums[count] = nums[i]
18 | count += 1
19 | return count
20 |
21 |
22 | if __name__ == '__main__':
23 | r = RemoveDuplicatesFromSortedArray()
24 | print(r.removeDuplicates([1, 1, 2]))
25 | print(r.removeDuplicates([0, 0, 1, 1, 1, 2, 2, 3, 3, 4]))
26 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Remove_Element.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | class RemoveElement:
8 | @staticmethod
9 | def removeElement(nums: List[int], val: int) -> int:
10 | # Counter for keeping track of elements other than val
11 | count = 0
12 | # Loop through all the elements of the array
13 | for i in range(len(nums)):
14 | if nums[i] != val:
15 | # If the element is not val
16 | nums[count] = nums[i]
17 | count += 1
18 | return count
19 |
20 |
21 | if __name__ == '__main__':
22 | r = RemoveElement()
23 | print(r.removeElement([2, 3, 3, 2], 3))
24 | print(r.removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2))
25 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Remove_Nth_Node_From_End_Of_List.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class ListNode:
7 | def __init__(self, val=0, next=None):
8 | self.val = val
9 | self.next = next
10 |
11 |
12 | def printList(node: ListNode):
13 | while node is not None:
14 | print(str(node.val), end=" ")
15 | node = node.next
16 | print()
17 |
18 |
19 | def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
20 | # Two pointers - fast and slow
21 | slow = head
22 | fast = head
23 | # Move fast pointer n steps ahead
24 | for i in range(0, n):
25 | if fast.next is None:
26 | # If n is equal to the number of nodes, delete the head node
27 | if i == n - 1:
28 | head = head.next
29 | return head
30 | fast = fast.next
31 | # Loop until fast node reaches to the end
32 | # Now we will move both slow and fast pointers
33 | while fast.next is not None:
34 | slow = slow.next
35 | fast = fast.next
36 | # Delink the nth node from last
37 | if slow.next is not None:
38 | slow.next = slow.next.next
39 | return head
40 |
41 |
42 | if __name__ == '__main__':
43 | head = ListNode(1)
44 | head.next = ListNode(2)
45 | head.next.next = ListNode(3)
46 | head.next.next.next = ListNode(4)
47 | head.next.next.next.next = ListNode(5)
48 | printList(removeNthFromEnd(head, 2))
49 |
50 | head = ListNode(1)
51 | printList(removeNthFromEnd(head, 1))
52 |
53 | head = ListNode(1)
54 | head.next = ListNode(2)
55 | printList(removeNthFromEnd(head, 1))
56 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Reverse_Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | import sys
5 |
6 |
7 | def reverse(x: int) -> int:
8 | isNegative = False
9 | if x < 0:
10 | isNegative = True
11 | x = -x
12 | reversedNumber = 0
13 | while x:
14 | reversedNumber = reversedNumber * 10 + x % 10
15 | x //= 10
16 | if reversedNumber >= 2 ** 31 - 1 or reversedNumber <= -2 ** 31:
17 | return 0
18 | return -reversedNumber if isNegative else reversedNumber
19 |
20 |
21 | if __name__ == '__main__':
22 | print(reverse(2342))
23 | print(reverse(-4345))
24 | print(reverse(340))
25 | print(sys.maxsize)
26 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Roman_To_Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def romanToInt(s: str) -> int:
7 | # Dictionary of roman numerals
8 | roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
9 | # Length of the given string
10 | n = len(s)
11 | # This variable will store result
12 | num = roman_map[s[n - 1]]
13 | # Loop for each character from right to left
14 | for i in range(n - 2, -1, -1):
15 | # Check if the character at right of current character is bigger or smaller
16 | if roman_map[s[i]] >= roman_map[s[i + 1]]:
17 | num += roman_map[s[i]]
18 | else:
19 | num -= roman_map[s[i]]
20 | return num
21 |
22 |
23 | if __name__ == '__main__':
24 | print(romanToInt('III'))
25 | print(romanToInt('IV'))
26 | print(romanToInt('IX'))
27 | print(romanToInt('LVIII'))
28 | print(romanToInt('MCMXCIV'))
29 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Search_In_Rotated_Sorted_Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @author Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def search(nums: List[int], target: int) -> int:
8 | # Special case
9 | if nums is None or len(nums) == 0:
10 | return -1
11 | # Left and right pointers for the array
12 | left, right = 0, len(nums) - 1
13 | # First step is to find the pivot where the array
14 | # is rotated
15 | while left < right:
16 | # Middle index
17 | middle = left + (right - left) // 2
18 | # If the element at the mid is greater than
19 | # the element at the right then we can say that
20 | # the array is rotated after middle index
21 | if nums[middle] > nums[right]:
22 | left = middle + 1
23 | # Else, the pivot is in the left part
24 | else:
25 | right = middle
26 | # After the above loop is completed, then the
27 | # left index will point to the pivot
28 | pivot = left
29 | left, right = 0, len(nums) - 1
30 | # Now we will find in which half of the array,
31 | # our targetValue is present
32 | if nums[pivot] <= target <= nums[right]:
33 | left = pivot
34 | else:
35 | right = pivot
36 | # Now perform normal binary search
37 | while left <= right:
38 | middle = left + (right - left) // 2
39 | if nums[middle] == target:
40 | return middle
41 | elif nums[middle] < target:
42 | left = middle + 1
43 | else:
44 | right = middle - 1
45 | return -1
46 |
47 |
48 | if __name__ == '__main__':
49 | numbers = [4, 5, 6, 7, 0, 1, 2]
50 | targetValue = 0
51 | print(search(numbers, targetValue))
52 |
53 | numbers = [4, 5, 6, 7, 0, 1, 2]
54 | targetValue = 3
55 | print(search(numbers, targetValue))
56 |
57 | numbers = [1]
58 | targetValue = 0
59 | print(search(numbers, targetValue))
60 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/String_To_Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def myAtoi(s: str) -> int:
7 | # Base condition
8 | if s is None or len(s) < 1:
9 | return 0
10 | # Max and Min values for the integers
11 | INT_MAX = 2147483647
12 | INT_MIN = -2147483648
13 | # Trimmed string
14 | s = s.lstrip()
15 | # Counter
16 | i = 0
17 | # Flag to indicate if the number is negative
18 | isNegative = len(s) > 1 and s[0] == '-'
19 | # Flag to indicate if the number is positive
20 | isPositive = len(s) > 1 and s[0] == '+'
21 | if isNegative:
22 | i += 1
23 | elif isPositive:
24 | i += 1
25 | # This will store the converted number
26 | number = 0
27 | # Loop for each numeric character in the string iff numeric characters are leading
28 | # characters in the string
29 | while i < len(s) and '0' <= s[i] <= '9':
30 | number = number * 10 + (ord(s[i]) - ord('0'))
31 | i += 1
32 | # Give back the sign to the number
33 | if isNegative:
34 | number = -number
35 | # Edge cases - integer overflow and underflow
36 | if number < INT_MIN:
37 | return INT_MIN
38 | if number > INT_MAX:
39 | return INT_MAX
40 | return number
41 |
42 |
43 | if __name__ == '__main__':
44 | print(myAtoi("42"))
45 | print(myAtoi(" -42"))
46 | print(myAtoi("4193 with words"))
47 | print(myAtoi("words and 987"))
48 | print(myAtoi("-91283472332"))
49 | print(myAtoi("91283472332"))
50 | print(myAtoi("9223372036854775808"))
51 | print(myAtoi(" "))
52 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Swap_Nodes_In_Pairs.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | class ListNode:
7 | def __init__(self, val=0, nextNode=None):
8 | self.val = val
9 | self.next = nextNode
10 |
11 |
12 | class SwapNodesInPairs:
13 | def swapPairs(self, head: ListNode) -> ListNode:
14 | # Dummy node
15 | dummy = ListNode(0)
16 | # Point the next of dummy node to the head
17 | dummy.next = head
18 | # This node will be used to traverse the list
19 | current = dummy
20 | # Loop until we reach to the second last node
21 | while current.next is not None and current.next.next is not None:
22 | # First node of the pair
23 | first = current.next
24 | # Second node of the pair
25 | second = current.next.next
26 | # Point the next of first node to the node after second node
27 | first.next = second.next
28 | # Now the current node's next should be the second node
29 | current.next = second
30 | # Linking the original second node to the first node
31 | current.next.next = first
32 | # Move the pointer two nodes ahead
33 | current = current.next.next
34 | return dummy.next
35 |
36 | def printList(self, head):
37 | temp = head
38 | while temp is not None:
39 | print(temp.val, end=" ")
40 | temp = temp.next
41 | print()
42 |
43 |
44 | if __name__ == '__main__':
45 | s = SwapNodesInPairs()
46 | head = ListNode(1)
47 | head.next = ListNode(2)
48 | head.next.next = ListNode(3)
49 | head.next.next.next = ListNode(4)
50 | s.printList(s.swapPairs(head))
51 |
52 | head = ListNode(1)
53 | s.printList(s.swapPairs(head))
54 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Three_Sum.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def threeSum(nums: List[int]) -> List[List[int]]:
8 | # Sort the given array
9 | nums.sort()
10 | # Length of the array
11 | n = len(nums)
12 | # Resultant list
13 | triplets = list()
14 | # Loop for each character in the array
15 | for i in range(0, n):
16 | # Avoid duplicates due to i
17 | if i > 0 and nums[i] == nums[i - 1]:
18 | continue
19 | # Left and right pointers
20 | j = i + 1
21 | k = n - 1
22 | # Loop for remaining pairs
23 | while j < k:
24 | if nums[i] + nums[j] + nums[k] == 0:
25 | triplets.append([nums[i], nums[j], nums[k]])
26 | j += 1
27 | # Avoid duplicates for j
28 | while j < k and nums[j] == nums[j - 1]:
29 | j += 1
30 | elif nums[i] + nums[j] + nums[k] < 0:
31 | j += 1
32 | else:
33 | k -= 1
34 | return triplets
35 |
36 |
37 | if __name__ == '__main__':
38 | print(threeSum([-1, 0, 1, 2, -1, -4]))
39 | print(threeSum([]))
40 | print(threeSum([-1, -2, 3, -4, -5, 9, -10, -11, 21, -22, -23, 45, -46, -47, 93, -94, -95, 189]))
41 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Three_Sum_Closest.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def threeSumClosest(nums: List[int], target: int) -> int:
8 | # Sort the given array
9 | nums.sort()
10 | # Length of the array
11 | n = len(nums)
12 | # Closest value
13 | closest = nums[0] + nums[1] + nums[n - 1]
14 | # Loop for each element of the array
15 | for i in range(0, n - 2):
16 | # Left and right pointers
17 | j = i + 1
18 | k = n - 1
19 | # Loop for all other pairs
20 | while j < k:
21 | current_sum = nums[i] + nums[j] + nums[k]
22 | if current_sum <= target:
23 | j += 1
24 | else:
25 | k -= 1
26 | if abs(closest - target) > abs(current_sum - target):
27 | closest = current_sum
28 | return closest
29 |
30 |
31 | if __name__ == '__main__':
32 | print(threeSumClosest([2, 3, 7, 1, 5, 7, 1, 8, -1, -4, -4, 3], 12))
33 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Two_Sum.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 | from typing import List
5 |
6 |
7 | def twoSum(nums: List[int], target: int) -> List[int]:
8 | # List to store results
9 | result = []
10 | # Dictionary to store the difference and its index
11 | index_map = {}
12 | # Loop for each element
13 | for i, n in enumerate(nums):
14 | # Difference which needs to be checked
15 | difference = target - n
16 | if difference in index_map:
17 | result.append(i)
18 | result.append(index_map[difference])
19 | break
20 | else:
21 | index_map[n] = i
22 | return result
23 |
24 |
25 | numbers = [2, 7, 11, 15]
26 | target_value = 9
27 | print(str(twoSum(numbers, target_value)))
28 |
29 | numbers = [3, 2, 4]
30 | target_value = 6
31 | print(str(twoSum(numbers, target_value)))
32 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/Valid_Parentheses.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def isValid(s: str) -> bool:
7 | # Stack for left symbols
8 | leftSymbols = []
9 | # Loop for each character of the string
10 | for c in s:
11 | # If left symbol is encountered
12 | if c in ['(', '{', '[']:
13 | leftSymbols.append(c)
14 | # If right symbol is encountered
15 | elif c == ')' and len(leftSymbols) != 0 and leftSymbols[-1] == '(':
16 | leftSymbols.pop()
17 | elif c == '}' and len(leftSymbols) != 0 and leftSymbols[-1] == '{':
18 | leftSymbols.pop()
19 | elif c == ']' and len(leftSymbols) != 0 and leftSymbols[-1] == '[':
20 | leftSymbols.pop()
21 | # If none of the valid symbols is encountered
22 | else:
23 | return False
24 | return leftSymbols == []
25 |
26 |
27 | if __name__ == '__main__':
28 | print(isValid("()"))
29 | print(isValid("()[]{}"))
30 | print(isValid("(]"))
31 | print(isValid("([)]"))
32 | print(isValid("{[]}"))
33 |
--------------------------------------------------------------------------------
/LeetCode/Python/src/ZigZag_Conversion.py:
--------------------------------------------------------------------------------
1 | """
2 | @author - Anirudh Sharma
3 | """
4 |
5 |
6 | def convert(s: str, numRows: int) -> str:
7 | # Base condition
8 | if s is None and numRows <= 0:
9 | return ""
10 | if numRows == 1:
11 | return s
12 | # Resultant string
13 | result = ""
14 | # Step size
15 | step = 2 * numRows - 2
16 | # Loop for each row
17 | for i in range(0, numRows):
18 | # Loop for each character in the row
19 | for j in range(i, len(s), step):
20 | result += s[j]
21 | if i != 0 and i != numRows - 1 and (j + step - 2 * i) < len(s):
22 | result += s[j + step - 2 * i]
23 | return result
24 |
25 |
26 | if __name__ == '__main__':
27 | s = "PAYPALISHIRING"
28 | numRows = 3
29 | print(convert(s, numRows))
30 |
31 | numRows = 4
32 | print(convert(s, numRows))
33 |
34 | s = "ANIRUDHSHARMAISGREAT"
35 | numRows = 5
36 | print(convert(s, numRows))
37 |
--------------------------------------------------------------------------------
/ProblemSolving/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java'
3 | }
4 |
5 | group 'org.redquark.tutorials.problemsolving'
6 | version '1.0-SNAPSHOT'
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.0'
14 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0'
15 | }
16 |
17 | test {
18 | useJUnitPlatform()
19 | }
--------------------------------------------------------------------------------
/ProblemSolving/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'ProblemSolving'
2 |
3 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/BitDifference.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * You are given two numbers A and B, count the number of bits needed to be flipped to convert A to B.
5 | */
6 | public class BitDifference {
7 |
8 | private static int countBitsFlip(int a, int b) {
9 | // Find XOR of two numbers to find out different bits
10 | int xor = a ^ b;
11 | // Count of 1s in the XOR output
12 | int count = 0;
13 | // Loop until xor becomes 0
14 | while (xor != 0) {
15 | xor &= (xor - 1);
16 | count++;
17 | }
18 | return count;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(countBitsFlip(10, 20));
23 | System.out.println(countBitsFlip(20, 25));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/CheckEvenOrOdd.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Check if a given integer n is even or odd.
5 | */
6 | public class CheckEvenOrOdd {
7 |
8 | private static String check(int n) {
9 | return (n & 1) == 0 ? "Even" : "Odd";
10 | }
11 |
12 | public static void main(String[] args) {
13 | System.out.println(check(4));
14 | System.out.println(check(863));
15 | System.out.println(check(-124));
16 | System.out.println(check(-3));
17 | System.out.println(check(0));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/CheckKthBit.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given a number n and a bit number k, check if kth bit of n is set or not. A bit is called set if it is 1.
5 | * Position of set bit '1' should be indexed starting with 0 from LSB side in binary representation of the number.
6 | */
7 | public class CheckKthBit {
8 |
9 | private static boolean checkKthBit(int n, int k) {
10 | // Variable for shifting
11 | int mask = 1;
12 | // Shift k positions
13 | for (int i = 0; i < k; i++) {
14 | mask <<= 1;
15 | }
16 | // Negate the shift
17 | mask = ~mask;
18 | // OR the shift with n
19 | return (mask | n) == ~0;
20 | }
21 |
22 | public static void main(String[] args) {
23 | System.out.println(checkKthBit(4, 0));
24 | System.out.println(checkKthBit(4, 2));
25 | System.out.println(checkKthBit(500, 3));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/CheckOppositeSign.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given two integers a and b, check if they have opposite signs
5 | */
6 | public class CheckOppositeSign {
7 |
8 | private static boolean check(int a, int b) {
9 | return (a ^ b) < 0;
10 | }
11 |
12 | public static void main(String[] args) {
13 | System.out.println(check(4, 6));
14 | System.out.println(check(7, -9));
15 | System.out.println(check(-2, -3));
16 | System.out.println(check(-1, 8));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/CountSetBitsInANumber.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | public class CountSetBitsInANumber {
4 |
5 | private static int count(int n) {
6 | // Special case
7 | if (n == 0) {
8 | return 0;
9 | }
10 | // Count of set bits
11 | int setBits = 0;
12 | // Loop until n is greater than 0
13 | while (n > 0) {
14 | n &= (n - 1);
15 | setBits++;
16 | }
17 | return setBits;
18 | }
19 |
20 | public static void main(String[] args) {
21 | System.out.println(count(4));
22 | System.out.println(count(9));
23 | System.out.println(count(63));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/CountTotalSetBits.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given a number n, find the total count of set bits for all numbers from 1 to N(both inclusive).
5 | */
6 | public class CountTotalSetBits {
7 |
8 | private static int count(int n) {
9 | // Special case
10 | if (n <= 0) {
11 | return 0;
12 | }
13 | // Get maximum power of two less than n
14 | int maxPower = getMaximumPowerOfTwo(n);
15 | // Now calculate the total number of set bits
16 | return maxPower * (1 << (maxPower - 1))
17 | + (n - (1 << maxPower) + 1)
18 | + count(n - (1 << maxPower));
19 | }
20 |
21 | private static int getMaximumPowerOfTwo(int n) {
22 | int power = 0;
23 | while ((1 << power) <= n) {
24 | power++;
25 | }
26 | return power - 1;
27 | }
28 |
29 | public static void main(String[] args) {
30 | System.out.println(count(4));
31 | System.out.println(count(17));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/FindFirstSetBit.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given an integer an N. The task is to return the position of first set bit found from the right side in the
5 | * binary representation of the number.
6 | *
7 | * Note: If there is no set bit in the integer N, then return 0 from the function.
8 | */
9 | public class FindFirstSetBit {
10 |
11 | private static int getFirstSetBit(int n) {
12 | // Special case
13 | if (n == 0) {
14 | return 0;
15 | }
16 | // Position of the first set bit from the right
17 | int position = 1;
18 | // Variable for shifting
19 | int mask = 1;
20 | // Counting the position of first set bit
21 | while ((n & mask) == 0) {
22 | position++;
23 | mask <<= 1;
24 | }
25 | return position;
26 | }
27 |
28 | public static void main(String[] args) {
29 | System.out.println(getFirstSetBit(18));
30 | System.out.println(getFirstSetBit(12));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/GeneratePowerSet.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class GeneratePowerSet {
7 |
8 | private static List> generate(int[] S) {
9 | // List to store the output
10 | List> powerSet = new ArrayList<>();
11 | // Special case
12 | if (S == null || S.length == 0) {
13 | return powerSet;
14 | }
15 | // Length of the array
16 | int n = S.length;
17 | // Total number of sets
18 | int count = 1 << n;
19 | // Generate each subset one by one
20 | for (int i = 0; i < count; i++) {
21 | // List to store current subset
22 | List currentSubset = new ArrayList<>();
23 | // Check every bit of i
24 | for (int j = 0; j < n; j++) {
25 | // If j-th bit of i is set, add it to the list
26 | if ((i & (1 << j)) != 0) {
27 | currentSubset.add(S[j]);
28 | }
29 | }
30 | powerSet.add(currentSubset);
31 | }
32 | return powerSet;
33 | }
34 |
35 | public static void main(String[] args) {
36 | int[] S = new int[]{1, 2, 3};
37 | System.out.println(generate(S));
38 |
39 | S = new int[]{11, 12, 13, 14};
40 | System.out.println(generate(S));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/LongestConsecutive1s.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given a number n, ind the length of the longest consecutive 1s in its binary representation.
5 | */
6 | public class LongestConsecutive1s {
7 |
8 | private static int maxConsecutiveOnes(int N) {
9 | int maxConsecutiveOnesCount = 0;
10 | while (N != 0) {
11 | N &= (N << 1);
12 | maxConsecutiveOnesCount++;
13 | }
14 | return maxConsecutiveOnesCount;
15 | }
16 |
17 | public static void main(String[] args) {
18 | System.out.println(maxConsecutiveOnes(14));
19 | System.out.println(maxConsecutiveOnes(222));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/PowerOf4And8.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given an integer, check if it is a power of 4 and 8 or not
5 | */
6 | public class PowerOf4And8 {
7 |
8 | private static boolean isPowerOf4(int n) {
9 | return n != 0 && (n & (n - 1)) == 0 && (n & 0xAAAAAAAA) == 0;
10 | }
11 |
12 | private static boolean isPowerOf8(int n) {
13 | return n != 0 && (n & (n - 1)) == 0 && (n & 0xB6DB6DB6) == 0;
14 | }
15 |
16 | public static void main(String[] args) {
17 | int n = 16;
18 | if (isPowerOf4(n)) {
19 | System.out.println(n + " is a power of 4");
20 | } else {
21 | System.out.println(n + " is not a power of 4");
22 | }
23 | if (isPowerOf8(n)) {
24 | System.out.println(n + " is a power of 8");
25 | } else {
26 | System.out.println(n + " is not a power of 8");
27 | }
28 | n = 64;
29 | if (isPowerOf4(n)) {
30 | System.out.println(n + " is a power of 4");
31 | } else {
32 | System.out.println(n + " is not a power of 4");
33 | }
34 | if (isPowerOf8(n)) {
35 | System.out.println(n + " is a power of 8");
36 | } else {
37 | System.out.println(n + " is not a power of 8");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/PowerOfTwo.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given a non-negative integer N. The task is to check if N is a power of 2.
5 | * More formally, check if N can be expressed as 2x for some x.
6 | */
7 | public class PowerOfTwo {
8 |
9 | private static boolean isPowerOfTwo(long n) {
10 | if (n <= 0) {
11 | return false;
12 | }
13 | return (n & (n - 1)) == 0;
14 | }
15 |
16 | public static void main(String[] args) {
17 | System.out.println(isPowerOfTwo(4));
18 | System.out.println(isPowerOfTwo(65536));
19 | System.out.println(isPowerOfTwo(32350));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/ReverseBits.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Give an integer, reverse its bits. For e.g., if the input is 10011, then the output should be 11001.
5 | */
6 | public class ReverseBits {
7 |
8 | private static int reverse(int n) {
9 | // Special case
10 | if (n == 0) {
11 | return 0;
12 | }
13 | // Sequence of 0s
14 | int m = 0;
15 | // Loop from LSB to MSB
16 | for (int i = 31; i >= 0 & n != 0; i--) {
17 | // If the current bit in n is 1, set the corresponding bit in m
18 | if ((n & 1) != 0) {
19 | m |= (1 << i);
20 | }
21 | n >>= 1;
22 | }
23 | return m;
24 | }
25 |
26 | public static void main(String[] args) {
27 | System.out.println(reverse(4));
28 | System.out.println(reverse(6));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/RightMostDifferentBit.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given two numbers M and N, find the position of the rightmost different bit in the binary representation of numbers.
5 | */
6 | public class RightMostDifferentBit {
7 |
8 | private static int posOfRightMostDiffBit(int m, int n) {
9 | // Find the XOR of both numbers to get 1 at the position
10 | // of difference in bits
11 | int xor = m ^ n;
12 | // Special case
13 | if (xor == 0) {
14 | return 0;
15 | }
16 | // Now find the position of the rightmost set bit
17 | // Position of the first set bit from the right
18 | int position = 1;
19 | // Variable for shifting
20 | int mask = 1;
21 | // Counting the position of first set bit
22 | while ((xor & mask) == 0) {
23 | position++;
24 | mask <<= 1;
25 | }
26 | return position;
27 | }
28 |
29 | public static void main(String[] args) {
30 | System.out.println(posOfRightMostDiffBit(11, 9));
31 | System.out.println(posOfRightMostDiffBit(52, 4));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/RotateBits.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Anirudh Sharma
8 | *
9 | * Given an integer N and an integer D, rotate the binary representation of the integer N by D digits to the
10 | * left as well as right and print the results in decimal values after each of the rotation.
11 | */
12 | public class RotateBits {
13 |
14 | private static List rotate(int N, int D) {
15 | // Reduce D to its effective value for a 16 bit number
16 | D %= 16;
17 | // This list will store the left and right rotations of N by D
18 | List output = new ArrayList<>();
19 | // Left rotation
20 | int left = (N << D | N >> (16 - D)) & 0xFFFF;
21 | // Right rotation
22 | int right = ((N >> D | N << (16 - D))) & 0xFFFF;
23 | output.add(left);
24 | output.add(right);
25 | return output;
26 | }
27 |
28 | public static void main(String[] args) {
29 | System.out.println(rotate(28, 2));
30 | System.out.println(rotate(29, 2));
31 | System.out.println(rotate(54, 6));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/SetKthBit.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | *
6 | * Given a number N and a value K. From the right, set the Kth bit in the binary representation of N.
7 | * The position of Least Significant Bit(or last bit) is 0, the second last bit is 1 and so on.
8 | */
9 | public class SetKthBit {
10 |
11 | private static int setKthBit(int N, int K) {
12 | return N | (1 << (K));
13 | }
14 |
15 | public static void main(String[] args) {
16 | System.out.println(setKthBit(10, 2));
17 | System.out.println(setKthBit(524288, 5));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/SingleNumber.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * At a party of N people, each person is denoted by an integer.
5 | * Couples are represented by the same number. Find out the only singe person in the party of couples.
6 | */
7 | public class SingleNumber {
8 |
9 | private static int findSingle(int[] nums) {
10 | int xor = nums[0];
11 | for (int i = 1; i < nums.length; i++) {
12 | xor ^= nums[i];
13 | }
14 | return xor;
15 | }
16 |
17 | public static void main(String[] args) {
18 | int[] nums = new int[]{1, 2, 3, 2, 1};
19 | System.out.println(findSingle(nums));
20 |
21 | nums = new int[]{1, 2, 3, 5, 3, 2, 1, 4, 5, 6, 6};
22 | System.out.println(findSingle(nums));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/SparseNumber.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given a number N, check whether it is sparse or not. A number is said to be a sparse number if no two or
5 | * more consecutive bits are set in the binary representation.
6 | */
7 | public class SparseNumber {
8 |
9 | private static boolean isSparse(int n) {
10 | return (n & (n << 1)) == 0;
11 | }
12 |
13 | public static void main(String[] args) {
14 | System.out.println(isSparse(2));
15 | System.out.println(isSparse(3));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/SwapEvenOddBits.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * Given an unsigned integer n, swap all odd bits with even bits.
5 | */
6 | public class SwapEvenOddBits {
7 |
8 | private static int swap(int n) {
9 | // Masks for even and odd bits
10 | int evenMask = 0xAAAAAAAA;
11 | int oddMask = 0x55555555;
12 | // Perform AND operation between even and odd masks
13 | int evenBits = n & evenMask;
14 | int oddBits = n & oddMask;
15 | // Shift even bits to right and odd bits to left to make
16 | // even bits odd and odd bit even
17 | evenBits >>= 1;
18 | oddBits <<= 1;
19 | return evenBits | oddBits;
20 | }
21 |
22 | public static void main(String[] args) {
23 | System.out.println(swap(23));
24 | System.out.println(swap(2));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/ProblemSolving/src/main/java/org/redquark/tutorials/problemsolving/bitmagic/ToggleBitsInRange.java:
--------------------------------------------------------------------------------
1 | package org.redquark.tutorials.problemsolving.bitmagic;
2 |
3 | /**
4 | * @author Anirudh Sharma
5 | *
6 | * Given a non-negative number N and two values L and R, toggle the bits in the range L to R in the binary
7 | * representation of N, i.e, to toggle bits from the rightmost Lth bit to the rightmost Rth bit.
8 | *
9 | * A toggle operation flips a bit 0 to 1 and a bit 1 to 0. Print N after the bits are toggled.
10 | */
11 | public class ToggleBitsInRange {
12 |
13 | private static int toggleBits(int N, int L, int R) {
14 | int mask = ((1 << R) - 1) ^ ((1 << (L - 1)) - 1);
15 | return N ^ mask;
16 | }
17 |
18 | public static void main(String[] args) {
19 | System.out.println(toggleBits(17, 2, 3));
20 | System.out.println(toggleBits(50, 2, 5));
21 | System.out.println(toggleBits(10812, 7, 7));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Snippets/JavaScript/emails/index.js:
--------------------------------------------------------------------------------
1 | const sendEmail = require('./sendEmail');
2 |
3 | module.exports = {
4 | sendEmail
5 | }
--------------------------------------------------------------------------------
/Snippets/JavaScript/emails/sendEmail.js:
--------------------------------------------------------------------------------
1 | const nodemailer = require('nodemailer');
2 |
3 | const toEmail = '';
4 | const fromEmail = '';
5 | const subject = '';
6 | const message = '';
7 |
8 | const transporter = nodemailer.createTransport({
9 | service: 'gmail',
10 | auth: {
11 | user: '',
12 | pass: ''
13 | }
14 | });
15 |
16 | const sendEmail = () => {
17 | const details = {
18 | from: fromEmail,
19 | to: toEmail,
20 | subject: subject,
21 | html: message
22 | };
23 |
24 | transporter.sendMail(details, (error, data) => {
25 | if (error) {
26 | console.log(error);
27 | } else {
28 | console.log(data);
29 | }
30 | });
31 | };
32 |
33 | module.exports = {
34 | sendEmail
35 | };
--------------------------------------------------------------------------------
/Snippets/JavaScript/files/deleteFile.js:
--------------------------------------------------------------------------------
1 | // Import the core node js fs module
2 | const fs = require('fs');
3 | // Relative path of the file to be deleted
4 | const fileName = 'files/sample-file-to-write.txt';
5 |
6 | // This function deletes the file
7 | const deleteFile = () => {
8 | fs.unlink(fileName, (err) => {
9 | if (err) {
10 | throw err;
11 | }
12 | console.log("File deleted successfully");
13 | });
14 | }
15 |
16 | module.exports = { deleteFile };
--------------------------------------------------------------------------------
/Snippets/JavaScript/files/index.js:
--------------------------------------------------------------------------------
1 | const readFile = require('./readFile');
2 | const writeFile = require('./writeFile');
3 | const deleteFile = require('./deleteFile');
4 |
5 | module.exports = {
6 | readFile,
7 | writeFile,
8 | deleteFile
9 | };
--------------------------------------------------------------------------------
/Snippets/JavaScript/files/readFile.js:
--------------------------------------------------------------------------------
1 | // Import the module
2 | const fs = require('fs');
3 |
4 | // This function reads the file and prints the data on the console using the callback function
5 | const readFile = () => {
6 | fs.readFile('files/sample-text-file.txt', 'utf8', (err, data) => {
7 | if (err) {
8 | return console.log(err);
9 | }
10 | console.log(data);
11 | });
12 | }
13 |
14 | module.exports = { readFile };
--------------------------------------------------------------------------------
/Snippets/JavaScript/files/sample-text-file.txt:
--------------------------------------------------------------------------------
1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
2 | quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
3 | Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
4 | Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
--------------------------------------------------------------------------------
/Snippets/JavaScript/files/writeFile.js:
--------------------------------------------------------------------------------
1 | // Import the core node js fs module
2 | const fs = require('fs');
3 |
4 | const contentToWrite = 'This content will be written into the file';
5 |
6 | const writeFile = () => {
7 | fs.writeFile('files/sample-file-to-write.txt', contentToWrite, (err) => {
8 | if (err) {
9 | throw err;
10 | }
11 | console.log('File is saved!');
12 | });
13 | }
14 |
15 | module.exports = { writeFile };
16 |
--------------------------------------------------------------------------------
/Snippets/JavaScript/index.js:
--------------------------------------------------------------------------------
1 | const cronJob = require('./jobs');
2 | const {
3 | readFile,
4 | writeFile,
5 | deleteFile
6 | } = require('./files');
7 | const {
8 | sendEmail
9 | } = require('./emails');
10 |
11 | readFile.readFile();
12 | writeFile.writeFile();
13 | deleteFile.deleteFile();
14 | sendEmail.sendEmail();
15 | cronJob.run();
--------------------------------------------------------------------------------
/Snippets/JavaScript/jobs/cronJob..js:
--------------------------------------------------------------------------------
1 | // Import module
2 | const cron = require('node-cron');
3 |
4 | // This expression defines the cron
5 | const CRON_EXPRESSION = "*/10 * * * * *";
6 |
7 | // Actual task to execute i.e., your business logic
8 | const jobToExecute = () => {
9 | console.log('Running a task every ten seconds');
10 | }
11 |
12 | // This function runs the job based on the CRON_EXPRESSION
13 | const run = () => {
14 | cron.schedule(CRON_EXPRESSION, () => {
15 | jobToExecute();
16 | });
17 | }
18 |
19 | module.exports = { run };
--------------------------------------------------------------------------------
/Snippets/JavaScript/jobs/index.js:
--------------------------------------------------------------------------------
1 | const cronJob = require("./cronJob.");
2 |
3 | module.exports = cronJob;
--------------------------------------------------------------------------------
/Snippets/JavaScript/package-lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "javascript-snippets",
3 | "version": "1.0.0",
4 | "lockfileVersion": 1,
5 | "requires": true,
6 | "dependencies": {
7 | "node-cron": {
8 | "version": "2.0.3",
9 | "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-2.0.3.tgz",
10 | "integrity": "sha512-eJI+QitXlwcgiZwNNSRbqsjeZMp5shyajMR81RZCqeW0ZDEj4zU9tpd4nTh/1JsBiKbF8d08FCewiipDmVIYjg==",
11 | "requires": {
12 | "opencollective-postinstall": "^2.0.0",
13 | "tz-offset": "0.0.1"
14 | }
15 | },
16 | "nodemailer": {
17 | "version": "6.4.16",
18 | "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.4.16.tgz",
19 | "integrity": "sha512-68K0LgZ6hmZ7PVmwL78gzNdjpj5viqBdFqKrTtr9bZbJYj6BRj5W6WGkxXrEnUl3Co3CBXi3CZBUlpV/foGnOQ=="
20 | },
21 | "opencollective-postinstall": {
22 | "version": "2.0.3",
23 | "resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.3.tgz",
24 | "integrity": "sha512-8AV/sCtuzUeTo8gQK5qDZzARrulB3egtLzFgteqB2tcT4Mw7B8Kt7JcDHmltjz6FOAHsvTevk70gZEbhM4ZS9Q=="
25 | },
26 | "tz-offset": {
27 | "version": "0.0.1",
28 | "resolved": "https://registry.npmjs.org/tz-offset/-/tz-offset-0.0.1.tgz",
29 | "integrity": "sha512-kMBmblijHJXyOpKzgDhKx9INYU4u4E1RPMB0HqmKSgWG8vEcf3exEfLh4FFfzd3xdQOw9EuIy/cP0akY6rHopQ=="
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/Snippets/JavaScript/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "javascript-snippets",
3 | "version": "1.0.0",
4 | "description": "This Node JS project houses small useful code snippets",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node index.js"
8 | },
9 | "author": "Anirudh Sharma ",
10 | "license": "MIT",
11 | "dependencies": {
12 | "node-cron": "^2.0.3",
13 | "nodemailer": "^6.4.16"
14 | }
15 | }
16 |
--------------------------------------------------------------------------------