From bffe07e6e94a9da2bc1bdd3dff8e7306417e21f1 Mon Sep 17 00:00:00 2001 From: uday510 Date: Sun, 29 Jan 2023 13:13:08 +0530 Subject: [PATCH 0001/1894] Added SubArrayWithLeastAverage using constant space Solution. --- Arrays/subarray_with_least_avg.java | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Arrays/subarray_with_least_avg.java b/Arrays/subarray_with_least_avg.java index 8f3ef866..48ae6199 100644 --- a/Arrays/subarray_with_least_avg.java +++ b/Arrays/subarray_with_least_avg.java @@ -50,35 +50,40 @@ public class SubArrayWithLeastAverage { public static void main(String[] args) { -// int[] arr = {3, 7, 90, 20, 10, 50, 40}; - int[] arr = {3, 7, 5, 20, -10, 0, 12}; - int size = 2; +// int[] arr = {3, 7, 90, 20, -10, 0, 12}; + int[] arr = {431, 313, 53, 251, 105, 423, 326, 297, + 218, 89, 394, 365, 348, 474, 157, 262, 33, 187, + 67, 79, 495, 199, 175, 228, 27, 305, 496, 331, + 40, 98, 405, 221, 327, 488, 252, 73, 218, 152, + 313, 274, 195, 353, 225, 292, 426, 257, 418, + 364, 344, 349, 181}; + int size = 12; int ans = solve(arr, size); System.out.println(ans); } public static int solve(int[] arr, int size) { // O(N) time | O(1) space - int sum = 0; - int ans = 0; + int currentSum = 0; + int idx = 0; int len = arr.length; // sliding window for (int i = 0; i < size; i++) - sum += arr[i]; + currentSum += arr[i]; int startIdx = 1; int endIdx = size; - + int minSum = currentSum; // slide remaining windows while (endIdx < len) { - int currentSum = sum + arr[endIdx] - arr[startIdx - 1]; - if ((currentSum / 3 ) < (sum / 3)) { - ans = startIdx; + currentSum = currentSum + arr[endIdx] - arr[startIdx - 1]; + if (currentSum < minSum) { + minSum = currentSum; + idx = startIdx; } startIdx++; endIdx++; - sum = currentSum; } - return ans; + return idx; } } From 275224e16f11ec945cd5113d3d489f3323de5cdd Mon Sep 17 00:00:00 2001 From: uday510 Date: Sun, 29 Jan 2023 14:51:16 +0530 Subject: [PATCH 0002/1894] create minimum_size_subarray_sum.java space Solution. --- Arrays/minimum_size_subarray_sum.java | 82 +++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Arrays/minimum_size_subarray_sum.java diff --git a/Arrays/minimum_size_subarray_sum.java b/Arrays/minimum_size_subarray_sum.java new file mode 100644 index 00000000..e685bd1f --- /dev/null +++ b/Arrays/minimum_size_subarray_sum.java @@ -0,0 +1,82 @@ +/** + * Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. + * + * + * + * Example 1: + * + * Input: target = 7, nums = [2,3,1,2,4,3] + * Output: 2 + * Explanation: The subarray [4,3] has the minimal length under the problem constraint. + * Example 2: + * + * Input: target = 4, nums = [1,4,4] + * Output: 1 + * Example 3: + * + * Input: target = 11, nums = [1,1,1,1,1,1,1,1] + * Output: 0 + * + * + * Constraints: + * + * 1 <= target <= 109 + * 1 <= nums.length <= 105 + * 1 <= nums[i] <= 104 + * + * https://leetcode.com/problems/minimum-size-subarray-sum/ + */ +public class MinimumSizeSubarraySum { + public static void main(String[] args) { + int[] nums = {2, 3, 1, 2, 4, 3}; + + int target = 7; + int ans = solve(nums, target); + System.out.println(ans); + } + public static int solve(int[] nums, int target) { + // O(N) time | O(1) space + + // Sliding Window + + int leftIdx = 0, + rightIdx = 0, + currentSum = 0, + minIdx = Integer.MAX_VALUE, + len = nums.length; + + // Variable size sliding window: 2 - pointer + while (rightIdx < len) { + int currentNum = nums[rightIdx]; + currentSum += currentNum; + + if (currentSum >= target) { // Check id currentSum >= target + //Skip all left elements until currentSum < target (To find the smallest window) + while (currentSum >= target) { + currentSum -= nums[leftIdx++]; + } + int currentWindowSize = rightIdx - leftIdx + 1 + 1; // including leftIdx - 1 idx and update smallest window size. + minIdx = Math.min(minIdx, currentWindowSize); + } + rightIdx++; + } + return minIdx == Integer.MAX_VALUE ? 0 : minIdx; + + // O(N^2) time | O(1) space +// int ans = Integer.MAX_VALUE, len = nums.length; +// for (int i = 0; i < len; i++) {; +// int sum = 0; +// for (int j = i; j < len; j++) { +// int currentNum = nums[j]; +// sum += currentNum; +// if (sum >= target) { +// ans = Math.min(ans, j - i + 1); +// } +// } +// } +// return ans == Integer.MAX_VALUE ? 0 : ans; + + + + } +} From 0617ec42fe6591770d7b3313bd630f332c9cd7ae Mon Sep 17 00:00:00 2001 From: anandv07 Date: Tue, 31 Jan 2023 16:51:23 +0530 Subject: [PATCH 0003/1894] Add binarysearch java --- Binary_Search/FloorOfTarget.java | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Binary_Search/FloorOfTarget.java diff --git a/Binary_Search/FloorOfTarget.java b/Binary_Search/FloorOfTarget.java new file mode 100644 index 00000000..93df8e39 --- /dev/null +++ b/Binary_Search/FloorOfTarget.java @@ -0,0 +1,42 @@ +/* Floor of an element in a sorted array + You are given a sorted array nums and a target . + Find the index of the greatest element that is less than or equal to target + + EXAMPLES: + INPUT : nums = [2,4,5,7,9,11,18,25], target = 18 + OUTPUT: 6 + + INPUT : nums = [2,4,5,7,9,11,18,25], target = 10 + OUTPUT: 4 + + APPROACH : + We will implement this problem using BinarySearch since the array is sorted and will be similar to ceil + but with slight modification + + */ + + +public class FloorOfTarget{ + + public static int search_floor(int[] nums,int target){ + int start = 0,end = nums.length-1; + while(start <=end){ + int mid = start +(end-start)/2; + if(nums[mid]==target){ + return mid; // returns the target + } + else if(nums[mid] > target){ + end = mid-1; + } + else{ + start = mid +1; + } + } + return end; // returns the nearest element to target if the target is not found + } + public static void main(String[] args){ + int[] nums = {2,4,5,7,9,11,18,25}; + int target = 10; // output will be 4 in this case. + System.out.print(search_floor(nums,target)); +} +} From 7c7eb68e5c4619119a9865a777b4fec2ef6c715c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Jan 2023 22:24:16 +0530 Subject: [PATCH 0004/1894] add first repeating character --- HashTable/first_repeated_character.go | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 HashTable/first_repeated_character.go diff --git a/HashTable/first_repeated_character.go b/HashTable/first_repeated_character.go new file mode 100644 index 00000000..0c05be46 --- /dev/null +++ b/HashTable/first_repeated_character.go @@ -0,0 +1,33 @@ +// Program to find first repeating character in a word +// Sample Input : "DataStructures" +// Output: a + +package main + +import "fmt" + +func FirstRepeatedCCharacter(word string) byte { + length := len(word) + + hMap := [256]int{} // Extended Ascii can support 256 different characters + + // initialize hMap values to 0 + for i := 0; i < 256; i++ { + hMap[i] = 0 + } + + // every time you see a character in a word increment its position in hMap + for i := 0; i < length; i++ { + // if character is already present incase "1" then return character + if hMap[word[i]] == 1 { + return word[i] + } + // increment value in position of character + hMap[word[i]]++ + } + return byte(0) +} + +func main() { + fmt.Printf("%c",FirstRepeatedCCharacter("DataStructures")) +} \ No newline at end of file From 9803fa8da1d5a0262a67e0d99e79c6998758e12c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Jan 2023 22:43:46 +0530 Subject: [PATCH 0005/1894] add SeparateEvenAndOdd --- Searching/separate_even_odd.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Searching/separate_even_odd.go diff --git a/Searching/separate_even_odd.go b/Searching/separate_even_odd.go new file mode 100644 index 00000000..795e2b20 --- /dev/null +++ b/Searching/separate_even_odd.go @@ -0,0 +1,32 @@ +// Program to separate Even and Odd numbers +// Sample input: [1, 2, 3, 4, 5, 6] +// Output : [6 2 4 3 5 1] + +package main + +import "fmt" + +func SeparateEvenAndOdd(Arr []int) []int { + start, end := 0, len(Arr) - 1 + + for start < end { + for Arr[start] % 2 == 0 && start < end { + start++ // element in correct place so just increment the counter + } + for Arr[end] % 2 == 1 && start < end { + end-- // element in correct place so just decrement the counter + } + // two pointers start and end which are not in correct place so need to be swapped + if start < end { + Arr[start], Arr[end] = Arr[end], Arr[start] + start++ + end-- + } + } + return Arr +} + +func main() { + Arr := []int{1, 2, 3, 4, 5, 6} + fmt.Println(SeparateEvenAndOdd(Arr)) +} \ No newline at end of file From 0f50e5115cc1e51d8aa1618ce086d98f4ef4141c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Jan 2023 22:48:47 +0530 Subject: [PATCH 0006/1894] add SeparateZerosAndOnes --- Searching/separate_0s_and_1s.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Searching/separate_0s_and_1s.go diff --git a/Searching/separate_0s_and_1s.go b/Searching/separate_0s_and_1s.go new file mode 100644 index 00000000..d49f3def --- /dev/null +++ b/Searching/separate_0s_and_1s.go @@ -0,0 +1,32 @@ +// Program to separate Zeros and Ones +// Sample input: [0, 1, 0, 1, 0, 0, 1] +// Output : [0, 0, 0, 0, 1, 1, 1] + +package main + +import "fmt" + +func SeparateZerosAndOnes(Arr []int) []int { + start, end := 0, len(Arr) - 1 + + for start < end { + for Arr[start] == 0 && start < end { + start++ // element in correct place so just increment the counter + } + for Arr[end] == 1 && start < end { + end-- // element in correct place so just decrement the counter + } + // two pointers start and end which are not in correct place so need to be swapped + if start < end { + Arr[start], Arr[end] = Arr[end], Arr[start] + start++ + end-- + } + } + return Arr +} + +func main() { + Arr := []int{0, 1, 1, 0, 1, 0, 0, 1} + fmt.Println(SeparateZerosAndOnes(Arr)) +} \ No newline at end of file From 1d3294fd48be4975a681594999108706fc0829ef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Jan 2023 23:03:50 +0530 Subject: [PATCH 0007/1894] update contributing.md --- CONTRIBUTING.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 05e35a88..4b8ea80f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,8 +3,10 @@ Contributions are always welcome! - Pick any good first issue +- Read description on the issue (Mostly it will be the link to the question) - Add question on top of file - Add sample input and output - Explain approach with comments +- Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) -- Send a PR +- Send a PR against dev branch From b219d082e1881db6f27d4e24f6e58a89f7a9e58f Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 1 Feb 2023 08:37:56 +0530 Subject: [PATCH 0008/1894] create single number Solution. --- Bit_Manipulation/single_number.java | 73 +++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Bit_Manipulation/single_number.java diff --git a/Bit_Manipulation/single_number.java b/Bit_Manipulation/single_number.java new file mode 100644 index 00000000..ff3a6cf6 --- /dev/null +++ b/Bit_Manipulation/single_number.java @@ -0,0 +1,73 @@ +/** + * Given an array of integers A, every element appears twice except for one. Find that integer that occurs once. + * + * NOTE: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? + * + * + * + * Problem Constraints + * 1 <= |A| <= 2000000 + * + * 0 <= A[i] <= INTMAX + * + * + * + * Input Format + * The first and only argument of input contains an integer array A. + * + * + * + * Output Format + * Return a single integer denoting the single element. + * + * + * + * Example Input + * Input 1: + * + * A = [1, 2, 2, 3, 1] + * Input 2: + * + * A = [1, 2, 2] + * + * + * Example Output + * Output 1: + * + * 3 + * Output 2: + * + * 1 + * + * + * Example Explanation + * Explanation 1: + * + * 3 occurs once. + * Explanation 2: + * + * 1 occurs once. + */ +package BitManipulation; + +import com.google.common.base.Stopwatch; + +public class SingleNumber { + public static void main(String[] args) { + Stopwatch timer = Stopwatch.createStarted(); + + int[] arr = {1, 2, 2, 3, 1}; + int ans = solve(arr); + System.out.println(ans); + + System.out.println("Runtime " + timer); + } + public static int solve(int[] array) { + // O(N) time | O(1) space + int ans = 0; + + for (int num : array) ans ^= num; + + return ans; + } +} From 630d3ba15286aa00d4c3091c6c2b8a675fcf073a Mon Sep 17 00:00:00 2001 From: kingson299 Date: Wed, 1 Feb 2023 20:41:18 +0800 Subject: [PATCH 0009/1894] add queue_using_stack.js --- Queues/queue_using_stack.js | 90 +++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Queues/queue_using_stack.js diff --git a/Queues/queue_using_stack.js b/Queues/queue_using_stack.js new file mode 100644 index 00000000..aed98f31 --- /dev/null +++ b/Queues/queue_using_stack.js @@ -0,0 +1,90 @@ +/* +Implement a first in first out (FIFO) queue using only two stacks. +The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). + +Implement the MyQueue class: + +void push(int x) Pushes element x to the back of the queue. +- method adds an element to the back of the queue by pushing it onto stack1. + + +int pop() Removes the element from the front of the queue and returns it. +- method removes and returns the front element of the queue by first checking if stack2 is empty. +- if it is, reversing the elements from stack1 onto stack2 so that the front element + of the queue is now at the top of stack2. +- Then it pops the top element from stack2. + + +int peek() Returns the element at the front of the queue. +- returns the front element of the queue without removing it. +- First checking if stack2 is empty +- if it is, reversing the elements from stack1 onto stack2 so that the front element of the queue is now at the top of stack2. +- Then it returns the top element of stack2. + + +boolean empty() Returns true if the queue is empty, false otherwise. +- returns a boolean indicating whether the queue is empty or not. +- It returns true if both stack1 and stack2 are empty, and false otherwise. +*/ + +var MyQueue = function() { + this.stack1 = []; + this.stack2 = []; +}; + + +/** + * @param {number} x + * @return {void} + */ +MyQueue.prototype.push = function(x) { + this.stack1.push(x); +}; + + +/** + * @return {number} + */ +MyQueue.prototype.pop = function() { + if (this.stack2.length === 0) { + if (this.stack1.length === 0) { + return "Underflow"; + } + while (this.stack1.length > 0) { + this.stack2.push(this.stack1.pop()); + } + } + return this.stack2.pop(); +}; + +/** + * @return {number} + */ +MyQueue.prototype.peek = function() { + if (this.stack2.length === 0) { + if (this.stack1.length === 0) { + return "Queue is empty"; + } + while (this.stack1.length > 0) { + this.stack2.push(this.stack1.pop()); + } + } + return this.stack2[this.stack2.length - 1]; +}; + +/** + * @return {boolean} + */ +MyQueue.prototype.empty = function() { + return this.stack1.length === 0 && this.stack2.length === 0; +}; + + +// MyQueue object will be instantiated and called as such: +let myQueue = new MyQueue(); +var param_0 = myQueue.push(1); // queue is: [1] +var param_1 = myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) +var param_2 = myQueue.peek(); // return 1 +var param_3 = myQueue.pop(); // return 1, queue is [2] +var param_4 = myQueue.empty(); // return false + From a471fbaac1d56743f36107afb79923f67d566c48 Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 1 Feb 2023 20:42:01 +0530 Subject: [PATCH 0010/1894] create decimal_to_any_base.java Solution. --- Bit_Manipulation/decimal_to_any_base.java | 66 +++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Bit_Manipulation/decimal_to_any_base.java diff --git a/Bit_Manipulation/decimal_to_any_base.java b/Bit_Manipulation/decimal_to_any_base.java new file mode 100644 index 00000000..d7550b6c --- /dev/null +++ b/Bit_Manipulation/decimal_to_any_base.java @@ -0,0 +1,66 @@ +/** + * You are given a number A. You are also given a base B. A is a number on base B. + * You are required to convert the number A into its corresponding value in decimal number system. + * + * + * Problem Constraints + * 0 <= A <= 109 + * 2 <= B <= 9 + * + * + * Input Format + * First argument A is an integer. + * Second argument B is an integer. + * + * + * Output Format + * Return an integer. + * + * + * Example Input + * Input 1: + * A = 1010 + * B = 2 + * Input 2: + * A = 22 + * B = 3 + * + * + * Example Output + * Output 1: + * 10 + * Output 2: + * 8 + * + * + * Example Explanation + * For Input 1: + * The decimal 10 in base 2 is 1010. + * For Input 2: + * The decimal 8 in base 3 is 22. + */ +package BitManipulation; + +public class AnyBaseToDecimal { + public static void main(String[] args) { + int num = 22; + int base = 3; + int ans = solve(num, base); + System.out.println(ans); + } + public static int solve(int num, int base) { + // O(1) time | O(1) space + int currentNum = num; + int ans = 0; + int len = String.valueOf(num).length() - 1; + int i = 0; + + while (i <= len) { + int currentDigit = currentNum % 10; + currentNum = currentNum / 10; + ans += (int) Math.pow(base, i) * currentDigit; + i++; + } + return ans; + } +} From 1257113b06d53895d3cfaeb2ec789fb6fdc9ad84 Mon Sep 17 00:00:00 2001 From: Uday Date: Wed, 1 Feb 2023 20:49:01 +0530 Subject: [PATCH 0011/1894] Update decimal_to_any_base.java --- Bit_Manipulation/decimal_to_any_base.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/Bit_Manipulation/decimal_to_any_base.java b/Bit_Manipulation/decimal_to_any_base.java index d7550b6c..b9feffb5 100644 --- a/Bit_Manipulation/decimal_to_any_base.java +++ b/Bit_Manipulation/decimal_to_any_base.java @@ -50,17 +50,13 @@ public static void main(String[] args) { } public static int solve(int num, int base) { // O(1) time | O(1) space - int currentNum = num; - int ans = 0; - int len = String.valueOf(num).length() - 1; - int i = 0; - - while (i <= len) { + int res = 0 , multiplier = 1, currentNum = num; + while(currentNum > 0){ int currentDigit = currentNum % 10; - currentNum = currentNum / 10; - ans += (int) Math.pow(base, i) * currentDigit; - i++; + res += multiplier * currentDigit; + multiplier *= base; + currentNum /= 10; } - return ans; + return res; } } From adcd76960aae755d950ac30576b40ae6337c7942 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Feb 2023 22:42:15 +0530 Subject: [PATCH 0012/1894] update contributing.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b8ea80f..5fd0f7a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Contributions are always welcome! -- Pick any good first issue +- Pick any good first issue and add comment on it (Example: "I'll take this up") - Read description on the issue (Mostly it will be the link to the question) - Add question on top of file - Add sample input and output From 5c606690ede6e4dd651bcccf0ea3c4e31ca4fc08 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Feb 2023 22:42:36 +0530 Subject: [PATCH 0013/1894] update readme.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index eaae885b..e7f00f83 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ ## Contributing Contributions are always welcome! +You can join the fun by following our contributing guide. 🌈 Everyone is welcome! Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) From 91ab0b26fec81b099cfb54ceae9a6d3a4bd23eae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Feb 2023 22:50:22 +0530 Subject: [PATCH 0014/1894] update readme.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e7f00f83..8a0dc795 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ ## Contributing -Contributions are always welcome! -You can join the fun by following our contributing guide. 🌈 Everyone is welcome! +🌈 Everyone is welcome! +You can join the fun by following our contributing guide. Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) ## Fork this repository -Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. +Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. - [How to Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo) From 7a50f569961be32f750c0a0767813da22c39c2f6 Mon Sep 17 00:00:00 2001 From: uday510 Date: Fri, 3 Feb 2023 00:13:20 +0530 Subject: [PATCH 0015/1894] create mod_array.java --- Bit_Manipulation/decimal_to_any_base.java | 2 +- Bit_Manipulation/mod_array.java | 70 +++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 Bit_Manipulation/mod_array.java diff --git a/Bit_Manipulation/decimal_to_any_base.java b/Bit_Manipulation/decimal_to_any_base.java index b9feffb5..b8c672d7 100644 --- a/Bit_Manipulation/decimal_to_any_base.java +++ b/Bit_Manipulation/decimal_to_any_base.java @@ -54,7 +54,7 @@ public static int solve(int num, int base) { while(currentNum > 0){ int currentDigit = currentNum % 10; res += multiplier * currentDigit; - multiplier *= base; + multiplier *= B; currentNum /= 10; } return res; diff --git a/Bit_Manipulation/mod_array.java b/Bit_Manipulation/mod_array.java new file mode 100644 index 00000000..3c3931cc --- /dev/null +++ b/Bit_Manipulation/mod_array.java @@ -0,0 +1,70 @@ +/** + * You are given a large number in the form of a array A of size N where each element denotes a digit of the number. + * You are also given a number B. You have to find out the value of A % B and return it. + * + * + * + * Problem Constraints + * 1 <= N <= 105 + * 0 <= Ai <= 9 + * 1 <= B <= 109 + * + * + * Input Format + * The first argument is an integer array A. + * The second argument is an integer B. + * + * + * Output Format + * Return a single integer denoting the value of A % B. + * + * + * Example Input + * Input 1: + * A = [1, 4, 3] + * B = 2 + * Input 2: + * + * A = [4, 3, 5, 3, 5, 3, 2, 1] + * B = 47 + * + * + * Example Output + * Output 1: + * 1 + * Output 2: + * + * 20 + * + * + * Example Explanation + * Explanation 1: + * 143 is an odd number so 143 % 2 = 1. + * Explanation 2: + * + * 43535321 % 47 = 20 + */ + +package ModularArithmetic; + +public class ModArray { + public static void main(String[] args) { + int[] array = {4, 3, 5, 3, 5, 3, 2, 1}; + int b = 47; + int ans = solve(array, b); + System.out.println(ans); + } + public static int solve(int[] array, int b) { + // O(N) time | O(1) space + int res = 0; + int len = array.length - 1; + int POWER_10 = 1; + + for (int i = len; i > -1; i--) { + int currentDigit = array[i]; + res += ( (currentDigit % b) * (currentDigit % b) ) % b; + POWER_10 = (POWER_10 * 10) % b; + } + return res; + } +} From 2c9e607a15b01ca331f92bd52f2e717eb426687a Mon Sep 17 00:00:00 2001 From: uday510 Date: Fri, 3 Feb 2023 01:19:30 +0530 Subject: [PATCH 0016/1894] Fixed Solution that giving wrong answer for larger inputs --- Bit_Manipulation/mod_array.java | 64 +++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/Bit_Manipulation/mod_array.java b/Bit_Manipulation/mod_array.java index 3c3931cc..e2f6c309 100644 --- a/Bit_Manipulation/mod_array.java +++ b/Bit_Manipulation/mod_array.java @@ -45,6 +45,54 @@ * 43535321 % 47 = 20 */ +/** + * You are given a large number in the form of a array A of size N where each element denotes a digit of the number. + * You are also given a number B. You have to find out the value of A % B and return it. + * + * + * + * Problem Constraints + * 1 <= N <= 105 + * 0 <= Ai <= 9 + * 1 <= B <= 109 + * + * + * Input Format + * The first argument is an integer array A. + * The second argument is an integer B. + * + * + * Output Format + * Return a single integer denoting the value of A % B. + * + * + * Example Input + * Input 1: + * A = [1, 4, 3] + * B = 2 + * Input 2: + * + * A = [4, 3, 5, 3, 5, 3, 2, 1] + * B = 47 + * + * + * Example Output + * Output 1: + * 1 + * Output 2: + * + * 20 + * + * + * Example Explanation + * Explanation 1: + * 143 is an odd number so 143 % 2 = 1. + * Explanation 2: + * + * 43535321 % 47 = 20 + */ + + package ModularArithmetic; public class ModArray { @@ -54,17 +102,19 @@ public static void main(String[] args) { int ans = solve(array, b); System.out.println(ans); } - public static int solve(int[] array, int b) { + public static int solve(int[] array, int divisor) { // O(N) time | O(1) space - int res = 0; + long res = 0; int len = array.length - 1; - int POWER_10 = 1; + long POWER_10 = 1; + long MOD = divisor; for (int i = len; i > -1; i--) { - int currentDigit = array[i]; - res += ( (currentDigit % b) * (currentDigit % b) ) % b; - POWER_10 = (POWER_10 * 10) % b; + long currentDigit = array[i]; + long currentValue = (currentDigit * POWER_10) % MOD; + res = (res + currentValue) % MOD; + POWER_10 = (POWER_10 * 10) % MOD; } - return res; + return (int) res; } } From 08cecfde242b4d8c8f18dbe5c9db3d9d35900d04 Mon Sep 17 00:00:00 2001 From: Uday Date: Fri, 3 Feb 2023 01:23:07 +0530 Subject: [PATCH 0017/1894] Fix Solution for larger inputs --- Bit_Manipulation/mod_array.java | 64 +++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/Bit_Manipulation/mod_array.java b/Bit_Manipulation/mod_array.java index 3c3931cc..e2f6c309 100644 --- a/Bit_Manipulation/mod_array.java +++ b/Bit_Manipulation/mod_array.java @@ -45,6 +45,54 @@ * 43535321 % 47 = 20 */ +/** + * You are given a large number in the form of a array A of size N where each element denotes a digit of the number. + * You are also given a number B. You have to find out the value of A % B and return it. + * + * + * + * Problem Constraints + * 1 <= N <= 105 + * 0 <= Ai <= 9 + * 1 <= B <= 109 + * + * + * Input Format + * The first argument is an integer array A. + * The second argument is an integer B. + * + * + * Output Format + * Return a single integer denoting the value of A % B. + * + * + * Example Input + * Input 1: + * A = [1, 4, 3] + * B = 2 + * Input 2: + * + * A = [4, 3, 5, 3, 5, 3, 2, 1] + * B = 47 + * + * + * Example Output + * Output 1: + * 1 + * Output 2: + * + * 20 + * + * + * Example Explanation + * Explanation 1: + * 143 is an odd number so 143 % 2 = 1. + * Explanation 2: + * + * 43535321 % 47 = 20 + */ + + package ModularArithmetic; public class ModArray { @@ -54,17 +102,19 @@ public static void main(String[] args) { int ans = solve(array, b); System.out.println(ans); } - public static int solve(int[] array, int b) { + public static int solve(int[] array, int divisor) { // O(N) time | O(1) space - int res = 0; + long res = 0; int len = array.length - 1; - int POWER_10 = 1; + long POWER_10 = 1; + long MOD = divisor; for (int i = len; i > -1; i--) { - int currentDigit = array[i]; - res += ( (currentDigit % b) * (currentDigit % b) ) % b; - POWER_10 = (POWER_10 * 10) % b; + long currentDigit = array[i]; + long currentValue = (currentDigit * POWER_10) % MOD; + res = (res + currentValue) % MOD; + POWER_10 = (POWER_10 * 10) % MOD; } - return res; + return (int) res; } } From fc628ca21b8a34517f23a22fd6a4a9d54370d6b8 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 3 Feb 2023 14:24:38 +0530 Subject: [PATCH 0018/1894] Strings folder added, reverse string file added --- Strings/reverse_strings.js | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Strings/reverse_strings.js diff --git a/Strings/reverse_strings.js b/Strings/reverse_strings.js new file mode 100644 index 00000000..e83356a6 --- /dev/null +++ b/Strings/reverse_strings.js @@ -0,0 +1,41 @@ +/// Problem Statement: +/// You are given a string of length N. You need to reverse the string word by word. There can be multiple spaces between two words and there can be leading or trailing spaces but, in the output, reversed string you need to put a single space between two words, and your reversed string should not contain leading or trailing spaces. + +/// Sample Input: You need to reverse the string word by word +/// Expected Output: word by word string the reverse to need You + +/// Decalaration of function which will receive string to reverese +function reverseString(inputString) { + /// Trim function removes all the leading and trailing spaces, Split method store them in the array inputStringArray + var trimmedString = inputString.trim(); + var inputStringArray = trimmedString.split(" "); + + /// Variable declaration to store the output result + var outputString = ""; + + /// Loop through the array in reverse order to reverse the string, subtracting -1 from length because length starts from 1 but index strats from 0 + for (i = inputStringArray.length - 1; i >= 0; i--) { + /// If its a first iteration then store the word in variable otherwise concatenate it with the current string + if (i == inputStringArray.length - 1) { + outputString = inputStringArray[i] + " "; + } else { + /// Checking if its an empty string then continue otherwise store it in variable + if (inputStringArray[i] == "") { + continue; + } else { + outputString += inputStringArray[i] + " "; + } + } + } + return outputString.trim(); +} + +// console.log("You are given a string of length N"); +// console.log(reverseString("You are given a string of length N")); + +console.log(" You need to reverse the string word by word "); +console.log( + reverseString( + " You need to reverse the string word by word " + ) +); From 94000f87a3fee6fb71f943660763ce5d6405c17b Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 3 Feb 2023 14:32:12 +0530 Subject: [PATCH 0019/1894] Solution optimized --- Strings/reverse_strings.js | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/Strings/reverse_strings.js b/Strings/reverse_strings.js index e83356a6..40d7a17a 100644 --- a/Strings/reverse_strings.js +++ b/Strings/reverse_strings.js @@ -16,15 +16,10 @@ function reverseString(inputString) { /// Loop through the array in reverse order to reverse the string, subtracting -1 from length because length starts from 1 but index strats from 0 for (i = inputStringArray.length - 1; i >= 0; i--) { /// If its a first iteration then store the word in variable otherwise concatenate it with the current string - if (i == inputStringArray.length - 1) { - outputString = inputStringArray[i] + " "; + if (inputStringArray[i] == "") { + continue; } else { - /// Checking if its an empty string then continue otherwise store it in variable - if (inputStringArray[i] == "") { - continue; - } else { - outputString += inputStringArray[i] + " "; - } + outputString += inputStringArray[i] + " "; } } return outputString.trim(); From 982489570f3c351dea401e56b08ec46c2af23ed5 Mon Sep 17 00:00:00 2001 From: Uday Date: Fri, 3 Feb 2023 18:27:20 +0530 Subject: [PATCH 0020/1894] Update mod_array solution --- Bit_Manipulation/mod_array.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Bit_Manipulation/mod_array.java b/Bit_Manipulation/mod_array.java index e2f6c309..6321cd0c 100644 --- a/Bit_Manipulation/mod_array.java +++ b/Bit_Manipulation/mod_array.java @@ -98,8 +98,8 @@ public class ModArray { public static void main(String[] args) { int[] array = {4, 3, 5, 3, 5, 3, 2, 1}; - int b = 47; - int ans = solve(array, b); + int divisor = 47; + int ans = solve(array, divisor); System.out.println(ans); } public static int solve(int[] array, int divisor) { From 3f4d1fb5bd920a731f49aa1566e4e7b09aa70920 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:09:55 +0530 Subject: [PATCH 0021/1894] update contribution.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5fd0f7a0..8916c7a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Contributions are always welcome! -- Pick any good first issue and add comment on it (Example: "I'll take this up") +- Pick any good first issue and add comment on it (Example: "I'll take this up"), or Add classic DSA problem which is currently not present in this repo - Read description on the issue (Mostly it will be the link to the question) - Add question on top of file - Add sample input and output From 77912b181fe353fda536bd97ae5b0fa27830bfd0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:13:54 +0530 Subject: [PATCH 0022/1894] update code_of_conduct.md --- CODE_OF_CONDUCT.md | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 18c91471..82a2301c 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -12,28 +12,36 @@ and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. +## Conflict resolution + +When multiple contributors disagree on the direction for a particular patch or the general direction of the project, the conflict should be resolved by communication. The people who disagree should get together, try to understand each other's points of view, and work to find a design that addresses everyone's concerns. + +This is usually sufficient to resolve issues. If you cannot come to an agreement, ask for the advice of a more senior member of the project. + +Be wary of agreement by attrition, where one person argues a point repeatedly until other participants give up in the interests of moving on. This is not conflict resolution, as it does not address everyone's concerns. Be wary of agreement by compromise, where two good competing solutions are merged into one mediocre solution. A conflict is addressed when the participants agree that the final solution is better than all the conflicting proposals. Sometimes the solution is more work than either of the proposals. Embrace the yak shave. + ## Our Standards Examples of behavior that contributes to a positive environment for our community include: -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience -* Focusing on what is best not just for us as individuals, but for the +- Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or +- The use of sexualized language or imagery, and sexual attention or advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities @@ -106,7 +114,7 @@ Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an +standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within From ac502c1d50f715be3d5998fcbc22573deb4b0310 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:15:44 +0530 Subject: [PATCH 0023/1894] update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 8a0dc795..472315b8 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,10 @@ 🌈 Everyone is welcome! You can join the fun by following our contributing guide. +Before you get started, we encourage you to read these documents which describe some of our community norms: + +Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CODE_OF_CONDUCT.md), which stipulates explicitly that everyone must be gracious, respectful, and professional. This also documents our conflict resolution policy and encourages people to ask questions. + Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) ## Fork this repository From a3017aecc7d384217f1137069810496265429439 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:20:46 +0530 Subject: [PATCH 0024/1894] update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 472315b8..8777cb98 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,12 @@ 🌈 Everyone is welcome! You can join the fun by following our contributing guide. +Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) + Before you get started, we encourage you to read these documents which describe some of our community norms: Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CODE_OF_CONDUCT.md), which stipulates explicitly that everyone must be gracious, respectful, and professional. This also documents our conflict resolution policy and encourages people to ask questions. -Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) - ## Fork this repository Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. From a798a821a0261357179d652e5a7501f456499038 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:38:07 +0530 Subject: [PATCH 0025/1894] add logo --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 8777cb98..8a8fe2d0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ + +

+ + + Data Structures & Algorithms + +

+
# Implementation of well known Data Structures and Algorithms ## Contributing From 50799293a2ba09d41a32cdd8f22a5f3944704e23 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Feb 2023 22:39:24 +0530 Subject: [PATCH 0026/1894] fix heading --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8a8fe2d0..50eb55d7 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ + # Implementation of well known Data Structures and Algorithms ## Contributing From 7b63838350b774849a192f1481b20fbe79bce07f Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 4 Feb 2023 14:03:59 +0530 Subject: [PATCH 0027/1894] Add interesting array problem solution --- Bit_Manipulation/interesting_array.java | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Bit_Manipulation/interesting_array.java diff --git a/Bit_Manipulation/interesting_array.java b/Bit_Manipulation/interesting_array.java new file mode 100644 index 00000000..52d9cbf0 --- /dev/null +++ b/Bit_Manipulation/interesting_array.java @@ -0,0 +1,26 @@ +package BitManipulation; + +import com.google.common.base.Stopwatch; + +public class InterestingArray { + public static void main(String[] args) { + Stopwatch timer = Stopwatch.createStarted(); + + int[] array = {9, 14, 27, 81, 197, 0, 1}; + String ans = solve(array); + System.out.println(ans); + + System.out.println("Runtime " + timer); + } + + public static String solve(int[] array) { + // O(N) time | O(1) space + int oddCount = 0; + + for (var num : array) + if (num % 2 != 0) + oddCount += 1; + + return oddCount % 2 != 0 ? "No" : "Yes"; + } +} From 4af5f38ea688e2fd5e8b9b34d9b2173d9539b034 Mon Sep 17 00:00:00 2001 From: Ansh Tripathi <110754826+Anshtripathi079@users.noreply.github.com> Date: Sat, 4 Feb 2023 15:38:10 +0530 Subject: [PATCH 0028/1894] Create selectionsort.py --- sorting/selectionsort.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 sorting/selectionsort.py diff --git a/sorting/selectionsort.py b/sorting/selectionsort.py new file mode 100644 index 00000000..6717d6c3 --- /dev/null +++ b/sorting/selectionsort.py @@ -0,0 +1,31 @@ +# Selection sort in Python + +# Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list. + +# Time complexity = O(n^2) and Space complexity = O(n). + +# Sample input = [-2, 45, 0, 11, -9] , Output = [-9, -2, 0, 11, 45] + + +def selectionSort(array, size): + + for step in range(size): + min_idx = step + + for i in range(step + 1, size): + + # to sort in descending order, change > to < in this line + # select the minimum element in each loop + + if array[i] < array[min_idx]: + min_idx = i + + # put min at the correct position + (array[step], array[min_idx]) = (array[min_idx], array[step]) + + +data = [-2, 45, 0, 11, -9] +size = len(data) +selectionSort(data, size) +print('Sorted Array in Ascending Order:') +print(data) \ No newline at end of file From 6e9edaee512a56836c9ed9c12db528b086d151bb Mon Sep 17 00:00:00 2001 From: Ansh Tripathi <110754826+Anshtripathi079@users.noreply.github.com> Date: Sat, 4 Feb 2023 16:27:19 +0530 Subject: [PATCH 0029/1894] Create selectionsort.java --- sorting/selectionsort.java | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 sorting/selectionsort.java diff --git a/sorting/selectionsort.java b/sorting/selectionsort.java new file mode 100644 index 00000000..d70eabed --- /dev/null +++ b/sorting/selectionsort.java @@ -0,0 +1,47 @@ +// Selection sort in Java +// Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list. + +// Time complexity = O(n^2) and Space complexity = O(n). + +// Sample input = [20, 12, 10, 15, 2] , Output = [2, 10, 12, 15, 20] + +import java.util.Arrays; + +class SelectionSort { + void selectionSort(int array[]) + { + int size = array.length; + + for (int step = 0; step < size - 1; step++) + { + int min_idx = step; + + for (int i = step + 1; i < size; i++) + { + // To sort in descending order, change > to < in this line. + // Select the minimum element in each loop. + + if (array[i] < array[min_idx]) + { + min_idx = i; + } + } + + // put min at the correct position + + int temp = array[step]; + array[step] = array[min_idx]; + array[min_idx] = temp; + } + } + + // driver code + public static void main(String args[]) + { + int[] data = { 20, 12, 10, 15, 2 }; + SelectionSort ss = new SelectionSort(); + ss.selectionSort(data); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} \ No newline at end of file From f747fe34f6e3fb37d6b5c4b17b678fddb7cb645f Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 4 Feb 2023 18:59:23 +0530 Subject: [PATCH 0030/1894] Add subArrayWithBitwiseOR1 solution --- .../subarrays_with_bitwise_OR_1.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Bit_Manipulation/subarrays_with_bitwise_OR_1.java diff --git a/Bit_Manipulation/subarrays_with_bitwise_OR_1.java b/Bit_Manipulation/subarrays_with_bitwise_OR_1.java new file mode 100644 index 00000000..eda139d2 --- /dev/null +++ b/Bit_Manipulation/subarrays_with_bitwise_OR_1.java @@ -0,0 +1,68 @@ +/** + * Problem Description + * Given an array B of length A with elements 1 or 0. Find the number of subarrays such that the bitwise OR of all the elements present in the subarray is 1. + * + * + * Problem Constraints + * 1 <= A <= 105 + * + * + * Input Format + * The first argument is a single integer A. + * The second argument is an integer array B. + * + * + * Output Format + * Return the number of subarrays with bitwise array 1. + * + * + * Example Input + * Input 1: + * A = 3 + * B = [1, 0, 1] + * Input 2: + * A = 2 + * B = [1, 0] + * + * + * Example Output + * Output 1: + * 5 + * Output2: + * 2 + * + * + * Example Explanation + * Explanation 1: + * The subarrays are :- [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] + * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 + * Explanation 2: + * The subarrays are :- [1], [0], [1, 0] + * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 + */ + +package BitManipulation; + +public class subArrayWithBitwiseOR1 { + public static void main(String[] args) { + int[] array = {1, 0, 1}; + int n = 3; + int ans = solve(array, n); + System.out.println(ans); + } + public static int solve(int[] array, int len) { + // O(N) time | O(1) space + int possibleSubarraysWithThisIdx = 0; + int ans = 0; + + for (int i = 0; i < len; i++) { + int currentNum = array[i]; + if (currentNum == 1) + possibleSubarraysWithThisIdx = i + 1; + + ans += possibleSubarraysWithThisIdx; + } + + return ans; + } +} From 217cc2bd1ab6c0af19368c0fbfbc099adb284fff Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Feb 2023 19:25:51 +0530 Subject: [PATCH 0031/1894] add integer to roman in cpp --- HashTable/integer_to_roman.cpp | 61 ++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 HashTable/integer_to_roman.cpp diff --git a/HashTable/integer_to_roman.cpp b/HashTable/integer_to_roman.cpp new file mode 100644 index 00000000..93871651 --- /dev/null +++ b/HashTable/integer_to_roman.cpp @@ -0,0 +1,61 @@ +/* +Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. + +Given an integer, convert it to a roman numeral. + +Example 1: + +Input: num = 3 +Output: "III" +Explanation: 3 is represented as 3 ones. +Example 2: + +Input: num = 58 +Output: "LVIII" +Explanation: L = 50, V = 5, III = 3. +Example 3: + +Input: num = 1994 +Output: "MCMXCIV" +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + + +Constraints: + +1 <= num <= 3999 + +*/ + +class Solution { +public: + string intToRoman(int num) { + // Store Roamn characters according to their order + string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + string M[] = {"", "M", "MM", "MMM"}; + string result; + // build up the result from higher value i.e M down to lower i.e I + result += M[num/1000]; + result += C[(num % 1000) / 100]; + result += X[(num % 100) / 10]; + result += I[num % 10]; + return result; + } +}; \ No newline at end of file From 8dc068d095153cbebf8b0b3ca700238d71989532 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Feb 2023 19:28:38 +0530 Subject: [PATCH 0032/1894] add roman to integer in cpp --- HashTable/roman_to_integer.cpp | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 HashTable/roman_to_integer.cpp diff --git a/HashTable/roman_to_integer.cpp b/HashTable/roman_to_integer.cpp new file mode 100644 index 00000000..53775306 --- /dev/null +++ b/HashTable/roman_to_integer.cpp @@ -0,0 +1,66 @@ +/* +Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. +Given a roman numeral, convert it to an integer. + + + +Example 1: + +Input: s = "III" +Output: 3 +Explanation: III = 3. +Example 2: + +Input: s = "LVIII" +Output: 58 +Explanation: L = 50, V= 5, III = 3. +Example 3: + +Input: s = "MCMXCIV" +Output: 1994 +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + + +Constraints: + +1 <= s.length <= 15 +s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). +It is guaranteed that s is a valid roman numeral in the range [1, 3999]. + +*/ + +class Solution { +public: + int romanToInt(string s) { + // Map Roman Characters to integer values + unordered_map mp = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}, }; + int len = s.size(); + int sum = mp[s[len-1]]; + // start from end and build up the value to start + for(int i = len - 2; i >= 0; i--){ + if(mp[s[i]] < mp[s[i + 1]]){ + sum -= mp[s[i]]; + } + else{ + sum += mp[s[i]]; + } + } + return sum; + } +}; \ No newline at end of file From f9d0b18f323482b7a987a97b27b84e546532003a Mon Sep 17 00:00:00 2001 From: Ansh Tripathi <110754826+Anshtripathi079@users.noreply.github.com> Date: Sat, 4 Feb 2023 19:30:28 +0530 Subject: [PATCH 0033/1894] Create insertionsort.java --- sorting/insertionsort.java | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sorting/insertionsort.java diff --git a/sorting/insertionsort.java b/sorting/insertionsort.java new file mode 100644 index 00000000..8b915356 --- /dev/null +++ b/sorting/insertionsort.java @@ -0,0 +1,48 @@ +// Insertion sort in Java + +// Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. + +// Time complexity = O(n^2) and Space complexity = O(1). + +// Sample input = [ 9, 5, 1, 4, 3] , Output = [1, 3, 4, 5, 9] + + +import java.util.Arrays; + +class InsertionSort + { + + void insertionSort(int array[]) + { + int size = array.length; + + for (int step = 1; step < size; step++) + { + int key = array[step]; + int j = step - 1; + + // Compare key with each element on the left of it until an element smaller than + // it is found. + // For descending order, change keyarray[j]. + + while (j >= 0 && key < array[j]) + { + array[j + 1] = array[j]; + --j; + } + + // Place key at after the element just smaller than it. + array[j + 1] = key; + } + } + + // Driver code + public static void main(String args[]) + { + int[] data = { 9, 5, 1, 4, 3 }; + InsertionSort is = new InsertionSort(); + is.insertionSort(data); + System.out.println("Sorted Array in Ascending Order: "); + System.out.println(Arrays.toString(data)); + } +} \ No newline at end of file From 6efeca821993320c53cf5e11af4c51b4baaadbc8 Mon Sep 17 00:00:00 2001 From: Kamal Pratik Date: Sun, 5 Feb 2023 02:55:21 +0530 Subject: [PATCH 0034/1894] Added the solution for Integer to Roman problem in java language --- HashTable/integer_to_roman.java | 75 +++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 HashTable/integer_to_roman.java diff --git a/HashTable/integer_to_roman.java b/HashTable/integer_to_roman.java new file mode 100644 index 00000000..e5ca77da --- /dev/null +++ b/HashTable/integer_to_roman.java @@ -0,0 +1,75 @@ +/* +Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. +Given an integer, convert it to a roman numeral. + +Example 1: + +Input: num = 3 +Output: "III" +Explanation: 3 is represented as 3 ones. +Example 2: + +Input: num = 58 +Output: "LVIII" +Explanation: L = 50, V = 5, III = 3. +Example 3: + +Input: num = 1994 +Output: "MCMXCIV" +Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + +Constraints: + +1 <= num <= 3999 +*/ + +class Solution { + public String intToRoman(int num) { + String ones[] = {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX"}; + String tens[] = {"XX","XXX","XL","L","LX","LXX","LXXX","XC"}; + StringBuilder str = new StringBuilder(); + if (num>=1000) { + int t = num/1000; + for (int i = 1; i <= t; i++) str.append("M"); + num = num%1000; + } + if (num>=900){ + str.append("CM"); + num = num%900; + } + if (num>=500) { + str.append("D"); + num = num%500; + } + if (num>=400) { + str.append("CD"); + num = num%400; + } + if (num>=100) { + int t = num/100; + for (int i = 1; i <= t; i++) str.append("C"); + num = num % 100; + } + if (num>=20) { + str.append(tens[num/10-2]); + num = num % 10; + } + if (num>0) str.append(ones[num-1]); + return str.toString(); + } +} \ No newline at end of file From d186e355ecde7966e5a902c12357a331f871e8d9 Mon Sep 17 00:00:00 2001 From: Kamal Pratik Date: Sun, 5 Feb 2023 03:22:12 +0530 Subject: [PATCH 0035/1894] Added a more readable solution to Integer to Roman java solution --- HashTable/integer_to_roman.java | 41 +++++++------------------- git branch | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 31 deletions(-) create mode 100644 git branch diff --git a/HashTable/integer_to_roman.java b/HashTable/integer_to_roman.java index e5ca77da..cc4a1504 100644 --- a/HashTable/integer_to_roman.java +++ b/HashTable/integer_to_roman.java @@ -40,36 +40,15 @@ C can be placed before D (500) and M (1000) to make 400 and 900. class Solution { public String intToRoman(int num) { - String ones[] = {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX"}; - String tens[] = {"XX","XXX","XL","L","LX","LXX","LXXX","XC"}; - StringBuilder str = new StringBuilder(); - if (num>=1000) { - int t = num/1000; - for (int i = 1; i <= t; i++) str.append("M"); - num = num%1000; - } - if (num>=900){ - str.append("CM"); - num = num%900; - } - if (num>=500) { - str.append("D"); - num = num%500; - } - if (num>=400) { - str.append("CD"); - num = num%400; - } - if (num>=100) { - int t = num/100; - for (int i = 1; i <= t; i++) str.append("C"); - num = num % 100; - } - if (num>=20) { - str.append(tens[num/10-2]); - num = num % 10; - } - if (num>0) str.append(ones[num-1]); - return str.toString(); + int numsVal[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < numsVal.length; i++) { + while (num >= numsVal[i]) { + sb.append(romans[i]); + num -= numsVal[i]; + } + } + return sb.toString(); } } \ No newline at end of file diff --git a/git branch b/git branch new file mode 100644 index 00000000..881d8f7e --- /dev/null +++ b/git branch @@ -0,0 +1,52 @@ +diff --git a/HashTable/integer_to_roman.java b/HashTable/integer_to_roman.java +index e5ca77d..cc4a150 100644 +--- a/HashTable/integer_to_roman.java ++++ b/HashTable/integer_to_roman.java +@@ -40,36 +40,15 @@ Constraints: +  + class Solution { + public String intToRoman(int num) { +- String ones[] = {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX"}; +- String tens[] = {"XX","XXX","XL","L","LX","LXX","LXXX","XC"}; +- StringBuilder str = new StringBuilder(); +- if (num>=1000) { +- int t = num/1000; +- for (int i = 1; i <= t; i++) str.append("M"); +- num = num%1000;  +- } +- if (num>=900){ +- str.append("CM"); +- num = num%900; +- } +- if (num>=500) { +- str.append("D"); +- num = num%500;  +- } +- if (num>=400) { +- str.append("CD"); +- num = num%400; +- } +- if (num>=100) { +- int t = num/100; +- for (int i = 1; i <= t; i++) str.append("C"); +- num = num % 100; +- } +- if (num>=20) { +- str.append(tens[num/10-2]); +- num = num % 10;  +- } +- if (num>0) str.append(ones[num-1]); +- return str.toString(); ++ int numsVal[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; ++ String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; ++ StringBuilder sb = new StringBuilder();  ++ for (int i = 0; i < numsVal.length; i++) { ++ while (num >= numsVal[i]) { ++ sb.append(romans[i]); ++ num -= numsVal[i]; ++ } ++ }  ++ return sb.toString(); + } + } +\ No newline at end of file From 97e7a10f576eb844f3c6c3181f96bf9c5e5cab9d Mon Sep 17 00:00:00 2001 From: Kamal Pratik Date: Sun, 5 Feb 2023 03:48:21 +0530 Subject: [PATCH 0036/1894] Added a more readable solution of Integer to Roman java solution --- HashTable/integer_to_roman.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HashTable/integer_to_roman.java b/HashTable/integer_to_roman.java index cc4a1504..71feaf9f 100644 --- a/HashTable/integer_to_roman.java +++ b/HashTable/integer_to_roman.java @@ -41,7 +41,7 @@ C can be placed before D (500) and M (1000) to make 400 and 900. class Solution { public String intToRoman(int num) { int numsVal[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + String[] romans = {"M" , "CM" , "D" , "CD" , "C" , "XC" , "L" , "XL" , "X" , "IX" , "V" , "IV" , "I"}; StringBuilder sb = new StringBuilder(); for (int i = 0; i < numsVal.length; i++) { while (num >= numsVal[i]) { From 8d20c09e23abc6e1fe5ba27535dee8fa15a9b9ba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Feb 2023 11:55:53 +0530 Subject: [PATCH 0037/1894] remove junk --- git branch | 52 ---------------------------------------------------- 1 file changed, 52 deletions(-) delete mode 100644 git branch diff --git a/git branch b/git branch deleted file mode 100644 index 881d8f7e..00000000 --- a/git branch +++ /dev/null @@ -1,52 +0,0 @@ -diff --git a/HashTable/integer_to_roman.java b/HashTable/integer_to_roman.java -index e5ca77d..cc4a150 100644 ---- a/HashTable/integer_to_roman.java -+++ b/HashTable/integer_to_roman.java -@@ -40,36 +40,15 @@ Constraints: -  - class Solution { - public String intToRoman(int num) { -- String ones[] = {"I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV","XVI","XVII","XVIII","XIX"}; -- String tens[] = {"XX","XXX","XL","L","LX","LXX","LXXX","XC"}; -- StringBuilder str = new StringBuilder(); -- if (num>=1000) { -- int t = num/1000; -- for (int i = 1; i <= t; i++) str.append("M"); -- num = num%1000;  -- } -- if (num>=900){ -- str.append("CM"); -- num = num%900; -- } -- if (num>=500) { -- str.append("D"); -- num = num%500;  -- } -- if (num>=400) { -- str.append("CD"); -- num = num%400; -- } -- if (num>=100) { -- int t = num/100; -- for (int i = 1; i <= t; i++) str.append("C"); -- num = num % 100; -- } -- if (num>=20) { -- str.append(tens[num/10-2]); -- num = num % 10;  -- } -- if (num>0) str.append(ones[num-1]); -- return str.toString(); -+ int numsVal[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; -+ String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; -+ StringBuilder sb = new StringBuilder();  -+ for (int i = 0; i < numsVal.length; i++) { -+ while (num >= numsVal[i]) { -+ sb.append(romans[i]); -+ num -= numsVal[i]; -+ } -+ }  -+ return sb.toString(); - } - } -\ No newline at end of file From 18cb3acd553557e6038c42b2dd7994439b259a81 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Feb 2023 12:03:03 +0530 Subject: [PATCH 0038/1894] modify file name --- 2D-Arrays/binarySearch.cpp => 2D_Arrays/2d_binary_search.cpp | 0 {2D-Arrays => 2D_Arrays}/search_el.cpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename 2D-Arrays/binarySearch.cpp => 2D_Arrays/2d_binary_search.cpp (100%) rename {2D-Arrays => 2D_Arrays}/search_el.cpp (100%) diff --git a/2D-Arrays/binarySearch.cpp b/2D_Arrays/2d_binary_search.cpp similarity index 100% rename from 2D-Arrays/binarySearch.cpp rename to 2D_Arrays/2d_binary_search.cpp diff --git a/2D-Arrays/search_el.cpp b/2D_Arrays/search_el.cpp similarity index 100% rename from 2D-Arrays/search_el.cpp rename to 2D_Arrays/search_el.cpp From e40c1525eed818e136a9829351ddb470c9cfff0e Mon Sep 17 00:00:00 2001 From: Alec Swift Date: Sun, 5 Feb 2023 23:55:00 -0800 Subject: [PATCH 0039/1894] Add merge_sort.py --- sorting/merge_sort.py | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 sorting/merge_sort.py diff --git a/sorting/merge_sort.py b/sorting/merge_sort.py new file mode 100644 index 00000000..d406a046 --- /dev/null +++ b/sorting/merge_sort.py @@ -0,0 +1,56 @@ +# Time Complexity of O(nlogn) + +def main(): + # test for merge sort + a_lst = [3,2,-1,9,0,7,-3,-4,10,9] + merge_sort(a_lst, 0, 9) + print(a_lst) + +def merge_sort(a_lst: list[int], start: int, n: int) -> None: + if start < n: + mid: int = (start + n) // 2 + merge_sort(a_lst, start, mid) + merge_sort(a_lst, mid + 1, n) + merge(a_lst, start, mid, n) + + +def merge(a_lst: list[int], start: int, mid: int, n: int): + n_left: int = mid - start + 1 # length of left array + n_right: int = n - mid # length of right array + + left: list[int] = [0] * n_left # Initialize left and right arrays + right: list[int] = [0] * n_right + + for idx in range(n_left): # Fill left and right arrays + left[idx] = a_lst[start + idx] + for idx in range(n_right): + right[idx] = a_lst[mid + idx + 1] + + # Fill the orignal array with the smallest element from either + # left or right until left or right is empty + l_idx: int = 0 + r_idx: int = 0 + idx: int = start + while l_idx < len(left) and r_idx < len(right): + if left[l_idx] < right[r_idx]: + a_lst[idx] = left[l_idx] + l_idx += 1 + else: + a_lst[idx] = right[r_idx] + r_idx += 1 + idx += 1 + + # Fill the original array with the rest of the elements + # from the half array that is nonempty + + while l_idx < len(left): + a_lst[idx] = left[l_idx] + l_idx += 1 + idx += 1 + while r_idx < len(right): + a_lst[idx] = right[r_idx] + r_idx += 1 + idx += 1 + +if __name__ == "__main__": + main() From 9781f006f0ccfb332819ba14ad81ad241f4069f7 Mon Sep 17 00:00:00 2001 From: anandv07 Date: Mon, 6 Feb 2023 17:08:32 +0530 Subject: [PATCH 0040/1894] Add Binary Search Problem --- Binary_Search/CeilLetter.java | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Binary_Search/CeilLetter.java diff --git a/Binary_Search/CeilLetter.java b/Binary_Search/CeilLetter.java new file mode 100644 index 00000000..347fd9f9 --- /dev/null +++ b/Binary_Search/CeilLetter.java @@ -0,0 +1,47 @@ +/* Ceiling of an element in a sorted array + You are given a sorted array of characheters and a target . + Find the smallest character that is greater than target. + + Note : The letters wrap around in the array + ie, for an array ['c','d'], if target = 'z', then return first element in the array('a') + + + EXAMPLES: + INPUT : nums = ['a'.'b','c''g'.'l'], target = 'k' + OUTPUT: 'l' + + INPUT : nums = ['a'.'b','c''g'.'l'], target = 'l' + OUTPUT: 'a' + + APPROACH : + Approach will be similar to that of ceil of target except we don't need to check for equality. + + We will implement this problem using BinarySearch since the array is sorted. + + */ + + + +public class CeilLetter{ + public static int ceil(char[] arr,int target){ + int start = 0,end = arr.length-1; + while(start <=end){ + int mid = start +(end-start)/2; + if(arr[mid] > target){ + end = mid-1; + } + else{ + start = mid +1; + } + } + return start % arr.length ; // returns the first element if no element is greater than the target. + } + + public static void main(String[] args){ + + char[] arr = {'a','c','d','h','m'}; + int target = 'm'; + int index= ceil(arr,target); + System.out.println(arr[index]); +} + } \ No newline at end of file From 989cb19040fadc40df9f5fa79e04b41a5174d71c Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Mon, 6 Feb 2023 20:47:01 +0530 Subject: [PATCH 0041/1894] Added Median_of_Two_Sorted_Arrays.cpp --- Leetcode/Median_of_Two_Sorted_Arrays.cpp | 76 ++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Leetcode/Median_of_Two_Sorted_Arrays.cpp diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Leetcode/Median_of_Two_Sorted_Arrays.cpp new file mode 100644 index 00000000..9dcdc6ca --- /dev/null +++ b/Leetcode/Median_of_Two_Sorted_Arrays.cpp @@ -0,0 +1,76 @@ +/* +Approach: + let nums1 = [1, 3, 4, 7, 10, 12], nums2 = [2, 3, 6, 15] + + In order to find the median, we need a single sorted array. So a naive approach is that, just merge the 2 sorted arrays and find the median of that array. + This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) + + Now, lets optimise it. + So, the sorted form of the given array is [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. Now suppose, on partitioning the above merged-sorted array in the mid-point, we get 5 elements on left and 5 elements on the right. + Now, we can get 5 elements by selecting {4 from left, 1 from right}, {3 from left, 2 from right}, {2 from left, 3 from right} and {1 from left, 4 from right}. + Lets analyse case-wise: + case 1: 4 from left, 1 from right + +*/ + +#include + +class Solution { +public: + double findMedianSortedArrays(std::vector& nums1, std::vector& nums2) { + int n1 = nums1.size(); // stores the length of nums1 array + int n2 = nums2.size(); // stores the length of nums2 array + + if(n2 > n1) return findMedianSortedArrays(nums2, nums1); + + // according to approach described above, I am applying binary search on nums1 array + int lo = 0, hi = n1; + while(lo <= hi){ + int mid1 = (lo+hi)/2; // mid of nums1 + int mid2 = (n1 + n2 + 1)/2 - mid1; + // why?? => suppose nums1[] is partitioned at index 3 => nums1[3] = 7. + + std::pair maxleft, maxright; + maxleft.first = mid1 == 0 ? INT_MIN : nums1[mid1-1]; + maxleft.second = mid2 == 0 ? INT_MIN : nums2[mid2-1]; + + minright.first = mid1 == n1 ? INT_MAX : nums1[mid1]; + minright.second = mid2 == n2 ? INT_MAX : nums2[mid2]; + + if(maxleft.first <= minright.second and maxleft.second <= minright.first){ + if((n1+n2)%2 == 1){ + return std::max(maxleft.first, maxleft.second); + } else { + return (std::max(maxleft.first, maxleft.second) + std::min(minright.first, minright.second))/2.0; + } + } else if (maxleft.first > minright.second){ + hi = mid1-1; + } else { + lo = mid1+1; + } + } + } +}; + +int main(int argc, char const *argv[]) +{ + int n; + + std::cin>>n; + std::vector arr1(n, 0); + for(int i=0;i>arr1[i]; + } + + std::cin>>n; + std::vector arr2(n, 0); + for(int i=0;i>arr2[i]; + } + + const Solution sol = new Solution(); + double res = sol.findMedianSortedArrays(arr1, arr2); + + std::cout< Date: Mon, 6 Feb 2023 22:29:42 +0530 Subject: [PATCH 0042/1894] add longest substring without repeating characters in go (brute force) --- ...-substring-without-repeating-characters.go | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Sliding_Window/longest-substring-without-repeating-characters.go diff --git a/Sliding_Window/longest-substring-without-repeating-characters.go b/Sliding_Window/longest-substring-without-repeating-characters.go new file mode 100644 index 00000000..f7e50808 --- /dev/null +++ b/Sliding_Window/longest-substring-without-repeating-characters.go @@ -0,0 +1,62 @@ +package main + +/* +Given a string s, find the length of the longest substring without repeating characters. + + + +Example 1: + +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. +Example 2: + +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +Example 3: + +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + + +Constraints: + +0 <= s.length <= 5 * 104 +s consists of English letters, digits, symbols and spaces. +*/ +// Approach 1 Brute force +// Intuition +// Check all the substring one by one to see if it has no duplicate character. +func lengthOfLongestSubstring(s string) int { + n := len(s) + res := 0 + for i := 0; i < n; i++ { + for j := i; j < n; j++ { + if check(s, i, j) { + res = max(res, j - i + 1) + } + } + } + return res +} +func max(a, b int) int { + if a >= b { + return a + } else { + return b + } +} +func check(s string, start int, end int) bool { + hMap := [128]int{} + for i := start; i <= end; i++ { + hMap[s[i]]++ + if hMap[s[i]] > 1 { + return false + } + } + return true +} \ No newline at end of file From cccb077e5f13a171cec86f71c8ebf45379176b6f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Feb 2023 22:54:21 +0530 Subject: [PATCH 0043/1894] add time and space complexity --- Sliding_Window/longest-substring-without-repeating-characters.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Sliding_Window/longest-substring-without-repeating-characters.go b/Sliding_Window/longest-substring-without-repeating-characters.go index f7e50808..c40f51e5 100644 --- a/Sliding_Window/longest-substring-without-repeating-characters.go +++ b/Sliding_Window/longest-substring-without-repeating-characters.go @@ -31,6 +31,7 @@ s consists of English letters, digits, symbols and spaces. // Approach 1 Brute force // Intuition // Check all the substring one by one to see if it has no duplicate character. +// Time complexity O(n³ ) Space complexity O(m) where m is size of hMap func lengthOfLongestSubstring(s string) int { n := len(s) res := 0 From be4056c47806aaed1f2f81439de8e61d5c827f18 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Feb 2023 23:12:57 +0530 Subject: [PATCH 0044/1894] add sliding window approach --- ...-substring-without-repeating-characters.go | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Sliding_Window/longest-substring-without-repeating-characters.go b/Sliding_Window/longest-substring-without-repeating-characters.go index c40f51e5..6be51382 100644 --- a/Sliding_Window/longest-substring-without-repeating-characters.go +++ b/Sliding_Window/longest-substring-without-repeating-characters.go @@ -32,7 +32,7 @@ s consists of English letters, digits, symbols and spaces. // Intuition // Check all the substring one by one to see if it has no duplicate character. // Time complexity O(n³ ) Space complexity O(m) where m is size of hMap -func lengthOfLongestSubstring(s string) int { +func LengthOfLongestSubstring1(s string) int { n := len(s) res := 0 for i := 0; i < n; i++ { @@ -60,4 +60,24 @@ func check(s string, start int, end int) bool { } } return true +} + +// Approach 2: Sliding window +// Time complexity O(n) Space complexity O(m) where m is size of char +func LengthOfLongestSubstring2(s string) int { + result := 0 + for i := 0; i < len(s); i++ { + char := make(map[byte]bool) + char[s[i]] = true + for j := i + 1; j < len(s); j++ { + if _, ok := char[s[j]]; ok { + break + } + char[s[j]] = true + } + if len(char) > result { + result = len(char) + } + } + return result } \ No newline at end of file From 4a7dad2dd7a2ea00986f1a49d62981b6e2a394b7 Mon Sep 17 00:00:00 2001 From: Lucas Date: Mon, 6 Feb 2023 23:57:02 +0100 Subject: [PATCH 0045/1894] Added pow.js --- Math/pow.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Math/pow.js diff --git a/Math/pow.js b/Math/pow.js new file mode 100644 index 00000000..d867d1a3 --- /dev/null +++ b/Math/pow.js @@ -0,0 +1,19 @@ +// Implement pow(x, n), which calculates x raised to the power n (i.e., xn). +// Time complexity: O(log n) | Space complexity: O(log n) + +function pow(x, n) { + // Any number raised to 0 is 1) + if (n === 0) return 1 + // Power of a negative number is the reciprocal of power of positive number + if (n < 0) return 1 / pow(x, -n) + // If n is even, calculate pow(x, n / 2) and return the square of it + if (n % 2 === 0) return pow(x, n / 2) * pow(x, n / 2) + // If n is odd, return x * pow(x, n - 1) (x raised to odd power n can be represented as x * x^(n-1)) + return x * pow(x, n - 1) +} + +// Sample inputs and outputs +console.log(pow(2, 10)) // 1024 +console.log(pow(2, -3)) // 0.125 +console.log(pow(3, 3)) // 27 +console.log(pow(3, 0)) // 1 \ No newline at end of file From 7961bf3d34ec8ad1898ef7402b45bb5f279a4981 Mon Sep 17 00:00:00 2001 From: uday510 Date: Tue, 7 Feb 2023 17:37:44 +0530 Subject: [PATCH 0046/1894] Add NobleInteger Problem Solution --- sorting/noble_integer.java | 84 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 sorting/noble_integer.java diff --git a/sorting/noble_integer.java b/sorting/noble_integer.java new file mode 100644 index 00000000..ba26c404 --- /dev/null +++ b/sorting/noble_integer.java @@ -0,0 +1,84 @@ +/** + * Given an integer array A, find if an integer p exists in the array such that the number of integers greater than p in the array equals p. + * + * + * + * Problem Constraints + * 1 <= |A| <= 2*105 + * -108 <= A[i] <= 108 + * + * + * Input Format + * First and only argument is an integer array A. + * + * + * + * Output Format + * Return 1 if any such integer p is present else, return -1. + * + * + * + * Example Input + * Input 1: + * + * A = [3, 2, 1, 3] + * Input 2: + * + * A = [1, 1, 3, 3] + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * -1 + * + * + * Example Explanation + * Explanation 1: + * + * For integer 2, there are 2 greater elements in the array.. + * Explanation 2: + * + * There exist no integer satisfying the required conditions. + */ + +package Sorting; + +import java.util.Arrays; + +public class NobleInteger { + public static void main(String[] args) { + int[] arr = {3, 2, 1, 3}; + int res = solve(arr); + System.out.println(res); + } + public static int solve(int[] array) { + // O(NLog(N) time | O(1) space + int len = array.length - 1; + Arrays.sort(array); + int count = 0; + + if (array[len] == 0) return 1; + for (int i = len - 1; i > -1; i--) { + int currentNum = array[i], + previousNum = array[i + 1]; + if (currentNum != previousNum) count = len - i; + if (count == currentNum) return 1; + } + return -1; + + // O(N^2) time | O(1) space +// for (int previousNum : array) { +// int count = 0; +// for (int currentNum : array) { +// if (currentNum > previousNum) +// count++; +// } +// if (count == previousNum) return 1; +// } +// return -1; + } +} From 96a9a555449577d4a7b975afaed31ab0e32674eb Mon Sep 17 00:00:00 2001 From: uday510 Date: Tue, 7 Feb 2023 17:40:57 +0530 Subject: [PATCH 0047/1894] Add NumberOf1Bits Solution --- Bit_Manipulation/number_of_1_bits.java | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Bit_Manipulation/number_of_1_bits.java diff --git a/Bit_Manipulation/number_of_1_bits.java b/Bit_Manipulation/number_of_1_bits.java new file mode 100644 index 00000000..eb292191 --- /dev/null +++ b/Bit_Manipulation/number_of_1_bits.java @@ -0,0 +1,56 @@ +/** + * Write a function that takes an integer and returns the number of 1 bits it has. + * + * + * Problem Constraints + * 1 <= A <= 109 + * + * + * Input Format + * First and only argument contains integer A + * + * + * Output Format + * Return an integer as the answer + * + * + * Example Input + * Input 1: + * 11 + * Input 2: + * 6 + * + * + * Example Output + * Output 1: + * 3 + * Output 2: + * 2 + * + * + * Example Explanation + * Explaination 1: + * 11 is represented as 1011 in binary. + * Explaination 2: + * 6 is represented as 110 in binary. + */ + +package BitManipulation; + +public class NumberOf1Bits { + public static void main(String[] args) { + int num = 11; + int ans = solve(num); + System.out.println(ans); + } + public static int solve(int num) { + // O(Log(N)) tine | O(1) space + int currentNum = num, count = 0; + + while (currentNum != 0) { + if ( (currentNum & 1) == 1) count++; + currentNum = currentNum >> 1; + } + return count; + } +} From 981c544ea756c4c06ad1e0585c09b17b360ebae3 Mon Sep 17 00:00:00 2001 From: uday510 Date: Tue, 7 Feb 2023 17:52:35 +0530 Subject: [PATCH 0048/1894] Add subArrayWithBitwiseOR1 Problem Solution --- .../subarrays_with_bitwise_or.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Bit_Manipulation/subarrays_with_bitwise_or.java diff --git a/Bit_Manipulation/subarrays_with_bitwise_or.java b/Bit_Manipulation/subarrays_with_bitwise_or.java new file mode 100644 index 00000000..d1b84173 --- /dev/null +++ b/Bit_Manipulation/subarrays_with_bitwise_or.java @@ -0,0 +1,69 @@ +/** + * Problem Description + * Given an array B of length A with elements 1 or 0. Find the number of subarrays such that + * the bitwise OR of all the elements present in the subarray is 1. + * + * + * Problem Constraints + * 1 <= A <= 105 + * + * + * Input Format + * The first argument is a single integer A. + * The second argument is an integer array B. + * + * + * Output Format + * Return the number of subarrays with bitwise array 1. + * + * + * Example Input + * Input 1: + * A = 3 + * B = [1, 0, 1] + * Input 2: + * A = 2 + * B = [1, 0] + * + * + * Example Output + * Output 1: + * 5 + * Output2: + * 2 + * + * + * Example Explanation + * Explanation 1: + * The subarrays are :- [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] + * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 + * Explanation 2: + * The subarrays are :- [1], [0], [1, 0] + * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 + */ + +package BitManipulation; + +public class subArrayWithBitwiseOR1 { + public static void main(String[] args) { + int[] array = {1, 0, 1}; + int n = 3; + int ans = solve(array, n); + System.out.println(ans); + } + public static int solve(int[] array, int len) { + // O(N) time | O(1) space + int possibleSubarraysWithThisIdx = 0; + int ans = 0; + + for (int i = 0; i < len; i++) { + int currentNum = array[i]; + if (currentNum == 1) + possibleSubarraysWithThisIdx = i + 1; + + ans += possibleSubarraysWithThisIdx; + } + + return ans; + } +} From 19e71179c1fe189ce7525ce6acbe8825324f4f82 Mon Sep 17 00:00:00 2001 From: uday510 Date: Tue, 7 Feb 2023 17:54:15 +0530 Subject: [PATCH 0049/1894] Add FindGoodDays Problem Solution --- Bit_Manipulation/find_good_days.java | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Bit_Manipulation/find_good_days.java diff --git a/Bit_Manipulation/find_good_days.java b/Bit_Manipulation/find_good_days.java new file mode 100644 index 00000000..64a849e8 --- /dev/null +++ b/Bit_Manipulation/find_good_days.java @@ -0,0 +1,74 @@ +/** + * Problem Description + * Alex has a cat named Boomer. He decides to put his cat to the test for eternity. + * + * He starts on day 1 with one stash of food unit, every next day, the stash doubles. + * + * If Boomer is well behaved during a particular day, only then she receives food worth equal to the stash produced on that day. + * + * Boomer receives a net worth of A units of food. What is the number of days she received the stash? + * + * + * + * Problem Constraints + * 1 <= A <= 231-1 + * + * + * + * Input Format + * First and only argument is an integer A. + * + * + * + * Output Format + * Return an integer denoting the number of days Boomer was well behaved. + * + * + * + * Example Input + * Input 1: + * + * A = 5 + * Input 2: + * + * A = 8 + * + * + * Example Output + * Output 1: + * + * 2 + * Output 2: + * + * 1 + * + * + * Example Explanation + * Explanation 1: + * + * To eat a total of 5 units of food, Boomer behaved normally on Day 1 and on the Day 3. + * Explanation 2: + * + * To eat a total of 8 units of food, Boomer behaved normally only on day 4. + */ + +package BitManipulation; +public class FindGoodDays { + public static void main(String[] args) { + int a = 5; + int res = solve(a); + System.out.println(res); + } + public static int solve(int a) { + // O(N) time | O(1) space + + // Count 1 bits + int currentNum = a, res = 0; + + while (currentNum != 0) { + if ( (currentNum & 1) == 1) res++; + currentNum = currentNum >> 1; + } + return res; + } +} From 7cd7744de43cb0f7e5343a0822ded28572afa566 Mon Sep 17 00:00:00 2001 From: anandv07 Date: Tue, 7 Feb 2023 21:12:26 +0530 Subject: [PATCH 0050/1894] Add FirstOccurence BinarySearch Java --- Binary_Search/FirstOccurence.java | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Binary_Search/FirstOccurence.java diff --git a/Binary_Search/FirstOccurence.java b/Binary_Search/FirstOccurence.java new file mode 100644 index 00000000..816fee33 --- /dev/null +++ b/Binary_Search/FirstOccurence.java @@ -0,0 +1,56 @@ +/* Finding the index of the first occurence of a number in a sorted array: +Given a sorted array and a number x,find the first occurence of x in the +array. If the element is not found , return -1. + +Solve it in O(logN) complexity + +Example : + +INPUT : nums = [1,5,7,7,7,9,11,14], target = 7 +OUTPUT: 2 + +INPUT : nums = [1,2,4,6,45,55], target = 20 +OUTPUT: -1 + +Approach: + + # Approach will be similar to other binary search problems, but there is a need to find first occurence, + So ,if the element found is equal to target, make the end pointer point before of the mid value. + + # Once the condition violates and loop terminates ,check if the target value is equal to the start pointer value. + if it is equal, return the start pointer. if it is not return -1; + +*/ + + + +public class FirstOccurence{ + public static int firstOccurence(int[] arr,int target){ + int start = 0,end=arr.length-1; + while(start <= end){ + int mid = start + (end-start)/2; + if (arr[mid]== target){ + end = mid -1; + } + else if(arr[mid] > target){ + end = mid -1; + } + else if(arr[mid] < target){ + start = mid + 1; + } + } + if(start < arr.length && arr[start] == target){ + return start; + } + else{ + return -1; + } + } + + public static void main(String[] args){ + int[] arr = {1,5,7,7,7,9,11,14}; + int target = 7; + System.out.print(firstOccurence(arr,target)); + + } +} \ No newline at end of file From cbd7b9527d6e2f8a833983d21165c3a04d1e657a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Tue, 7 Feb 2023 22:30:15 +0530 Subject: [PATCH 0051/1894] Update CONTRIBUTING.md --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8916c7a7..c28f8441 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,3 +10,7 @@ Contributions are always welcome! - Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) - Send a PR against dev branch + +## What if the problem you want to add is not present in the issue? +- You can suggest an idea for this project under issues tab (add list of questions you think it is important, it will be assigned to you) +- You can directly make a PR against dev branch with the proposed problems with appropriate comments and description From ac0cbd2755fe3b6bc6e3a49f775abb4eb092642c Mon Sep 17 00:00:00 2001 From: Kushal Lahoti Date: Tue, 7 Feb 2023 22:47:51 +0530 Subject: [PATCH 0052/1894] Added power program in go --- Math/PowXn.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Math/PowXn.go diff --git a/Math/PowXn.go b/Math/PowXn.go new file mode 100644 index 00000000..e7eab949 --- /dev/null +++ b/Math/PowXn.go @@ -0,0 +1,38 @@ +/* Implement pow(x, n), which calculates x raised to the power n (i.e., xn). in Go + +--- Recursion Approach --- + +Example 1: +Input: x = 2, n = 10 +Output: 1024 + +Example 2: +Input: x = 2.10000, n = 3 +Output: 9.26100 + +Example 3: +Input: x = 2.00000, n = -2 +Output: 0.25000 + +Explanation: 2^(-2) = 1/(2^2) = 1/4 = 0.25 + +*/ + +package main +import "fmt" + +func Pow(x float64, n int) float64 { + switch { + case n == 0: return 1 + case n == 1: return x + case n < 0: return Pow(1/x, -n) + case n %2 == 0: return Pow(x*x, n/2) + } + return x*Pow(x*x, n/2) +} + +func main() { + var x float64 = 2 + var y int = 10 + fmt.Print(Pow(x, y)) +} \ No newline at end of file From bb08cdacf6326b2fc91db178b5a87c38daf159b2 Mon Sep 17 00:00:00 2001 From: uday510 Date: Tue, 7 Feb 2023 23:18:39 +0530 Subject: [PATCH 0053/1894] Add LargestNumber Problem Solution --- sorting/largest_number.java | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 sorting/largest_number.java diff --git a/sorting/largest_number.java b/sorting/largest_number.java new file mode 100644 index 00000000..fe850e46 --- /dev/null +++ b/sorting/largest_number.java @@ -0,0 +1,101 @@ +/** + * Given an array A of non-negative integers, arrange them such that they form the largest number. + * + * Note: The result may be very large, so you need to return a string instead of an integer. + * + * + * + * Problem Constraints + * 1 <= len(A) <= 100000 + * 0 <= A[i] <= 2*109 + * + * + * + * Input Format + * The first argument is an array of integers. + * + * + * + * Output Format + * Return a string representing the largest number. + * + * + * + * Example Input + * Input 1: + * + * A = [3, 30, 34, 5, 9] + * Input 2: + * + * A = [2, 3, 9, 0] + * + * + * Example Output + * Output 1: + * + * "9534330" + * Output 2: + * + * "9320" + * + * + * Example Explanation + * Explanation 1: + * + * Reorder the numbers to [9, 5, 34, 3, 30] to form the largest number. + * Explanation 2: + * + * Reorder the numbers to [9, 3, 2, 0] to form the largest number 9320. + * + * + * Reference : https://leetcode.com/problems/largest-number/solutions/53158/my-java-solution-to-share/ + */ +package Sorting; + +import java.util.Arrays; +import java.util.Comparator; + +public class LargestNumber { + + public static void main(String[] args) { + int[] array = {3, 30, 34, 5, 9}; + String res = solve(array); + System.out.println(res); + } + + public static String solve(int[] array) { + // O(N(Log(N)) time | O(n) space + if (array == null || array.length == 0) return ""; + + int len = array.length; + //1. Convert int array to String array + String[] stringArray = new String[len]; + for (int i = 0; i < len; i++) + stringArray[i] = String.valueOf(array[i]); + + //2. custom comparator to decide which string should come first. + Comparator comparator = new Comparator() { + @Override + public int compare(String o1, String o2) { // Eg: s1 = "9", s2 = "31" + String s1 = o1 + o2; // "931" + String s2 = o2 + o1; // "319" + + return s2.compareTo(s1); // reverse order + } + }; + + //3. Sort Strings according to custom comparator + Arrays.sort(stringArray, comparator); + + // An extreme edge case by leetcode, say you have only a bunch of 0 in your int array + // If, after being sorted, the largest number is `0`, the entire number + // is zero. + if (stringArray[0].charAt(0) == '0') return "0"; + + StringBuilder stringBuilder = new StringBuilder(); + for (String string : stringArray) { + stringBuilder.append(string); + } + return stringBuilder.toString(); + } +} From 36a87221c69071563ecd8be80664e918d51ef7e3 Mon Sep 17 00:00:00 2001 From: Kushal Lahoti Date: Tue, 7 Feb 2023 23:53:07 +0530 Subject: [PATCH 0054/1894] Added power program in python --- Math/PowXn.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Math/PowXn.py diff --git a/Math/PowXn.py b/Math/PowXn.py new file mode 100644 index 00000000..3a291051 --- /dev/null +++ b/Math/PowXn.py @@ -0,0 +1,27 @@ +# Implement pow(x, n), which calculates x raised to the power n (i.e., xn). in Go + +# --- Recursion Approach --- + +# Example 1: +# Input: x = 2, n = 10 +# Output: 1024 + +# Example 2: +# Input: x = 2.10000, n = 3 +# Output: 9.26100 + +# Example 3: +# Input: x = 2.00000, n = -2 +# Output: 0.25000 +# Explanation: 2^(-2) = 1/(2^2) = 1/4 = 0.25 + +def power(x, n): + if n == 0: return 1 + elif n<0: return power(1/x, -n) + else: return (x*power(x, n-1)) + + +if __name__ == '__main__': + x = 2 + n = 3 + print(power(x, n)) \ No newline at end of file From 8ff845171ff605578b4889f6a6af90e17258dc3e Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 8 Feb 2023 01:55:35 +0530 Subject: [PATCH 0055/1894] Add ThreeNumberSort Problem Solution --- sorting/largest_number.java | 1 + sorting/three_number_sort.java | 64 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 sorting/three_number_sort.java diff --git a/sorting/largest_number.java b/sorting/largest_number.java index fe850e46..2f7e77f5 100644 --- a/sorting/largest_number.java +++ b/sorting/largest_number.java @@ -96,6 +96,7 @@ public int compare(String o1, String o2) { // Eg: s1 = "9", s2 = "31" for (String string : stringArray) { stringBuilder.append(string); } + return stringBuilder.toString(); } } diff --git a/sorting/three_number_sort.java b/sorting/three_number_sort.java new file mode 100644 index 00000000..1071a96c --- /dev/null +++ b/sorting/three_number_sort.java @@ -0,0 +1,64 @@ +/** + * Three Number Sort + * + * You're given an array of integers and another array of three distinct integers. The first array is guaranteed to only contain integers that are in the second array, and the second array represents a desired order for the integers in the first array. For example, a second array of [x, y, z] represents a desired order of [x, x, ..., x, y, y, ..., y, z, z, ..., z] in the first array. + * + * Write a function that sorts the first array according to the desired order in the second array. + * + * The function should perform this in place (i.e., it should mutate the input array), and it shouldn't use any auxiliary space (i.e., it should run with constant space: O(1) space). + * + * Note that the desired order won't necessarily be ascending or descending and that the first array won't necessarily contain all three integers found in the second array—it might only contain one or two. + * Sample Input + * + * array = [1, 0, 0, -1, -1, 0, 1, 1] + * order = [0, 1, -1] + * + * Sample Output + * + * [0, 0, 0, 1, 1, 1, -1, -1] + */ + +package Sorting; + +import java.util.Arrays; + +public class ThreeNumberSort { + public static void main(String[] args) { + int[] array = {1, 0, 0, -1, -1, 0, 1, 1}; + int[] order = {0, 1, -1}; + + int[] res = solve(array, order); + System.out.println(Arrays.toString(res)); + } + public static int[] solve(int[] array, int[] order) { + // O(n) time | O(1) space - where n is the length of the array + + int firstValue = order[0]; + int secondValue = order[1]; + + int firstIdx = 0; + int secondIdx = 0; + int thirdIdx = array.length - 1; + + while (secondIdx <= thirdIdx) { + int value = array[secondIdx]; + + if (value == firstValue) { + swap(firstIdx, secondIdx, array); + firstIdx += 1; + secondIdx += 1; + } else if (value == secondValue) + secondIdx++; + else { + swap(secondIdx, thirdIdx, array); + thirdIdx -= 1; + } + } + return array; + } + public static void swap(int i, int j, int[] array) { + int temp = array[j]; + array[j] = array[i]; + array[i] = temp; + } +} From df6d85f6ca2135f9dcacd4f05d960085e5713bae Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 8 Feb 2023 02:00:01 +0530 Subject: [PATCH 0056/1894] Add DutchNationalFlag Problem Solution --- sorting/dutch_national_flag.java | 87 ++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 sorting/dutch_national_flag.java diff --git a/sorting/dutch_national_flag.java b/sorting/dutch_national_flag.java new file mode 100644 index 00000000..98e66c4a --- /dev/null +++ b/sorting/dutch_national_flag.java @@ -0,0 +1,87 @@ +/** + * Given an array with N objects colored red, white, or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + * + * We will use the integers 0, 1, and 2 to represent red, white, and blue, respectively. + * + * Note: Using the library sort function is not allowed. + * + * + * + * Problem Constraints + * 1 <= N <= 1000000 + * 0 <= A[i] <= 2 + * + * + * Input Format + * First and only argument of input contains an integer array A. + * + * + * Output Format + * Return an integer array in asked order + * + * + * Example Input + * Input 1 : + * A = [0 1 2 0 1 2] + * Input 2: + * + * A = [0] + * + * + * Example Output + * Output 1: + * [0 0 1 1 2 2] + * Output 2: + * + * [0] + * + * + * Example Explanation + * Explanation 1: + * [0 0 1 1 2 2] is the required order. + */ + +package Sorting; + +import java.util.Arrays; + +public class DutchNationalFlag { + + public static void main(String[] args) { + int[] array = {0, 0, 1, 1, 2, 2}; + + int[] res = solve(array); + System.out.println(Arrays.toString(res)); + } + public static int[] solve(int[] array) { + // O(n) time | O(1) space - where n is the length of the array + + int firstValue = 0; + int secondValue = 1; + + int firstIdx = 0; + int secondIdx = 0; + int thirdIdx = array.length - 1; + + while (secondIdx <= thirdIdx) { + int value = array[secondIdx]; + + if (value == firstValue) { + swap(firstIdx, secondIdx, array); + firstIdx += 1; + secondIdx += 1; + } else if (value == secondValue) + secondIdx++; + else { + swap(secondIdx, thirdIdx, array); + thirdIdx -= 1; + } + } + return array; + } + public static void swap(int i, int j, int[] array) { + int temp = array[j]; + array[j] = array[i]; + array[i] = temp; + } +} From a6db3bb8c6a5a1222b3e5d2af26c2883a5cfe71b Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 8 Feb 2023 02:11:10 +0530 Subject: [PATCH 0057/1894] Add CheckArithmeticProgression Problem Solution --- sorting/check_arithmetic_progression.java | 76 +++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 sorting/check_arithmetic_progression.java diff --git a/sorting/check_arithmetic_progression.java b/sorting/check_arithmetic_progression.java new file mode 100644 index 00000000..4d0d823b --- /dev/null +++ b/sorting/check_arithmetic_progression.java @@ -0,0 +1,76 @@ +/** + * Given an integer array A of size N. Return 1 if the array can be arranged to form an arithmetic progression, otherwise return 0. + * + * A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. + * + * + * + * Problem Constraints + * 2 <= N <= 105 + * + * -109 <= A[i] <= 109 + * + * + * + * Input Format + * The first and only argument is an integer array A of size N. + * + * + * + * Output Format + * Return 1 if the array can be rearranged to form an arithmetic progression, otherwise return 0. + * + * + * + * Example Input + * Input 1: + * + * A = [3, 5, 1] + * Input 2: + * + * A = [2, 4, 1] + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * 0 + * + * + * Example Explanation + * Explanation 1: + * + * We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. + * Explanation 2: + * + * There is no way to reorder the elements to obtain an arithmetic progression. + */ +package Sorting; + +import java.util.Arrays; + +public class CheckArithmeticProgression { + public static void main(String[] args) { + int[] array = {3, 5, 1}; + int res = solve(array); + System.out.println(res); + } + public static int solve(int[] A) { + // O(NLog(N)) time | O(1) space - where N is the length of the array + + Arrays.sort(A); + + int prevDiff = Math.abs(A[0] - A[1]); + for (int i = 2; i < A.length; i++) { + int prevNum = A[i-1]; + int currentNum = A[i]; + + int currentDiff = Math.abs(prevNum - currentNum); + if (prevDiff != currentDiff) return 0; + } + return 1; + } +} From 57646d562eee3c5aa218f04ff09e1fa88165cec2 Mon Sep 17 00:00:00 2001 From: uday510 Date: Wed, 8 Feb 2023 08:35:23 +0530 Subject: [PATCH 0058/1894] Add TensDigitSorting Problem Solution --- sorting/tens_digit_sorting.java | 115 ++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 sorting/tens_digit_sorting.java diff --git a/sorting/tens_digit_sorting.java b/sorting/tens_digit_sorting.java new file mode 100644 index 00000000..4607f6d3 --- /dev/null +++ b/sorting/tens_digit_sorting.java @@ -0,0 +1,115 @@ +/** + * Tens Digit Sorting + * + * + * Problem Description + * Given an array A of N integers. Sort the array in increasing order of the value at the tens place digit of every number. + * + * If a number has no tens digit, we can assume value to be 0. + * If 2 numbers have same tens digit, in that case number with max value will come first + * Solution should be based on comparator. + * + * + * Problem Constraints + * 1 <= N <= 105 + * + * 1 <= A[i] <= 109 + * + * + * + * Input Format + * First argument A is an array of integers. + * + * + * + * Output Format + * Return the array after sorting + * + * + * + * Example Input + * Input 1: + * A = [15, 11, 7, 19] + * Input 2: + * A = [2, 24, 22, 19] + * + * + * Example Output + * Output 1: + * [7, 19, 15, 11] + * Output 2: + * [2, 19, 24, 22] + * + * + * Example Explanation + * For Input 1: + * The sorted order is [7, 19, 15, 11]. The tens digit of 7 is 0, + * and that of 19, 15 and 11 is 1. + * For Input 2: + * The sorted order is [2, 19, 24, 22]. The tens digit of 2 is 0, + * that of 19 is 1 and that of 22 and 24 is 2. + */ + +package Sorting; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; + +public class TenDigitSorting { + public static void main(String[] args) { + ArrayList array = new ArrayList<>( + Arrays.asList(908, 903, 809, 801, 700, 608)); + + int[] arr = {7, 19, 15, 11}; + + // Using ArrayList + ArrayList res = solve(array); + System.out.println(res); + + // Using Array +// int[] res = solve(arr); +// System.out.println(Arrays.toString(res)); + } + public static ArrayList solve(ArrayList array) { + // O(N(Log(N)) time | O(1) space + Comparator comparator = new Comparator<>() { + @Override + public int compare(Integer val1, Integer val2) { + int num1 = (val1 / 10) % 10; + int num2 = (val2 / 10) % 10; + + if (num1 == num2) return val2.compareTo(val1); + return num1 - num2; + } + }; + + array.sort(comparator); + + return array; + } + + public static int[] solve(int[] array) { + // O(N(Log(N)) time | O(1) space + + Integer[] arr = new Integer[array.length]; + for (int i = 0; i < arr.length; i++) + arr[i] = array[i]; + Comparator comparator = new Comparator<>() { + @Override + public int compare(Integer val1, Integer val2) { + Integer num1 = val1 / 10; + Integer num2 = val2 / 10; + + return num1.compareTo(num2); + } + }; + + Arrays.sort(arr, comparator); + + for (int i = 0; i < arr.length; i++) + array[i] = arr[i]; + + return array; + } +} From c62bc9c07e10a2b9e7afb4902fc6660fe3463afc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Feb 2023 22:30:13 +0530 Subject: [PATCH 0059/1894] add trapping rain water --- Dynamic_Programming/trapping_rain_water.cpp | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Dynamic_Programming/trapping_rain_water.cpp diff --git a/Dynamic_Programming/trapping_rain_water.cpp b/Dynamic_Programming/trapping_rain_water.cpp new file mode 100644 index 00000000..3bcc198d --- /dev/null +++ b/Dynamic_Programming/trapping_rain_water.cpp @@ -0,0 +1,48 @@ + +/* +Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. + +Example 1: + +Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +Output: 6 + +Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. +Example 2: + +Input: height = [4,2,0,3,2,5] +Output: 9 + +Constraints: + +n == height.length +1 <= n <= 2 * 104 +0 <= height[i] <= 105 +*/ +#include + +class Solution { +public: + int trap(vector& height) { + int len = height.size(), result = 0; + if(len == 0) return 0; + int low = 0, high = len - 1, leftmax = 0, rightmax = 0; + while(low <= high){ + if(height[low] < height[high]){ + if(height[low] > leftmax) + leftmax = height[low]; + else + result += leftmax - height[low]; + low++; + } + else{ + if(height[high] > rightmax) + rightmax = height[high]; + else + result += rightmax - height[high]; + high--; + } + } + return result; + } +}; \ No newline at end of file From a7a391c7eddd6c4e484b1e3d170de1eef64f5b9b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Feb 2023 22:31:54 +0530 Subject: [PATCH 0060/1894] add zigzag conversion --- Strings/zigzag_conversion.cpp | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Strings/zigzag_conversion.cpp diff --git a/Strings/zigzag_conversion.cpp b/Strings/zigzag_conversion.cpp new file mode 100644 index 00000000..2dbb6ceb --- /dev/null +++ b/Strings/zigzag_conversion.cpp @@ -0,0 +1,62 @@ +/* +The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + +P A H N +A P L S I I G +Y I R +And then read line by line: "PAHNAPLSIIGYIR" + +Write the code that will take a string and make this conversion given a number of rows: + +string convert(string s, int numRows); + + +Example 1: + +Input: s = "PAYPALISHIRING", numRows = 3 +Output: "PAHNAPLSIIGYIR" +Example 2: + +Input: s = "PAYPALISHIRING", numRows = 4 +Output: "PINALSIGYAHRPI" +Explanation: +P I N +A L S I G +Y A H R +P I +Example 3: + +Input: s = "A", numRows = 1 +Output: "A" + + +Constraints: + +1 <= s.length <= 1000 +s consists of English letters (lower-case and upper-case), ',' and '.'. +1 <= numRows <= 1000 +*/ + +#include +class Solution { +public: + string convert(string s, int numRows) { + if(numRows <= 1) return s; + string *A = new string[numRows]; + int n = s.size(); + int row = 0; + int step = 1; + for(int i = 0; i < n; i++){ + A[row].push_back(s[i]); + if(row == 0) step = 1; + else if(row == numRows - 1) step = -1; + + row = row + step; + } + string ans = ""; + for(int i = 0; i < numRows; i++){ + ans += A[i]; + } + return ans; + } +}; \ No newline at end of file From be7005a416ab24c7f7106f7ad15c776c0c66ba1a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Feb 2023 22:36:32 +0530 Subject: [PATCH 0061/1894] add house robber problem --- Dynamic_Programming/house_robber.cpp | 54 ++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Dynamic_Programming/house_robber.cpp diff --git a/Dynamic_Programming/house_robber.cpp b/Dynamic_Programming/house_robber.cpp new file mode 100644 index 00000000..ddc286ec --- /dev/null +++ b/Dynamic_Programming/house_robber.cpp @@ -0,0 +1,54 @@ +/* +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. + + + +Example 1: + +Input: nums = [1,2,3,1] +Output: 4 +Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). +Total amount you can rob = 1 + 3 = 4. +Example 2: + +Input: nums = [2,7,9,3,1] +Output: 12 +Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). +Total amount you can rob = 2 + 9 + 1 = 12. + + +Constraints: + +1 <= nums.length <= 100 +0 <= nums[i] <= 400 +*/ + +#include + +class Solution { +public: + int rob(vector& nums) { + int len = nums.size(); + /* + if(len == 0) return 0; + if(len == 1) return nums[0]; + if(len == 2) return max(nums[0], nums[1]); + int dp[len]; + dp[0] = nums[0]; + dp[1] = max(nums[0], nums[1]); + for(int i = 2; i < len; i++){ + dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]); + } + return dp[len-1]; + */ + int prev = 0, curr = 0, temp = 0; + for(int i = 0; i < len; i++){ + temp = max(nums[i] + prev, curr); + prev = curr; + curr = temp; + } + return curr; + } +}; \ No newline at end of file From d25c4496f54141d46e708968ec7f1ff94ac74f0e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Feb 2023 22:41:54 +0530 Subject: [PATCH 0062/1894] add Maximum Length of a Concatenated String with Unique Characters --- ..._concatenated_string_with_unique_chars.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Strings/_len_of_concatenated_string_with_unique_chars.cpp diff --git a/Strings/_len_of_concatenated_string_with_unique_chars.cpp b/Strings/_len_of_concatenated_string_with_unique_chars.cpp new file mode 100644 index 00000000..d4a8a568 --- /dev/null +++ b/Strings/_len_of_concatenated_string_with_unique_chars.cpp @@ -0,0 +1,67 @@ +/* +You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. + +Return the maximum possible length of s. + +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + + + +Example 1: + +Input: arr = ["un","iq","ue"] +Output: 4 +Explanation: All the valid concatenations are: +- "" +- "un" +- "iq" +- "ue" +- "uniq" ("un" + "iq") +- "ique" ("iq" + "ue") +Maximum length is 4. +Example 2: + +Input: arr = ["cha","r","act","ers"] +Output: 6 +Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). +Example 3: + +Input: arr = ["abcdefghijklmnopqrstuvwxyz"] +Output: 26 +Explanation: The only string in arr has all 26 characters. + + +Constraints: + +1 <= arr.length <= 16 +1 <= arr[i].length <= 26 +arr[i] contains only lowercase English letters. +*/ + +#include +class Solution { +public: + int check(vector& arr, int i, string s){ + if(i == arr.size()){ + int freq[26] = {0}; + for(int k = 0; k < s.length(); k++){ + if(freq[s[k]-'a'] == 1) + return 0; + freq[s[k]-'a']++; + } + return s.length(); + } + int op1, op2; + op1 = op2 = INT_MIN; + // include the string + if(s.length() + arr[i].length() <= 26){ + op1 = check(arr, i+1, s + arr[i]); + } + // exclude it + op2 = check(arr, i+1, s); + return max(op1, op2); + } + int maxLength(vector& arr) { + return check(arr, 0, ""); + } +}; \ No newline at end of file From f901c30a24be4939a6c9e7e3251a1c73ed3d29d3 Mon Sep 17 00:00:00 2001 From: Mohammad-Farhan64 <19bcs2445@gmail.com> Date: Thu, 9 Feb 2023 05:22:12 +0530 Subject: [PATCH 0063/1894] created a new folder of c++ in that I added two file _len_of_concatenated_string_with_unique_chars.cpp and zigzag_conversion.cpp and new file create for Write a function to generate all combinations of well-formed parentheses in C++ --- ...ombinations_of_well_formed_parentheses.cpp | 40 +++++++++++++++++++ ..._concatenated_string_with_unique_chars.cpp | 0 Strings/{ => c++}/zigzag_conversion.cpp | 0 3 files changed, 40 insertions(+) create mode 100644 Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp rename Strings/{ => c++}/_len_of_concatenated_string_with_unique_chars.cpp (100%) rename Strings/{ => c++}/zigzag_conversion.cpp (100%) diff --git a/Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp b/Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp new file mode 100644 index 00000000..97b99e0f --- /dev/null +++ b/Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp @@ -0,0 +1,40 @@ +/* +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + + + +Example 1: + +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] +Example 2: + +Input: n = 1 +Output: ["()"] + + +Constraints: + +1 <= n <= 8 +*/ +#include +class Solution { +public: +vector ans; +int N; + void solve(string s,int count) + { + if(s.size()==2*N) + ans.push_back(s); + + if(count generateParenthesis(int n) { + string st; + solve(st,0); + return ans; + } +}; \ No newline at end of file diff --git a/Strings/_len_of_concatenated_string_with_unique_chars.cpp b/Strings/c++/_len_of_concatenated_string_with_unique_chars.cpp similarity index 100% rename from Strings/_len_of_concatenated_string_with_unique_chars.cpp rename to Strings/c++/_len_of_concatenated_string_with_unique_chars.cpp diff --git a/Strings/zigzag_conversion.cpp b/Strings/c++/zigzag_conversion.cpp similarity index 100% rename from Strings/zigzag_conversion.cpp rename to Strings/c++/zigzag_conversion.cpp From 537d814d3e04262c68fd23c6b9fecffe4cdfffbb Mon Sep 17 00:00:00 2001 From: Mohammad-Farhan64 <19bcs2445@gmail.com> Date: Thu, 9 Feb 2023 05:59:38 +0530 Subject: [PATCH 0064/1894] created Implement_pow(x, n).cpp --- Math/Implement_pow(x, n).cpp | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Math/Implement_pow(x, n).cpp diff --git a/Math/Implement_pow(x, n).cpp b/Math/Implement_pow(x, n).cpp new file mode 100644 index 00000000..07a355d8 --- /dev/null +++ b/Math/Implement_pow(x, n).cpp @@ -0,0 +1,49 @@ +/* +Implement pow(x, n), which calculates x raised to the power n (i.e., xn). + + + +Example 1: + +Input: x = 2.00000, n = 10 +Output: 1024.00000 +Example 2: + +Input: x = 2.10000, n = 3 +Output: 9.26100 +Example 3: + +Input: x = 2.00000, n = -2 +Output: 0.25000 +Explanation: 2-2 = 1/22 = 1/4 = 0.25 + + +Constraints: + +-100.0 < x < 100.0 +-231 <= n <= 231-1 +n is an integer. +-104 <= xn <= 104 + +if it we solve it though simply by recursion it will give time complexity of O(n) + so we will use divide and conquer approach that leads to O(logn) time complexity + eg. 3^7 dive seven by two 333 * 333 3 than in 333 divide by two 3 * 3 3 + on conquering 93 * 93 than again conquer 27 * 27 * 3 final output is 218 +*/ + +class Solution { +public: + double pow(double x, int n) + { + if(x==0)return 0; + if(n==0)return 1; + double res=pow(x,n/2); + res=res*res; + if(n%2)res=x*res; + return res; + } + double myPow(double x, int n) { + if(n<0)return pow(1/x,n); + return pow(x,n); + } +}; \ No newline at end of file From f302918d2a0c7d5eaf3f9fed0ca525d2b7f6eeb3 Mon Sep 17 00:00:00 2001 From: Mohammad-Farhan64 <19bcs2445@gmail.com> Date: Thu, 9 Feb 2023 06:15:15 +0530 Subject: [PATCH 0065/1894] moving all cpp file to newly created cpp folder --- Math/{ => cpp}/Implement_pow(x, n).cpp | 0 Math/{ => cpp}/modular_expo_itera.cpp | 54 +++++----- Math/{ => cpp}/modular_expo_recursive.cpp | 0 Math/{ => cpp}/prime_factorization.cpp | 96 ++++++++--------- Math/{ => cpp}/sieve_of_eratosthenes.cpp | 122 +++++++++++----------- 5 files changed, 136 insertions(+), 136 deletions(-) rename Math/{ => cpp}/Implement_pow(x, n).cpp (100%) rename Math/{ => cpp}/modular_expo_itera.cpp (96%) rename Math/{ => cpp}/modular_expo_recursive.cpp (100%) rename Math/{ => cpp}/prime_factorization.cpp (95%) rename Math/{ => cpp}/sieve_of_eratosthenes.cpp (96%) diff --git a/Math/Implement_pow(x, n).cpp b/Math/cpp/Implement_pow(x, n).cpp similarity index 100% rename from Math/Implement_pow(x, n).cpp rename to Math/cpp/Implement_pow(x, n).cpp diff --git a/Math/modular_expo_itera.cpp b/Math/cpp/modular_expo_itera.cpp similarity index 96% rename from Math/modular_expo_itera.cpp rename to Math/cpp/modular_expo_itera.cpp index b38432a0..db5d380a 100644 --- a/Math/modular_expo_itera.cpp +++ b/Math/cpp/modular_expo_itera.cpp @@ -1,27 +1,27 @@ -// Modular exponentiation is exponentiation performed over a modulus. -// It is useful in computer science, especially in the field of public-key cryptography, -// where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. -// Sample Input : 10 3 -// Output : 1000 -// Iterative approach -#include -using namespace std; -int modular_expo(int x, int n, int mod){ - int ans = 1; - while(n >= 1){ - if(n % 2 == 0){ - x = ((x % mod) * (x % mod)) % mod; - n /= 2; - } - else{ - ans = ((ans % mod) * (x % mod)) % mod; - n--; - } - } - return ans; -} -int main(){ - int mod = 1000000007; - cout << modular_expo(5, 3, mod); -return 0; -} +// Modular exponentiation is exponentiation performed over a modulus. +// It is useful in computer science, especially in the field of public-key cryptography, +// where it is used in both Diffie-Hellman Key Exchange and RSA public/private keys. +// Sample Input : 10 3 +// Output : 1000 +// Iterative approach +#include +using namespace std; +int modular_expo(int x, int n, int mod){ + int ans = 1; + while(n >= 1){ + if(n % 2 == 0){ + x = ((x % mod) * (x % mod)) % mod; + n /= 2; + } + else{ + ans = ((ans % mod) * (x % mod)) % mod; + n--; + } + } + return ans; +} +int main(){ + int mod = 1000000007; + cout << modular_expo(5, 3, mod); +return 0; +} diff --git a/Math/modular_expo_recursive.cpp b/Math/cpp/modular_expo_recursive.cpp similarity index 100% rename from Math/modular_expo_recursive.cpp rename to Math/cpp/modular_expo_recursive.cpp diff --git a/Math/prime_factorization.cpp b/Math/cpp/prime_factorization.cpp similarity index 95% rename from Math/prime_factorization.cpp rename to Math/cpp/prime_factorization.cpp index 7e87cfe6..2d204776 100644 --- a/Math/prime_factorization.cpp +++ b/Math/cpp/prime_factorization.cpp @@ -1,48 +1,48 @@ -// Prime factorisation is a method to find the prime factors of a given number, say a composite number. -// These factors are nothing but the prime numbers. A prime number is a number -// which has only two factors, i.e. 1 and the number itself. For example, 2 is a prime number which has two factors, 2 × 1 -// Sample Input: 10 -// Output -// 2->1 Times -// 5->1 Times -#include -using namespace std; - -int f[100], expo[100], len = -1; -void prime_factor(int n){ - int d = 2; - if(n == 1){ - len++; - f[len] = 2; - expo[len] = 0; - return; - } - while(n > 1 && 1ll * d * d <= n){ - int k = 0; - while(n % d == 0){ - n = n / d; - k++; - } - if(k > 0){ - len++; - f[len] = d; - expo[len] = k; - } - d++; - } - if(n > 1){ - len++; - f[len] = n; - expo[len] = 1; - } -} -int main(){ - int n; - cin >> n; - prime_factor(n); - for(int i = 0; i <= len; i++){ - cout << f[i] << "->" << expo[i] << " Times" << endl; - } - -return 0; -} +// Prime factorisation is a method to find the prime factors of a given number, say a composite number. +// These factors are nothing but the prime numbers. A prime number is a number +// which has only two factors, i.e. 1 and the number itself. For example, 2 is a prime number which has two factors, 2 × 1 +// Sample Input: 10 +// Output +// 2->1 Times +// 5->1 Times +#include +using namespace std; + +int f[100], expo[100], len = -1; +void prime_factor(int n){ + int d = 2; + if(n == 1){ + len++; + f[len] = 2; + expo[len] = 0; + return; + } + while(n > 1 && 1ll * d * d <= n){ + int k = 0; + while(n % d == 0){ + n = n / d; + k++; + } + if(k > 0){ + len++; + f[len] = d; + expo[len] = k; + } + d++; + } + if(n > 1){ + len++; + f[len] = n; + expo[len] = 1; + } +} +int main(){ + int n; + cin >> n; + prime_factor(n); + for(int i = 0; i <= len; i++){ + cout << f[i] << "->" << expo[i] << " Times" << endl; + } + +return 0; +} diff --git a/Math/sieve_of_eratosthenes.cpp b/Math/cpp/sieve_of_eratosthenes.cpp similarity index 96% rename from Math/sieve_of_eratosthenes.cpp rename to Math/cpp/sieve_of_eratosthenes.cpp index 9d95ecdb..9633d8c7 100644 --- a/Math/sieve_of_eratosthenes.cpp +++ b/Math/cpp/sieve_of_eratosthenes.cpp @@ -1,61 +1,61 @@ -// In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. -// It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, -// starting with the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers -// starting from that prime, with constant difference between them that is equal to that prime. -// This is the sieve's key distinction from using trial division to sequentially test each candidate -// number for divisibility by each prime. Once all the multiples of each discovered prime have been marked as composites, -// the remaining unmarked numbers are primes. Source(https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) - -// Sample INput: 100 -// Output : -// 3 -// 5 -// 7 -// 11 -// 13 -// 17 -// 19 -// 23 -// 29 -// 31 -// 37 -// 41 -// 43 -// 47 -// 53 -// 59 -// 61 -// 67 -// 71 -// 73 -// 79 -// 83 -// 89 -// 97 -#include -using namespace std; -const int nmax = 100001; -bool is_prime[nmax]; -void seive_of_ero(int n){ - for(int i = 2; i <= n; i++){ - is_prime[i] = true; - } - for(int i = 2; i <= n / 2; i++){ - if(is_prime[i]){ - for(int j = i * 2; j <= n; j += i){ - is_prime[j] = false; - } - } - } -} -int main(){ - int n; - cin >> n; - seive_of_ero(n); - for(int i = 0; i <= 500; i++){ - if(is_prime[i]) - cout << i << " " << endl; - } - -return 0; -} +// In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit. +// It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, +// starting with the first prime number, 2. The multiples of a given prime are generated as a sequence of numbers +// starting from that prime, with constant difference between them that is equal to that prime. +// This is the sieve's key distinction from using trial division to sequentially test each candidate +// number for divisibility by each prime. Once all the multiples of each discovered prime have been marked as composites, +// the remaining unmarked numbers are primes. Source(https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) + +// Sample INput: 100 +// Output : +// 3 +// 5 +// 7 +// 11 +// 13 +// 17 +// 19 +// 23 +// 29 +// 31 +// 37 +// 41 +// 43 +// 47 +// 53 +// 59 +// 61 +// 67 +// 71 +// 73 +// 79 +// 83 +// 89 +// 97 +#include +using namespace std; +const int nmax = 100001; +bool is_prime[nmax]; +void seive_of_ero(int n){ + for(int i = 2; i <= n; i++){ + is_prime[i] = true; + } + for(int i = 2; i <= n / 2; i++){ + if(is_prime[i]){ + for(int j = i * 2; j <= n; j += i){ + is_prime[j] = false; + } + } + } +} +int main(){ + int n; + cin >> n; + seive_of_ero(n); + for(int i = 0; i <= 500; i++){ + if(is_prime[i]) + cout << i << " " << endl; + } + +return 0; +} From 01b598ca125207cc54c1941ed07354e3bd07461f Mon Sep 17 00:00:00 2001 From: Kinjalk Date: Thu, 9 Feb 2023 17:42:35 +0530 Subject: [PATCH 0066/1894] Added solution for the concatenation string with unique chars problem --- ...h_concatenated_string_unique_characters.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Strings/max_length_concatenated_string_unique_characters.py diff --git a/Strings/max_length_concatenated_string_unique_characters.py b/Strings/max_length_concatenated_string_unique_characters.py new file mode 100644 index 00000000..5341745c --- /dev/null +++ b/Strings/max_length_concatenated_string_unique_characters.py @@ -0,0 +1,21 @@ +class Solution: + def maxLength(self, arr: List[str]) -> int: + + # [1] we should first throw away all strings with any + # duplicate characters; strings with all unique + # characters are the subsets of the alphabet, + # thus, can be stored using 'set' + unique = [] + for s in arr: + u = set(s) + if len(u) == len(s): unique.append(u) + + # [2] now start with an empty concatenation and iteratively + # increase its length by trying to add more strings + concat = [set()] + for u in unique: + for c in concat: + if not c & u: + concat.append(c | u) + + return max(len(cc) for cc in concat) \ No newline at end of file From 7f67f5f33bacba95c6f44be9ea2355fcb72e3087 Mon Sep 17 00:00:00 2001 From: Kinjalk Date: Thu, 9 Feb 2023 17:53:30 +0530 Subject: [PATCH 0067/1894] Adding question and sample IO --- ...h_concatenated_string_unique_characters.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Strings/max_length_concatenated_string_unique_characters.py b/Strings/max_length_concatenated_string_unique_characters.py index 5341745c..705401f9 100644 --- a/Strings/max_length_concatenated_string_unique_characters.py +++ b/Strings/max_length_concatenated_string_unique_characters.py @@ -1,3 +1,42 @@ +# Question -> + +# You are given an array of strings arr. A string s is formed by the concatenation +# of a subsequence of arr that has unique characters. + +# Return the maximum possible length of s. + +# A subsequence is an array that can be derived from another array +# by deleting some or no elements without changing the order of the remaining elements. + + +# Sample IO -> + +# Example 1: + +# Input: arr = ["un","iq","ue"] +# Output: 4 +# Explanation: All the valid concatenations are: +# - "" +# - "un" +# - "iq" +# - "ue" +# - "uniq" ("un" + "iq") +# - "ique" ("iq" + "ue") +# Maximum length is 4. +# Example 2: + +# Input: arr = ["cha","r","act","ers"] +# Output: 6 +# Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). +# Example 3: + +# Input: arr = ["abcdefghijklmnopqrstuvwxyz"] +# Output: 26 +# Explanation: The only string in arr has all 26 characters. + + +# Solution -> + class Solution: def maxLength(self, arr: List[str]) -> int: From 594dc11779bc3ff3815ffd1346be2432c78f3611 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Feb 2023 22:23:34 +0530 Subject: [PATCH 0068/1894] reorg folder structure and rename file --- .../{c++ => }/_len_of_concatenated_string_with_unique_chars.cpp | 0 ...of_well_formed_parentheses.cpp => well_formed_parentheses.cpp} | 0 Strings/{c++ => }/zigzag_conversion.cpp | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Strings/{c++ => }/_len_of_concatenated_string_with_unique_chars.cpp (100%) rename Strings/{c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp => well_formed_parentheses.cpp} (100%) rename Strings/{c++ => }/zigzag_conversion.cpp (100%) diff --git a/Strings/c++/_len_of_concatenated_string_with_unique_chars.cpp b/Strings/_len_of_concatenated_string_with_unique_chars.cpp similarity index 100% rename from Strings/c++/_len_of_concatenated_string_with_unique_chars.cpp rename to Strings/_len_of_concatenated_string_with_unique_chars.cpp diff --git a/Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp b/Strings/well_formed_parentheses.cpp similarity index 100% rename from Strings/c++/Write _a_function_to_generate_all_combinations_of_well_formed_parentheses.cpp rename to Strings/well_formed_parentheses.cpp diff --git a/Strings/c++/zigzag_conversion.cpp b/Strings/zigzag_conversion.cpp similarity index 100% rename from Strings/c++/zigzag_conversion.cpp rename to Strings/zigzag_conversion.cpp From 7773992f17d67cd35ac6ddd813ab9718c9438481 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Feb 2023 22:26:34 +0530 Subject: [PATCH 0069/1894] add first and fast position of element in sorted Array --- .../first_and_last_pos_of_element.cpp | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Binary_Search/first_and_last_pos_of_element.cpp diff --git a/Binary_Search/first_and_last_pos_of_element.cpp b/Binary_Search/first_and_last_pos_of_element.cpp new file mode 100644 index 00000000..52d33555 --- /dev/null +++ b/Binary_Search/first_and_last_pos_of_element.cpp @@ -0,0 +1,70 @@ +/* +Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. + +If target is not found in the array, return [-1, -1]. + +You must write an algorithm with O(log n) runtime complexity. + + + +Example 1: + +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] +Example 2: + +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] +Example 3: + +Input: nums = [], target = 0 +Output: [-1,-1] + + +Constraints: + +0 <= nums.length <= 105 +-109 <= nums[i] <= 109 +nums is a non-decreasing array. +-109 <= target <= 109 + +*/ +#include +class Solution { +public: + int get_index(vector& nums, int target, bool found){ + int ans = -1; + int start = 0, end = nums.size() - 1; + while(start <= end){ + int mid = start + (end - start) / 2; + if(nums[mid] == target){ + ans = mid; + if(found){ + end = mid - 1; // search in left part + } + else{ + start = mid + 1; // search in right part + } + } + else if(nums[mid] > target){ + end = mid - 1; + } + else{ + start = mid + 1; + } + } + return ans; + } + vector searchRange(vector& nums, int target) { + vector ans(2, -1); + int first = get_index(nums, target, true); + if(first == -1) + return ans; + int last = get_index(nums, target, false); + //ans.push_back(first); + //ans.push_back(last); + ans[0] = first; + ans[1] = last; + return ans; + } +}; \ No newline at end of file From 95f061c1389fbab8d0a01e4e237b3590c58adc27 Mon Sep 17 00:00:00 2001 From: uday510 Date: Thu, 9 Feb 2023 23:05:24 +0530 Subject: [PATCH 0070/1894] Add String Problems Solution --- Leetcode/reverse_words_in_string.java | 97 +++++++++++++++++++ .../reverse_words_in_string_algoexpect.java | 55 +++++++++++ 2 files changed, 152 insertions(+) create mode 100644 Leetcode/reverse_words_in_string.java create mode 100644 Leetcode/reverse_words_in_string_algoexpect.java diff --git a/Leetcode/reverse_words_in_string.java b/Leetcode/reverse_words_in_string.java new file mode 100644 index 00000000..496d2bde --- /dev/null +++ b/Leetcode/reverse_words_in_string.java @@ -0,0 +1,97 @@ +/** + * Given an input string s, reverse the order of the words. + * + * A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. + * + * Return a string of the words in reverse order concatenated by a single space. + * + * Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. + * + * + * + * Example 1: + * + * Input: s = "the sky is blue" + * Output: "blue is sky the" + * Example 2: + * + * Input: s = " hello world " + * Output: "world hello" + * Explanation: Your reversed string should not contain leading or trailing spaces. + */ + +package Strings; + +public class ReverseWordsInString { + public static void main(String[] args) { + String string = "the sky is blue"; + + String res = solve(string); + System.out.println(res); + } + public static String solve(String string) { + // O(N) time | O(N) - where N is the length of the array. + + //Convert String to String Builder + //and trim spaces at the same time + StringBuilder stringBuilder = trimSpaces(string); + + System.out.println(string); + + //reverse the whole word + reverse(stringBuilder, 0, stringBuilder.length() - 1); + System.out.println(stringBuilder); + + //reverse each word + reverseEachWord(stringBuilder); + System.out.println(stringBuilder); + + return stringBuilder.toString(); + } + + public static StringBuilder trimSpaces(String string) { + int leftIdx = 0, rightIdx = string.length() - 1; + + // remove leading spaces + while (leftIdx <= rightIdx && string.charAt(leftIdx) == ' ') ++leftIdx; + + // remove trailing spaces + while (leftIdx <= rightIdx && string.charAt(rightIdx) == ' ') --rightIdx; + + // reduce multiple spaces to single one + StringBuilder stringBuilder = new StringBuilder(); + while (leftIdx <= rightIdx) { + char currentChar = string.charAt(leftIdx); + + if (currentChar != ' ') stringBuilder.append(currentChar); + else if (stringBuilder.charAt(stringBuilder.length() - 1) != ' ') stringBuilder.append(currentChar); + + ++leftIdx; + } + return stringBuilder; + } + + public static void reverse(StringBuilder stringBuilder, int leftIdx, int rightIdx) { + while (leftIdx < rightIdx) { + char temp = stringBuilder.charAt(leftIdx); + stringBuilder.setCharAt(leftIdx++, stringBuilder.charAt(rightIdx)); + stringBuilder.setCharAt(rightIdx--, temp); + } + } + public static void reverseEachWord(StringBuilder stringBuilder) { + int len = stringBuilder.length(); + int startIdx = 0, endIdx = 0; + + while (startIdx < len) { + // go to the end of the word + while (endIdx < len && stringBuilder.charAt(endIdx) != ' ') ++endIdx; + // reverse the word + reverse(stringBuilder, startIdx, endIdx - 1); + // move to the next word + startIdx = endIdx + 1; + ++endIdx; + } + } + +} + diff --git a/Leetcode/reverse_words_in_string_algoexpect.java b/Leetcode/reverse_words_in_string_algoexpect.java new file mode 100644 index 00000000..60ca4a3c --- /dev/null +++ b/Leetcode/reverse_words_in_string_algoexpect.java @@ -0,0 +1,55 @@ +/** + * Reverse Words In String + * + * Write a function that takes in a string of words separated by one or more whitespaces and returns a string that has these words in reverse order. For example, given the string "tim is great", your function should return "great is tim". + * + * For this problem, a word can contain special characters, punctuation, and numbers. The words in the string will be separated by one or more whitespaces, and the reversed string must contain the same whitespaces as the original string. For example, given the string "whitespaces 4" you would be expected to return "4 whitespaces". + * + * Note that you're not allowed to to use any built-in split or reverse methods/functions. However, you are allowed to use a built-in join method/function. + * + * Also note that the input string isn't guaranteed to always contain words. + * Sample Input + * + * string = "AlgoExpert is the best!" + * + * Sample Output + * + * "best! the is AlgoExpert" + */ + +package Strings; + +import java.util.*; + +public class ReverseWordsInStringAlgoExpert { + public static void main(String[] args) { +// String string = "great! is Uday"; + String string = "the sky is blue"; + + String res = solve(string); + System.out.println(res); + } + public static String solve(String string) { + // O(N) time | O(N) space where N is the length of the string + ArrayList words = new ArrayList<>(); + int startOfWord = 0; // keeps track of first idx to + + for (int idx = 0; idx < string.length(); idx++) { + char character = string.charAt(idx); + + if (character == ' ') { + words.add(string.substring(startOfWord, idx)); + startOfWord = idx; + } else if (string.charAt(startOfWord) == ' ') { + words.add(" "); + startOfWord = idx; + } + } + + words.add(string.substring(startOfWord)); // last substring + + Collections.reverse(words); + System.out.println(words); + return String.join("", words); + } +} From 4bbf8dd327a6fb489951adaac00d80f8db041870 Mon Sep 17 00:00:00 2001 From: uday510 Date: Fri, 10 Feb 2023 02:32:54 +0530 Subject: [PATCH 0071/1894] Add String Problems Solution --- Leetcode/is_al_num.java | 76 ++++++++++++++++++++++++++++ Leetcode/longest_common_prefix.java | 72 ++++++++++++++++++++++++++ Leetcode/string_operations.java | 78 +++++++++++++++++++++++++++++ 3 files changed, 226 insertions(+) create mode 100644 Leetcode/is_al_num.java create mode 100644 Leetcode/longest_common_prefix.java create mode 100644 Leetcode/string_operations.java diff --git a/Leetcode/is_al_num.java b/Leetcode/is_al_num.java new file mode 100644 index 00000000..9e27b302 --- /dev/null +++ b/Leetcode/is_al_num.java @@ -0,0 +1,76 @@ +/** + * You are given a function isalpha() consisting of a character array A. + * + * Return 1 if all the characters of a character array are alphanumeric (a-z, A-Z, and 0-9) else, return 0. + * + * + * + * Problem Constraints + * 1 <= |A| <= 105 + * + * + * + * Input Format + * Only argument is a character array A. + * + * + * + * Output Format + * Return 1 if all the characters of the character array are alphanumeric (a-z, A-Z and 0-9), else return 0. + * + * + * + * Example Input + * Input 1: + * + * A = ['S', 'c', 'a', 'l', 'e', 'r', 'A', 'c', 'a', 'd', 'e', 'm', 'y', '2', '0', '2', '0'] + * Input 2: + * + * A = ['S', 'c', 'a', 'l', 'e', 'r', '#', '2', '0', '2', '0'] + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * 0 + * + * + * Example Explanation + * Explanation 1: + * + * All the characters are alphanumeric. + * Explanation 2: + * + * All the characters are NOT alphabets i.e ('#'). + */ +package Strings; + +public class IsAlNum { + public static void main(String[] args) { + char[] chars = {'S', 'c', 'a', 'l', 'e', 'r', 'A', 'c', 'a', 'd', 'e', 'm', 'y', '2', '0', '2', '0', '$'}; + + boolean res = solve(chars); + System.out.println(res); + } + public static boolean solve(char[] A) { + + // O(N) time | O(N) space + String string = new String(A); + + return string.matches("[a-zA-Z0-9]*"); + + // O(N) time | O(1) space +// for(Character x: A){ +// if(!Character.isLetterOrDigit(x)){ +// return true; +// } +// } +// return false; + + + } +} + diff --git a/Leetcode/longest_common_prefix.java b/Leetcode/longest_common_prefix.java new file mode 100644 index 00000000..552f52a7 --- /dev/null +++ b/Leetcode/longest_common_prefix.java @@ -0,0 +1,72 @@ +/** + * Given the array of strings A, you need to find the longest string S, which is the prefix of ALL the strings in the array. + * + * The longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2. + * + * Example: the longest common prefix of "abcdefgh" and "abcefgh" is "abc". + * + * + * + * Problem Constraints + * 0 <= sum of length of all strings <= 1000000 + * + * + * + * Input Format + * The only argument given is an array of strings A. + * + * + * + * Output Format + * Return the longest common prefix of all strings in A. + * + * + * + * Example Input + * Input 1: + * + * A = ["abcdefgh", "aefghijk", "abcefgh"] + * Input 2: + * + * A = ["abab", "ab", "abcd"]; + * + * + * Example Output + * Output 1: + * + * "a" + * Output 2: + * + * "ab" + * + * + * Example Explanation + * Explanation 1: + * + * Longest common prefix of all the strings is "a". + * Explanation 2: + * + * Longest common prefix of all the strings is "ab". + */ +package Strings; + +public class LongestCommonPrefix { + public static void main(String[] args) { + String[] strings = {"ab", "abab", "ab", "abcd"}; + + String res = solve(strings); + } + public static String solve(String[] strings) { + if (strings == null || strings.length == 0) return ""; + + for (int i = 0; i < strings[0].length(); i++) { + char currentChar = strings[0].charAt(i); + + for (int j = 1; j < strings.length; j++) { + if (i == strings[j].length() || strings[j].charAt(i) != currentChar) + return strings[0].substring(0, i); + } + } + return strings[0]; + } +} diff --git a/Leetcode/string_operations.java b/Leetcode/string_operations.java new file mode 100644 index 00000000..01a42793 --- /dev/null +++ b/Leetcode/string_operations.java @@ -0,0 +1,78 @@ +/** + * Akash likes playing with strings. One day he thought of applying following operations on the string in the given order: + * + * Concatenate the string with itself. + * Delete all the uppercase letters. + * Replace each vowel with '#'. + * You are given a string A of size N consisting of lowercase and uppercase alphabets. Return the resultant string after applying the above operations. + * + * NOTE: 'a' , 'e' , 'i' , 'o' , 'u' are defined as vowels. + * + * + * + * Problem Constraints + * + * 1<=N<=100000 + * + * + * Input Format + * + * First argument is a string A of size N. + * + * + * + * Output Format + * + * Return the resultant string. + * + * + * + * Example Input + * + * A="AbcaZeoB" + * + * + * + * Example Output + * + * "bc###bc###" + * + * + * + * Example Explanation + * + * First concatenate the string with itself so string A becomes "AbcaZeoBAbcaZeoB". + * Delete all the uppercase letters so string A becomes "bcaeobcaeo". + * Now replace vowel with '#'. + * A becomes "bc###bc###". + */ +package Strings; + +public class StringOperations { + public static void main(String[] args) { + String string = "AbcaZeoB"; + + String res = solve(string); + System.out.println(res); + } + public static String solve(String string) { + // O(N) time | O(N) space - where N is the length of string + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < string.length(); i++) { + char currentChar = string.charAt(i); + + if (currentChar >= 'a' && currentChar <= 'z') { + if (currentChar == 'a' || + currentChar == 'e' || + currentChar == 'i' || + currentChar == 'o' || + currentChar == 'u' + ) stringBuilder.append('#'); + else stringBuilder.append(string.charAt(i)); + } + } + + return stringBuilder.toString().concat(stringBuilder.toString()); + } +} From bfd6e8439c2024f0a400bd49d729825aeeac8c3e Mon Sep 17 00:00:00 2001 From: uday510 Date: Fri, 10 Feb 2023 09:18:55 +0530 Subject: [PATCH 0072/1894] Add String Problems Solution --- Leetcode/change_character.java | 77 ++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Leetcode/change_character.java diff --git a/Leetcode/change_character.java b/Leetcode/change_character.java new file mode 100644 index 00000000..28f05899 --- /dev/null +++ b/Leetcode/change_character.java @@ -0,0 +1,77 @@ +/** + * You are given a string A of size N consisting of lowercase alphabets. + * + * You can change at most B characters in the given string to any other lowercase alphabet such that the number of distinct characters in the string is minimized. + * + * Find the minimum number of distinct characters in the resulting string. + * + * + * + * Problem Constraints + * 1 <= N <= 100000 + * + * 0 <= B < N + * + * + * + * Input Format + * The first argument is a string A. + * + * The second argument is an integer B. + * + * + * + * Output Format + * Return an integer denoting the minimum number of distinct characters in the string. + * + * + * + * Example Input + * A = "abcabbccd" + * B = 3 + * + * + * + * Example Output + * 2 + * + * + * + * Example Explanation + * We can change both 'a' and one 'd' into 'b'.So the new string becomes "bbcbbbccb". + * So the minimum number of distinct character will be 2. + */ + +package Strings; + +import java.util.ArrayList; +import java.util.Collections; + +public class ChangeCharacter { + public static void main(String[] args) { + String string = "abcabbccd"; + int b = 3; + + int res = solve(string, b); + System.out.println(res); + } + public static int solve(String string, int b) { + + //count chars + int[] charsCount = new int[26]; + for (int i = 0; i < string.length(); i++) + ++charsCount[string.charAt(i) - 'a']; + + ArrayList arrayList = new ArrayList<>(); + for (int i = 0; i < 26; ++i) { + if (charsCount[i] > 0) arrayList.add(charsCount[i]); + } + + Collections.sort(arrayList); + for (int i = 0; i < arrayList.size(); ++i) { + b -= arrayList.get(i); + if (b < 0) return arrayList.size() - i; + } + return 1; + } +} From 65b75aee1d6f569bc157c4c03d18ab061747ef29 Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Fri, 10 Feb 2023 15:03:00 +0530 Subject: [PATCH 0073/1894] Added .exe --- .gitignore | 3 ++- Leetcode/Median_of_Two_Sorted_Arrays.cpp | 29 +++++++++++++++++------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index 8cd0df3a..d93b707e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .vscode -.idea \ No newline at end of file +.idea +*.exe \ No newline at end of file diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Leetcode/Median_of_Two_Sorted_Arrays.cpp index 9dcdc6ca..00ff5919 100644 --- a/Leetcode/Median_of_Two_Sorted_Arrays.cpp +++ b/Leetcode/Median_of_Two_Sorted_Arrays.cpp @@ -6,13 +6,27 @@ This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) Now, lets optimise it. - So, the sorted form of the given array is [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. Now suppose, on partitioning the above merged-sorted array in the mid-point, we get 5 elements on left and 5 elements on the right. - Now, we can get 5 elements by selecting {4 from left, 1 from right}, {3 from left, 2 from right}, {2 from left, 3 from right} and {1 from left, 4 from right}. - Lets analyse case-wise: - case 1: 4 from left, 1 from right - + So, the sorted form of the given array is arr = [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. + If we observe the sorted array carefully, then we notice that the 2 middle elements are arr[4] = 4 and arr[5] = 6, => arr[4] <= arr[5]. + + Thought process: + Now, since the arrays are sorted, so the binary searh may be able to solve the problem. + Observation 1: If we partition the sorted array arr into 2 halves, then for sure we know that there would be 5 elements on left half and 5 elements on right half. + Now, we can select 5 elements for right half from nums1 and nums2 combinedly and similarly the rest of the elements for the left half. + Example: + 1. left => [1, 3, 4, 7, 2], right => [10, 12, 3, 6, 15] + 2. left => [1, 3, 4, 2, 3], right => [7, 10, 12, 6, 15] + 3. left => [1, 3, 2, 3, 6], right => [4, 7, 10, 12, 15] + + Observation 2: All the elements on left half is lesser than all the elements on the right half. + Now, according to the observation, I have to check that all the elements in the left <= all the elements in the right. This can be done by just comparing the maximum of left half <= minimum of right half. + + Hence, the problem boils down to a searching problem; but how to identify the binary search approach?? + Suppose, we partition the element as example 1, then the max of left[] = 7 and min of right[] = 3, but according to the 2nd observation, it is not valid. So, in order to have a correct max in left, I need to reduce its value and consequestly, the min of right[] should be increased. That means, I have to move leftwards in nums1 to have a correct max value in left half. */ +// Leetcode link: https://leetcode.com/problems/median-of-two-sorted-arrays/ + #include class Solution { @@ -28,9 +42,8 @@ class Solution { while(lo <= hi){ int mid1 = (lo+hi)/2; // mid of nums1 int mid2 = (n1 + n2 + 1)/2 - mid1; - // why?? => suppose nums1[] is partitioned at index 3 => nums1[3] = 7. - std::pair maxleft, maxright; + std::pair maxleft, minright; maxleft.first = mid1 == 0 ? INT_MIN : nums1[mid1-1]; maxleft.second = mid2 == 0 ? INT_MIN : nums2[mid2-1]; @@ -68,7 +81,7 @@ int main(int argc, char const *argv[]) std::cin>>arr2[i]; } - const Solution sol = new Solution(); + Solution sol = Solution(); double res = sol.findMedianSortedArrays(arr1, arr2); std::cout< Date: Fri, 10 Feb 2023 15:08:23 +0530 Subject: [PATCH 0074/1894] Added .exe --- .gitignore | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index d93b707e..8cd0df3a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ .vscode -.idea -*.exe \ No newline at end of file +.idea \ No newline at end of file From 66e51e8a3a2a89b2583659ad9930dd0978c55e28 Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Fri, 10 Feb 2023 15:08:47 +0530 Subject: [PATCH 0075/1894] Added Code and Explanation --- Leetcode/Median_of_Two_Sorted_Arrays.cpp | 29 +++++++----------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Leetcode/Median_of_Two_Sorted_Arrays.cpp index 00ff5919..9dcdc6ca 100644 --- a/Leetcode/Median_of_Two_Sorted_Arrays.cpp +++ b/Leetcode/Median_of_Two_Sorted_Arrays.cpp @@ -6,26 +6,12 @@ This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) Now, lets optimise it. - So, the sorted form of the given array is arr = [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. - If we observe the sorted array carefully, then we notice that the 2 middle elements are arr[4] = 4 and arr[5] = 6, => arr[4] <= arr[5]. - - Thought process: - Now, since the arrays are sorted, so the binary searh may be able to solve the problem. - Observation 1: If we partition the sorted array arr into 2 halves, then for sure we know that there would be 5 elements on left half and 5 elements on right half. - Now, we can select 5 elements for right half from nums1 and nums2 combinedly and similarly the rest of the elements for the left half. - Example: - 1. left => [1, 3, 4, 7, 2], right => [10, 12, 3, 6, 15] - 2. left => [1, 3, 4, 2, 3], right => [7, 10, 12, 6, 15] - 3. left => [1, 3, 2, 3, 6], right => [4, 7, 10, 12, 15] - - Observation 2: All the elements on left half is lesser than all the elements on the right half. - Now, according to the observation, I have to check that all the elements in the left <= all the elements in the right. This can be done by just comparing the maximum of left half <= minimum of right half. - - Hence, the problem boils down to a searching problem; but how to identify the binary search approach?? - Suppose, we partition the element as example 1, then the max of left[] = 7 and min of right[] = 3, but according to the 2nd observation, it is not valid. So, in order to have a correct max in left, I need to reduce its value and consequestly, the min of right[] should be increased. That means, I have to move leftwards in nums1 to have a correct max value in left half. -*/ + So, the sorted form of the given array is [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. Now suppose, on partitioning the above merged-sorted array in the mid-point, we get 5 elements on left and 5 elements on the right. + Now, we can get 5 elements by selecting {4 from left, 1 from right}, {3 from left, 2 from right}, {2 from left, 3 from right} and {1 from left, 4 from right}. + Lets analyse case-wise: + case 1: 4 from left, 1 from right -// Leetcode link: https://leetcode.com/problems/median-of-two-sorted-arrays/ +*/ #include @@ -42,8 +28,9 @@ class Solution { while(lo <= hi){ int mid1 = (lo+hi)/2; // mid of nums1 int mid2 = (n1 + n2 + 1)/2 - mid1; + // why?? => suppose nums1[] is partitioned at index 3 => nums1[3] = 7. - std::pair maxleft, minright; + std::pair maxleft, maxright; maxleft.first = mid1 == 0 ? INT_MIN : nums1[mid1-1]; maxleft.second = mid2 == 0 ? INT_MIN : nums2[mid2-1]; @@ -81,7 +68,7 @@ int main(int argc, char const *argv[]) std::cin>>arr2[i]; } - Solution sol = Solution(); + const Solution sol = new Solution(); double res = sol.findMedianSortedArrays(arr1, arr2); std::cout< Date: Fri, 10 Feb 2023 20:31:26 +0530 Subject: [PATCH 0076/1894] "Committing " --- Binary_Search/FirstandLastPosition.java | 47 +++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Binary_Search/FirstandLastPosition.java diff --git a/Binary_Search/FirstandLastPosition.java b/Binary_Search/FirstandLastPosition.java new file mode 100644 index 00000000..3a7da6c8 --- /dev/null +++ b/Binary_Search/FirstandLastPosition.java @@ -0,0 +1,47 @@ +class FirstandLastPosition { + public int[] searchRange(int[] nums, int target) { + if(nums.length==0) return new int[]{-1,-1}; + int a=firstPos(nums, target); + int b=0; + if(a!=Integer.MAX_VALUE){ + b=lastPos(nums,target,a); + }else{ + return new int[]{-1,-1}; + } + return new int[]{a,b}; + } + private int firstPos(int[] arr,int target){ + int ans=Integer.MAX_VALUE,low=0,high=arr.length-1; + + while(low<=high){ + int mid=low+(high-low)/2; + + if(arr[mid]==target){ + ans=Math.min(ans,mid); + if(mid>0 && arr[mid-1]==target) low=mid-1; + high=mid-1; + }else if(arr[mid]>target){ + high=mid-1; + }else if(arr[mid]target){ + high=mid-1; + }else{ + low=mid+1; + } + } + return ans; + } +} From 93681d81f8f0d6cfa08dc28d5fac9838444d7e6d Mon Sep 17 00:00:00 2001 From: Ujjwal2421 Date: Fri, 10 Feb 2023 21:56:44 +0530 Subject: [PATCH 0077/1894] Added io --- Binary_Search/FirstandLastPosition.java | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Binary_Search/FirstandLastPosition.java b/Binary_Search/FirstandLastPosition.java index 3a7da6c8..ae3f09b1 100644 --- a/Binary_Search/FirstandLastPosition.java +++ b/Binary_Search/FirstandLastPosition.java @@ -1,3 +1,23 @@ +/* + Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value +If target is not found in the array, return [-1, -1]. + +You must write an algorithm with O(log n) runtime complexity. + +Example 1: + +Input: nums = [5,7,7,8,8,10], target = 8 +Output: [3,4] +Example 2: + +Input: nums = [5,7,7,8,8,10], target = 6 +Output: [-1,-1] + +How this Code Works? +The firstPos method will give the starting position of the target element. We will find the mid and check if the mid element is equals to the target we will check if previous element is equal to target or not if it is then place low to mid-1 if not just update the high to mid-1. Next condition is if the element is greater then target it means we have to search in the left side of array hence high=mid-1.And last condition if the element is less than the target do low=mid-1. If this method returns Integer.MAX_VALUE if means element is not present. Hence return {-1,-1} as answer. + +The lastPost method works same way as the above method. Passed extra paramter of low because it's now already clear that from where we have to start as we already got the first index. + */ class FirstandLastPosition { public int[] searchRange(int[] nums, int target) { if(nums.length==0) return new int[]{-1,-1}; @@ -42,6 +62,6 @@ private int lastPos(int[] arr,int target,int low){ low=mid+1; } } - return ans; - } + return ans; + } } From 71875edf96979230efd37bf0384a5a9aa7a92a0b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Feb 2023 12:03:29 +0530 Subject: [PATCH 0078/1894] reorg structure --- .gitignore | 3 ++- Math/{cpp => }/modular_expo_itera.cpp | 0 Math/{cpp => }/modular_expo_recursive.cpp | 0 Math/{cpp/Implement_pow(x, n).cpp => powXn.cpp} | 0 Math/{cpp => }/prime_factorization.cpp | 0 Math/{cpp => }/sieve_of_eratosthenes.cpp | 0 6 files changed, 2 insertions(+), 1 deletion(-) rename Math/{cpp => }/modular_expo_itera.cpp (100%) rename Math/{cpp => }/modular_expo_recursive.cpp (100%) rename Math/{cpp/Implement_pow(x, n).cpp => powXn.cpp} (100%) rename Math/{cpp => }/prime_factorization.cpp (100%) rename Math/{cpp => }/sieve_of_eratosthenes.cpp (100%) diff --git a/.gitignore b/.gitignore index 8cd0df3a..9049112d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .vscode -.idea \ No newline at end of file +.idea +.exe \ No newline at end of file diff --git a/Math/cpp/modular_expo_itera.cpp b/Math/modular_expo_itera.cpp similarity index 100% rename from Math/cpp/modular_expo_itera.cpp rename to Math/modular_expo_itera.cpp diff --git a/Math/cpp/modular_expo_recursive.cpp b/Math/modular_expo_recursive.cpp similarity index 100% rename from Math/cpp/modular_expo_recursive.cpp rename to Math/modular_expo_recursive.cpp diff --git a/Math/cpp/Implement_pow(x, n).cpp b/Math/powXn.cpp similarity index 100% rename from Math/cpp/Implement_pow(x, n).cpp rename to Math/powXn.cpp diff --git a/Math/cpp/prime_factorization.cpp b/Math/prime_factorization.cpp similarity index 100% rename from Math/cpp/prime_factorization.cpp rename to Math/prime_factorization.cpp diff --git a/Math/cpp/sieve_of_eratosthenes.cpp b/Math/sieve_of_eratosthenes.cpp similarity index 100% rename from Math/cpp/sieve_of_eratosthenes.cpp rename to Math/sieve_of_eratosthenes.cpp From 658ba2b99233d9ce7042604b898fc374f4c4201f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Feb 2023 12:08:10 +0530 Subject: [PATCH 0079/1894] rename files --- Arrays/{RemoveDuplicates.java => remove_duplicates.java} | 0 Arrays/{removeDuplicates.js => remove_duplicates.js} | 0 Arrays/{StockTrading.java => stock_trading.java} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Arrays/{RemoveDuplicates.java => remove_duplicates.java} (100%) rename Arrays/{removeDuplicates.js => remove_duplicates.js} (100%) rename Arrays/{StockTrading.java => stock_trading.java} (100%) diff --git a/Arrays/RemoveDuplicates.java b/Arrays/remove_duplicates.java similarity index 100% rename from Arrays/RemoveDuplicates.java rename to Arrays/remove_duplicates.java diff --git a/Arrays/removeDuplicates.js b/Arrays/remove_duplicates.js similarity index 100% rename from Arrays/removeDuplicates.js rename to Arrays/remove_duplicates.js diff --git a/Arrays/StockTrading.java b/Arrays/stock_trading.java similarity index 100% rename from Arrays/StockTrading.java rename to Arrays/stock_trading.java From 9624c0433b66b83cb2044c9e0a5c90d864cd46b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Feb 2023 12:13:17 +0530 Subject: [PATCH 0080/1894] rename folders --- {2D_Arrays => 2D Arrays}/2d_binary_search.cpp | 0 {2D_Arrays => 2D Arrays}/search_el.cpp | 0 .../CeilLetter.java | 0 .../CeilOfTarget.java | 0 .../FirstOccurence.java | 0 .../FirstandLastPosition.java | 0 .../FloorOfTarget.java | 0 .../IndexPosition.java | 0 .../PerfectSquare.java | 0 .../SquareRoot.java | 0 .../binary_search.py | 96 +++---- .../binary_search_iterative.go | 0 .../binary_search_recursive.go | 0 .../first_and_last_pos_of_element.cpp | 0 .../first_occurance.go | 0 .../last_occurance.go | 0 .../count_bits.go | 0 .../count_bits_test.go | 0 .../decimal_to_any_base.java | 0 .../find_good_days.java | 0 .../interesting_array.java | 0 .../mod_array.java | 0 .../number_of_1_bits.java | 0 .../parity_of_a_word.go | 0 .../setbits.cpp | 36 +-- .../single_number.java | 0 .../subarrays_with_bitwise_OR_1.java | 0 .../subarrays_with_bitwise_or.java | 0 .../climb_stairs.go | 0 .../edit_distance_dp.cpp | 104 ++++---- .../edit_distance_memoized.cpp | 86 +++---- .../edit_distance_recursive.cpp | 78 +++--- .../house_robber.cpp | 0 .../longest_common_subsequence_dp.cpp | 84 +++--- ...longest_common_subsequence_memoization.cpp | 92 +++---- .../longest_common_subsequence_recursive.cpp | 96 +++---- .../longest_increasing_subsequence.cpp | 72 +++--- .../min_cost_travel_in_a_grid.cpp | 104 ++++---- ...min_steps_to_reduce_a_number_to_one_dp.cpp | 86 +++---- ...eps_to_reduce_a_number_to_one_memoized.cpp | 78 +++--- .../rod_cutting_problem_dp.cpp | 68 ++--- .../rod_cutting_problem_memoized.cpp | 72 +++--- .../rod_cutting_problem_recursive.cpp | 66 ++--- .../trapping_rain_water.cpp | 0 .../wine_selling_problem_dp.cpp | 114 ++++----- .../wine_selling_problem_memoized.cpp | 82 +++--- .../wine_selling_problem_recursive.cpp | 70 ++--- .../linked_floyds_cycle_detection.cpp | 158 ++++++------ {Linked_List => Linked List}/linked_list.go | 0 .../linked_list_compute_midpoint.cpp | 122 ++++----- .../linked_list_dalete_at_tail.cpp | 118 ++++----- .../linked_list_delete_at_any_pos.cpp | 242 +++++++++--------- .../linked_list_delete_at_head.cpp | 88 +++---- .../linked_list_find_length.cpp | 86 +++---- .../linked_list_insert_at_any_pos.cpp | 150 +++++------ .../linked_list_insert_at_head.cpp | 66 ++--- .../linked_list_insert_at_tail.cpp | 84 +++--- .../linked_list_kth_node_from_end.cpp | 128 ++++----- .../linked_list_linear_search.cpp | 108 ++++---- .../linked_list_merge_k_sorted_lists.cpp | 196 +++++++------- ...nked_list_merge_two_sorted_linked_list.cpp | 152 +++++------ ...linked_list_mergesort_an_unsorted_list.cpp | 198 +++++++------- .../linked_list_odd_even.cpp | 126 ++++----- .../linked_list_recursive_search.cpp | 100 ++++---- .../linked_list_remove_dups.cpp | 180 ++++++------- .../linked_list_reverse.cpp | 120 ++++----- .../linked_list_reverse_recursive.cpp | 118 ++++----- .../linked_list_swap_nodes_in_pair.cpp | 114 ++++----- ...nked_list_swap_nodes_in_pair_iterative.cpp | 136 +++++----- .../linked_list_take_input.cpp | 92 +++---- ...ke_input_as_array_operator_overloading.cpp | 130 +++++----- ...d_list_take_input_operator_overloading.cpp | 138 +++++----- {Linked_List => Linked List}/sll.go | 0 .../sort_linked_list.cpp | 0 .../tempCodeRunnerFile.cpp | 2 +- .../bubble_sort_recursive.cpp | 66 ++--- .../check_permutations.cpp | 58 ++--- .../linear_search_string.cpp | 48 ++-- .../matrix_rotate_90_anti_clockwise.cpp | 70 ++--- .../matrix_rotate_90_clockwise.cpp | 70 ++--- .../matrix_search_in_sorted_mat.cpp | 72 +++--- .../matrix_spiral_print.cpp | 96 +++---- .../matrix_wave_print.cpp | 64 ++--- .../maximum_subarray.cpp | 60 ++--- .../maximum_subarray_cumulative.cpp | 70 ++--- .../maximum_subarray_kadanes.cpp | 42 +-- .../move_zeros.cpp | 54 ++-- .../printing_all_subarrays.cpp | 36 +-- .../rev_string.go | 36 +-- .../rotate_string.cpp | 52 ++-- .../set_bits.cpp | 32 +-- .../spiral_print.cpp | 88 +++---- .../tempCodeRunnerFile.cpp | 0 .../unique_occurences.cpp | 72 +++--- ...-substring-without-repeating-characters.go | 0 95 files changed, 2861 insertions(+), 2861 deletions(-) rename {2D_Arrays => 2D Arrays}/2d_binary_search.cpp (100%) rename {2D_Arrays => 2D Arrays}/search_el.cpp (100%) rename {Binary_Search => Binary Search}/CeilLetter.java (100%) rename {Binary_Search => Binary Search}/CeilOfTarget.java (100%) rename {Binary_Search => Binary Search}/FirstOccurence.java (100%) rename {Binary_Search => Binary Search}/FirstandLastPosition.java (100%) rename {Binary_Search => Binary Search}/FloorOfTarget.java (100%) rename {Binary_Search => Binary Search}/IndexPosition.java (100%) rename {Binary_Search => Binary Search}/PerfectSquare.java (100%) rename {Binary_Search => Binary Search}/SquareRoot.java (100%) rename {Binary_Search => Binary Search}/binary_search.py (97%) rename {Binary_Search => Binary Search}/binary_search_iterative.go (100%) rename {Binary_Search => Binary Search}/binary_search_recursive.go (100%) rename {Binary_Search => Binary Search}/first_and_last_pos_of_element.cpp (100%) rename {Binary_Search => Binary Search}/first_occurance.go (100%) rename {Binary_Search => Binary Search}/last_occurance.go (100%) rename {Bit_Manipulation => Bit Manipulation}/count_bits.go (100%) rename {Bit_Manipulation => Bit Manipulation}/count_bits_test.go (100%) rename {Bit_Manipulation => Bit Manipulation}/decimal_to_any_base.java (100%) rename {Bit_Manipulation => Bit Manipulation}/find_good_days.java (100%) rename {Bit_Manipulation => Bit Manipulation}/interesting_array.java (100%) rename {Bit_Manipulation => Bit Manipulation}/mod_array.java (100%) rename {Bit_Manipulation => Bit Manipulation}/number_of_1_bits.java (100%) rename {Bit_Manipulation => Bit Manipulation}/parity_of_a_word.go (100%) rename {Bit_Manipulation => Bit Manipulation}/setbits.cpp (96%) rename {Bit_Manipulation => Bit Manipulation}/single_number.java (100%) rename {Bit_Manipulation => Bit Manipulation}/subarrays_with_bitwise_OR_1.java (100%) rename {Bit_Manipulation => Bit Manipulation}/subarrays_with_bitwise_or.java (100%) rename {Dynamic_Programming => Dynamic Programming}/climb_stairs.go (100%) rename {Dynamic_Programming => Dynamic Programming}/edit_distance_dp.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/edit_distance_memoized.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/edit_distance_recursive.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/house_robber.cpp (100%) rename {Dynamic_Programming => Dynamic Programming}/longest_common_subsequence_dp.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/longest_common_subsequence_memoization.cpp (97%) rename {Dynamic_Programming => Dynamic Programming}/longest_common_subsequence_recursive.cpp (97%) rename {Dynamic_Programming => Dynamic Programming}/longest_increasing_subsequence.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/min_cost_travel_in_a_grid.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/min_steps_to_reduce_a_number_to_one_dp.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/min_steps_to_reduce_a_number_to_one_memoized.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/rod_cutting_problem_dp.cpp (97%) rename {Dynamic_Programming => Dynamic Programming}/rod_cutting_problem_memoized.cpp (97%) rename {Dynamic_Programming => Dynamic Programming}/rod_cutting_problem_recursive.cpp (97%) rename {Dynamic_Programming => Dynamic Programming}/trapping_rain_water.cpp (100%) rename {Dynamic_Programming => Dynamic Programming}/wine_selling_problem_dp.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/wine_selling_problem_memoized.cpp (96%) rename {Dynamic_Programming => Dynamic Programming}/wine_selling_problem_recursive.cpp (96%) rename {Linked_List => Linked List}/linked_floyds_cycle_detection.cpp (96%) rename {Linked_List => Linked List}/linked_list.go (100%) rename {Linked_List => Linked List}/linked_list_compute_midpoint.cpp (96%) rename {Linked_List => Linked List}/linked_list_dalete_at_tail.cpp (95%) rename {Linked_List => Linked List}/linked_list_delete_at_any_pos.cpp (95%) rename {Linked_List => Linked List}/linked_list_delete_at_head.cpp (95%) rename {Linked_List => Linked List}/linked_list_find_length.cpp (95%) rename {Linked_List => Linked List}/linked_list_insert_at_any_pos.cpp (95%) rename {Linked_List => Linked List}/linked_list_insert_at_head.cpp (95%) rename {Linked_List => Linked List}/linked_list_insert_at_tail.cpp (95%) rename {Linked_List => Linked List}/linked_list_kth_node_from_end.cpp (95%) rename {Linked_List => Linked List}/linked_list_linear_search.cpp (95%) rename {Linked_List => Linked List}/linked_list_merge_k_sorted_lists.cpp (95%) rename {Linked_List => Linked List}/linked_list_merge_two_sorted_linked_list.cpp (95%) rename {Linked_List => Linked List}/linked_list_mergesort_an_unsorted_list.cpp (95%) rename {Linked_List => Linked List}/linked_list_odd_even.cpp (95%) rename {Linked_List => Linked List}/linked_list_recursive_search.cpp (95%) rename {Linked_List => Linked List}/linked_list_remove_dups.cpp (95%) rename {Linked_List => Linked List}/linked_list_reverse.cpp (95%) rename {Linked_List => Linked List}/linked_list_reverse_recursive.cpp (95%) rename {Linked_List => Linked List}/linked_list_swap_nodes_in_pair.cpp (95%) rename {Linked_List => Linked List}/linked_list_swap_nodes_in_pair_iterative.cpp (95%) rename {Linked_List => Linked List}/linked_list_take_input.cpp (95%) rename {Linked_List => Linked List}/linked_list_take_input_as_array_operator_overloading.cpp (95%) rename {Linked_List => Linked List}/linked_list_take_input_operator_overloading.cpp (95%) rename {Linked_List => Linked List}/sll.go (100%) rename {Linked_List => Linked List}/sort_linked_list.cpp (100%) rename {Linked_List => Linked List}/tempCodeRunnerFile.cpp (96%) rename {Random_Problems => Random Problems}/bubble_sort_recursive.cpp (97%) rename {Random_Problems => Random Problems}/check_permutations.cpp (96%) rename {Random_Problems => Random Problems}/linear_search_string.cpp (95%) rename {Random_Problems => Random Problems}/matrix_rotate_90_anti_clockwise.cpp (96%) rename {Random_Problems => Random Problems}/matrix_rotate_90_clockwise.cpp (96%) rename {Random_Problems => Random Problems}/matrix_search_in_sorted_mat.cpp (96%) rename {Random_Problems => Random Problems}/matrix_spiral_print.cpp (96%) rename {Random_Problems => Random Problems}/matrix_wave_print.cpp (95%) rename {Random_Problems => Random Problems}/maximum_subarray.cpp (96%) rename {Random_Problems => Random Problems}/maximum_subarray_cumulative.cpp (96%) rename {Random_Problems => Random Problems}/maximum_subarray_kadanes.cpp (97%) rename {Random_Problems => Random Problems}/move_zeros.cpp (95%) rename {Random_Problems => Random Problems}/printing_all_subarrays.cpp (95%) rename {Random_Problems => Random Problems}/rev_string.go (94%) rename {Random_Problems => Random Problems}/rotate_string.cpp (94%) rename {Random_Problems => Random Problems}/set_bits.cpp (96%) rename {Random_Problems => Random Problems}/spiral_print.cpp (96%) rename {Random_Problems => Random Problems}/tempCodeRunnerFile.cpp (100%) rename {Random_Problems => Random Problems}/unique_occurences.cpp (96%) rename {Sliding_Window => Sliding Window}/longest-substring-without-repeating-characters.go (100%) diff --git a/2D_Arrays/2d_binary_search.cpp b/2D Arrays/2d_binary_search.cpp similarity index 100% rename from 2D_Arrays/2d_binary_search.cpp rename to 2D Arrays/2d_binary_search.cpp diff --git a/2D_Arrays/search_el.cpp b/2D Arrays/search_el.cpp similarity index 100% rename from 2D_Arrays/search_el.cpp rename to 2D Arrays/search_el.cpp diff --git a/Binary_Search/CeilLetter.java b/Binary Search/CeilLetter.java similarity index 100% rename from Binary_Search/CeilLetter.java rename to Binary Search/CeilLetter.java diff --git a/Binary_Search/CeilOfTarget.java b/Binary Search/CeilOfTarget.java similarity index 100% rename from Binary_Search/CeilOfTarget.java rename to Binary Search/CeilOfTarget.java diff --git a/Binary_Search/FirstOccurence.java b/Binary Search/FirstOccurence.java similarity index 100% rename from Binary_Search/FirstOccurence.java rename to Binary Search/FirstOccurence.java diff --git a/Binary_Search/FirstandLastPosition.java b/Binary Search/FirstandLastPosition.java similarity index 100% rename from Binary_Search/FirstandLastPosition.java rename to Binary Search/FirstandLastPosition.java diff --git a/Binary_Search/FloorOfTarget.java b/Binary Search/FloorOfTarget.java similarity index 100% rename from Binary_Search/FloorOfTarget.java rename to Binary Search/FloorOfTarget.java diff --git a/Binary_Search/IndexPosition.java b/Binary Search/IndexPosition.java similarity index 100% rename from Binary_Search/IndexPosition.java rename to Binary Search/IndexPosition.java diff --git a/Binary_Search/PerfectSquare.java b/Binary Search/PerfectSquare.java similarity index 100% rename from Binary_Search/PerfectSquare.java rename to Binary Search/PerfectSquare.java diff --git a/Binary_Search/SquareRoot.java b/Binary Search/SquareRoot.java similarity index 100% rename from Binary_Search/SquareRoot.java rename to Binary Search/SquareRoot.java diff --git a/Binary_Search/binary_search.py b/Binary Search/binary_search.py similarity index 97% rename from Binary_Search/binary_search.py rename to Binary Search/binary_search.py index 8f3a5daf..a0ba8c7a 100644 --- a/Binary_Search/binary_search.py +++ b/Binary Search/binary_search.py @@ -1,48 +1,48 @@ -""" - Intuition: - If you have to guess a magic number from 1-100, the best first attempt would be to guess '50' - or in other words, the middle. If I tell you that the magic number is higher, - you now don't need to consider all numbers 1-50, - and if it is lower you wouldn't need to consider numbers 50-100!! - - In Binary Search, we follow the same idea, - 1. Compar the target with the middle element. - 2. If the target is higher, then the target can only lie in the right (greater) subarray. We re-calculate mid and repeat step 1. - 3. If the target is lower, the target can only lie in the left (lower) half. We re-calculate mid and repeat step 1. - - Binary search can only operate on a sorted array. - Further reading: https://en.wikipedia.org/wiki/Binary_search_algorithm -""" - - - - -import math - -def binary_search(lst, target): - if not lst: - return -1 - lo = 0 - hi = len(lst)-1 - - while lo <= hi: - mid = math.floor(lo + (hi - lo) / 2) # Find mid. math.floor is used to round floats down. - if lst[mid] < target: # Element in mid is lower than target. - lo = mid + 1 # Our low (start) becomes the element after mid. - elif lst[mid] > target: # Element in mid is higher than target. - hi = mid - 1 # Our high (end) becomes the element before mid. - elif lst[mid] == target: - print(f"Found {target} at index {mid}.") - return mid - print(f"Target {target} not found.") - return -1 - - -arr = [10, 20, 30, 50, 60, 80, 110, 130, 140, 170] -binary_search(arr, 80) -binary_search(arr, 10) -binary_search(arr, 110) -binary_search(arr, 20) -binary_search(arr, 140) -binary_search(arr, 2) -binary_search(arr, 1) +""" + Intuition: + If you have to guess a magic number from 1-100, the best first attempt would be to guess '50' + or in other words, the middle. If I tell you that the magic number is higher, + you now don't need to consider all numbers 1-50, + and if it is lower you wouldn't need to consider numbers 50-100!! + + In Binary Search, we follow the same idea, + 1. Compar the target with the middle element. + 2. If the target is higher, then the target can only lie in the right (greater) subarray. We re-calculate mid and repeat step 1. + 3. If the target is lower, the target can only lie in the left (lower) half. We re-calculate mid and repeat step 1. + + Binary search can only operate on a sorted array. + Further reading: https://en.wikipedia.org/wiki/Binary_search_algorithm +""" + + + + +import math + +def binary_search(lst, target): + if not lst: + return -1 + lo = 0 + hi = len(lst)-1 + + while lo <= hi: + mid = math.floor(lo + (hi - lo) / 2) # Find mid. math.floor is used to round floats down. + if lst[mid] < target: # Element in mid is lower than target. + lo = mid + 1 # Our low (start) becomes the element after mid. + elif lst[mid] > target: # Element in mid is higher than target. + hi = mid - 1 # Our high (end) becomes the element before mid. + elif lst[mid] == target: + print(f"Found {target} at index {mid}.") + return mid + print(f"Target {target} not found.") + return -1 + + +arr = [10, 20, 30, 50, 60, 80, 110, 130, 140, 170] +binary_search(arr, 80) +binary_search(arr, 10) +binary_search(arr, 110) +binary_search(arr, 20) +binary_search(arr, 140) +binary_search(arr, 2) +binary_search(arr, 1) diff --git a/Binary_Search/binary_search_iterative.go b/Binary Search/binary_search_iterative.go similarity index 100% rename from Binary_Search/binary_search_iterative.go rename to Binary Search/binary_search_iterative.go diff --git a/Binary_Search/binary_search_recursive.go b/Binary Search/binary_search_recursive.go similarity index 100% rename from Binary_Search/binary_search_recursive.go rename to Binary Search/binary_search_recursive.go diff --git a/Binary_Search/first_and_last_pos_of_element.cpp b/Binary Search/first_and_last_pos_of_element.cpp similarity index 100% rename from Binary_Search/first_and_last_pos_of_element.cpp rename to Binary Search/first_and_last_pos_of_element.cpp diff --git a/Binary_Search/first_occurance.go b/Binary Search/first_occurance.go similarity index 100% rename from Binary_Search/first_occurance.go rename to Binary Search/first_occurance.go diff --git a/Binary_Search/last_occurance.go b/Binary Search/last_occurance.go similarity index 100% rename from Binary_Search/last_occurance.go rename to Binary Search/last_occurance.go diff --git a/Bit_Manipulation/count_bits.go b/Bit Manipulation/count_bits.go similarity index 100% rename from Bit_Manipulation/count_bits.go rename to Bit Manipulation/count_bits.go diff --git a/Bit_Manipulation/count_bits_test.go b/Bit Manipulation/count_bits_test.go similarity index 100% rename from Bit_Manipulation/count_bits_test.go rename to Bit Manipulation/count_bits_test.go diff --git a/Bit_Manipulation/decimal_to_any_base.java b/Bit Manipulation/decimal_to_any_base.java similarity index 100% rename from Bit_Manipulation/decimal_to_any_base.java rename to Bit Manipulation/decimal_to_any_base.java diff --git a/Bit_Manipulation/find_good_days.java b/Bit Manipulation/find_good_days.java similarity index 100% rename from Bit_Manipulation/find_good_days.java rename to Bit Manipulation/find_good_days.java diff --git a/Bit_Manipulation/interesting_array.java b/Bit Manipulation/interesting_array.java similarity index 100% rename from Bit_Manipulation/interesting_array.java rename to Bit Manipulation/interesting_array.java diff --git a/Bit_Manipulation/mod_array.java b/Bit Manipulation/mod_array.java similarity index 100% rename from Bit_Manipulation/mod_array.java rename to Bit Manipulation/mod_array.java diff --git a/Bit_Manipulation/number_of_1_bits.java b/Bit Manipulation/number_of_1_bits.java similarity index 100% rename from Bit_Manipulation/number_of_1_bits.java rename to Bit Manipulation/number_of_1_bits.java diff --git a/Bit_Manipulation/parity_of_a_word.go b/Bit Manipulation/parity_of_a_word.go similarity index 100% rename from Bit_Manipulation/parity_of_a_word.go rename to Bit Manipulation/parity_of_a_word.go diff --git a/Bit_Manipulation/setbits.cpp b/Bit Manipulation/setbits.cpp similarity index 96% rename from Bit_Manipulation/setbits.cpp rename to Bit Manipulation/setbits.cpp index edc23c8a..5b7ed619 100644 --- a/Bit_Manipulation/setbits.cpp +++ b/Bit Manipulation/setbits.cpp @@ -1,18 +1,18 @@ -// Program to count the number of bits that are set to 1 in an integer -// The following program tests bits one at a time starting with the least-significant bit. -// Since we perform O(1) computation per bit, the time complexity is O(n) where n is number of bits in the integer -// Best case time complexity is O(1), if the input io 0 -#include -using namespace std; -int find_set_bits(int n){ - int set_bits = 0; - while(n){ - set_bits += (n & 1); - n >>= 1; - } - return set_bits; -} -int main(){ - cout << find_set_bits(4) << endl; - return 0; -} +// Program to count the number of bits that are set to 1 in an integer +// The following program tests bits one at a time starting with the least-significant bit. +// Since we perform O(1) computation per bit, the time complexity is O(n) where n is number of bits in the integer +// Best case time complexity is O(1), if the input io 0 +#include +using namespace std; +int find_set_bits(int n){ + int set_bits = 0; + while(n){ + set_bits += (n & 1); + n >>= 1; + } + return set_bits; +} +int main(){ + cout << find_set_bits(4) << endl; + return 0; +} diff --git a/Bit_Manipulation/single_number.java b/Bit Manipulation/single_number.java similarity index 100% rename from Bit_Manipulation/single_number.java rename to Bit Manipulation/single_number.java diff --git a/Bit_Manipulation/subarrays_with_bitwise_OR_1.java b/Bit Manipulation/subarrays_with_bitwise_OR_1.java similarity index 100% rename from Bit_Manipulation/subarrays_with_bitwise_OR_1.java rename to Bit Manipulation/subarrays_with_bitwise_OR_1.java diff --git a/Bit_Manipulation/subarrays_with_bitwise_or.java b/Bit Manipulation/subarrays_with_bitwise_or.java similarity index 100% rename from Bit_Manipulation/subarrays_with_bitwise_or.java rename to Bit Manipulation/subarrays_with_bitwise_or.java diff --git a/Dynamic_Programming/climb_stairs.go b/Dynamic Programming/climb_stairs.go similarity index 100% rename from Dynamic_Programming/climb_stairs.go rename to Dynamic Programming/climb_stairs.go diff --git a/Dynamic_Programming/edit_distance_dp.cpp b/Dynamic Programming/edit_distance_dp.cpp similarity index 96% rename from Dynamic_Programming/edit_distance_dp.cpp rename to Dynamic Programming/edit_distance_dp.cpp index 9016c152..f6ba8eca 100644 --- a/Dynamic_Programming/edit_distance_dp.cpp +++ b/Dynamic Programming/edit_distance_dp.cpp @@ -1,52 +1,52 @@ -/* - Given two strings str1 and str2 and following three operations that can performed on str1. - 1) Insert - 2) Remove - 3) Replace - Find minimum number of operations required to convert ‘str1’ into ‘str2’. - For example if input strings are CAT AND CAR the edit distance is 1. - - Input : s1 : saturday s2 : sunday - Output : 3 -*/ -// Dynamic Programming Solution : TC O(n^2) -// Porgram Author : Abhisek Kumar Gupta -#include -using namespace std; -int find_edit_distance(string s1, string s2, int l1, int l2){ - int dp[100][100] = {}; - for(int i = 0; i <= l1; i++){ - dp[i][0] = i; - } - for(int i = 0; i <= l2; i++){ - dp[0][i] = i; - } - for(int i = 1; i <= l1; i++){ - for(int j = 1; j <= l2; j++){ - if(s1[i] == s2[j]) - dp[i][j] = dp[i - 1][j - 1]; - else{ - int del = dp[i][j - 1]; - int replace = dp[i - 1][j - 1]; - int insert = dp[i - 1][j]; - dp[i][j] = min(del, min(replace, insert)) + 1; - } - } - } - for(int i = 0; i <= l1; i++){ - for(int j = 0; j <= l2; j++){ - cout << setw(5) < +using namespace std; +int find_edit_distance(string s1, string s2, int l1, int l2){ + int dp[100][100] = {}; + for(int i = 0; i <= l1; i++){ + dp[i][0] = i; + } + for(int i = 0; i <= l2; i++){ + dp[0][i] = i; + } + for(int i = 1; i <= l1; i++){ + for(int j = 1; j <= l2; j++){ + if(s1[i] == s2[j]) + dp[i][j] = dp[i - 1][j - 1]; + else{ + int del = dp[i][j - 1]; + int replace = dp[i - 1][j - 1]; + int insert = dp[i - 1][j]; + dp[i][j] = min(del, min(replace, insert)) + 1; + } + } + } + for(int i = 0; i <= l1; i++){ + for(int j = 0; j <= l2; j++){ + cout << setw(5) < -using namespace std; -int calls = 0; -int memoize[1009][1009]; -int find_edit_distance(string s1, string s2, int l1, int l2){ - calls++; - if(l1 == 0) - return l2; - if(l2 == 0) - return l1; - if(memoize[l1][l2] != -1) return memoize[l1][l2]; - if(s1[l1] == s2[l2]){ - return find_edit_distance(s1, s2, l1 - 1, l2 - 1); - } - int del = find_edit_distance(s1, s2, l1, l2 - 1); - int replace = find_edit_distance(s1, s2, l1 - 1, l2 - 1); - int insert = find_edit_distance(s1, s2, l1 - 1, l2); - memoize[l1][l2] = min (del, min(replace, insert)) + 1; - return min (del, min(replace, insert)) + 1; -} -int main(){ - memset(memoize, -1, sizeof(memoize)); - string s1 = "abhisek"; - string s2 = "tsunade"; - int l1 = s1.length() - 1; - int l2 = s2.length() - 1; - int result = find_edit_distance(s1, s2, l1, l2); - cout << result; - cout << "\n" << calls; - return 0; +/* + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Memoized Solution : TC O(n^2) +// Porgram Author : Abhisek Kumar Gupta +#include +using namespace std; +int calls = 0; +int memoize[1009][1009]; +int find_edit_distance(string s1, string s2, int l1, int l2){ + calls++; + if(l1 == 0) + return l2; + if(l2 == 0) + return l1; + if(memoize[l1][l2] != -1) return memoize[l1][l2]; + if(s1[l1] == s2[l2]){ + return find_edit_distance(s1, s2, l1 - 1, l2 - 1); + } + int del = find_edit_distance(s1, s2, l1, l2 - 1); + int replace = find_edit_distance(s1, s2, l1 - 1, l2 - 1); + int insert = find_edit_distance(s1, s2, l1 - 1, l2); + memoize[l1][l2] = min (del, min(replace, insert)) + 1; + return min (del, min(replace, insert)) + 1; +} +int main(){ + memset(memoize, -1, sizeof(memoize)); + string s1 = "abhisek"; + string s2 = "tsunade"; + int l1 = s1.length() - 1; + int l2 = s2.length() - 1; + int result = find_edit_distance(s1, s2, l1, l2); + cout << result; + cout << "\n" << calls; + return 0; } \ No newline at end of file diff --git a/Dynamic_Programming/edit_distance_recursive.cpp b/Dynamic Programming/edit_distance_recursive.cpp similarity index 96% rename from Dynamic_Programming/edit_distance_recursive.cpp rename to Dynamic Programming/edit_distance_recursive.cpp index a5c8c62b..260cd7b0 100644 --- a/Dynamic_Programming/edit_distance_recursive.cpp +++ b/Dynamic Programming/edit_distance_recursive.cpp @@ -1,40 +1,40 @@ -/* - Given two strings str1 and str2 and following three operations that can performed on str1. - 1) Insert - 2) Remove - 3) Replace - Find minimum number of operations required to convert ‘str1’ into ‘str2’. - For example if input strings are CAT AND CAR the edit distance is 1. - - Input : s1 : saturday s2 : sunday - Output : 3 -*/ -// Recursive Solution : TC Exponential -// Porgram Author : Abhisek Kumar Gupta -#include -using namespace std; -int calls = 0; -int find_edit_distance(string s1, string s2, int l1, int l2){ - calls++; - if(l1 == 0) - return l2; - if(l2 == 0) - return l1; - if(s1[l1] == s2[l2]){ - return find_edit_distance(s1, s2, l1 - 1, l2 - 1); - } - int del = find_edit_distance(s1, s2, l1, l2 - 1); - int replace = find_edit_distance(s1, s2, l1 - 1, l2 - 1); - int insert = find_edit_distance(s1, s2, l1 - 1, l2); - return min (del, min(replace, insert)) + 1; -} -int main(){ - string s1 = "abhisek"; - string s2 = "tsunade"; - int l1 = s1.length() - 1; - int l2 = s2.length() - 1; - int result = find_edit_distance(s1, s2, l1, l2); - cout << result; - cout << "\n" << calls; - return 0; +/* + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Recursive Solution : TC Exponential +// Porgram Author : Abhisek Kumar Gupta +#include +using namespace std; +int calls = 0; +int find_edit_distance(string s1, string s2, int l1, int l2){ + calls++; + if(l1 == 0) + return l2; + if(l2 == 0) + return l1; + if(s1[l1] == s2[l2]){ + return find_edit_distance(s1, s2, l1 - 1, l2 - 1); + } + int del = find_edit_distance(s1, s2, l1, l2 - 1); + int replace = find_edit_distance(s1, s2, l1 - 1, l2 - 1); + int insert = find_edit_distance(s1, s2, l1 - 1, l2); + return min (del, min(replace, insert)) + 1; +} +int main(){ + string s1 = "abhisek"; + string s2 = "tsunade"; + int l1 = s1.length() - 1; + int l2 = s2.length() - 1; + int result = find_edit_distance(s1, s2, l1, l2); + cout << result; + cout << "\n" << calls; + return 0; } \ No newline at end of file diff --git a/Dynamic_Programming/house_robber.cpp b/Dynamic Programming/house_robber.cpp similarity index 100% rename from Dynamic_Programming/house_robber.cpp rename to Dynamic Programming/house_robber.cpp diff --git a/Dynamic_Programming/longest_common_subsequence_dp.cpp b/Dynamic Programming/longest_common_subsequence_dp.cpp similarity index 96% rename from Dynamic_Programming/longest_common_subsequence_dp.cpp rename to Dynamic Programming/longest_common_subsequence_dp.cpp index 800d39bb..94bc986a 100644 --- a/Dynamic_Programming/longest_common_subsequence_dp.cpp +++ b/Dynamic Programming/longest_common_subsequence_dp.cpp @@ -1,43 +1,43 @@ -// DP : Find Longest Common Subsequence of two string -// Program Author : Abhisek Kumar Gupta -#include - -using namespace std; -const int maxi = 10000; -int find_longest_common_subsequence(string a, string b, int n, int m, int dp[][maxi]){ - for(int i = 0; i <= n; i++){ - dp[i][0] = 0; - } - for(int i = 0; i <= m; i++){ - dp[0][i] = 0; - } - // dp solution builds the table of LCS of substrings and starts - // computing the length building on the final solution - // we place one string along row and one along the column - for(int i = 1; i <= n; i++){ - for(int j = 1; j <= m; j++){ - // populating table in row-wise order - if(a[i - 1] == b[j - 1]){ - dp[i][j] = dp[i - 1][j - 1] + 1; - } - else{ - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); - } - } - } - return dp[m][n]; -} -int main(){ - string a = "DABCEFIHKST"; - string b = "DCEFKAAAQST"; - int n = a.length(); - int m = b.length(); - int dp[n+1][maxi]; - memset(dp, -1, sizeof(dp)); - int result = find_longest_common_subsequence(a, b, n, m, dp); - cout << result; - return 0; -} -// Time complexity O(N * M) improvement over both -// Recursion and memoization +// DP : Find Longest Common Subsequence of two string +// Program Author : Abhisek Kumar Gupta +#include + +using namespace std; +const int maxi = 10000; +int find_longest_common_subsequence(string a, string b, int n, int m, int dp[][maxi]){ + for(int i = 0; i <= n; i++){ + dp[i][0] = 0; + } + for(int i = 0; i <= m; i++){ + dp[0][i] = 0; + } + // dp solution builds the table of LCS of substrings and starts + // computing the length building on the final solution + // we place one string along row and one along the column + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m; j++){ + // populating table in row-wise order + if(a[i - 1] == b[j - 1]){ + dp[i][j] = dp[i - 1][j - 1] + 1; + } + else{ + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[m][n]; +} +int main(){ + string a = "DABCEFIHKST"; + string b = "DCEFKAAAQST"; + int n = a.length(); + int m = b.length(); + int dp[n+1][maxi]; + memset(dp, -1, sizeof(dp)); + int result = find_longest_common_subsequence(a, b, n, m, dp); + cout << result; + return 0; +} +// Time complexity O(N * M) improvement over both +// Recursion and memoization // Space complexity O(N * M) \ No newline at end of file diff --git a/Dynamic_Programming/longest_common_subsequence_memoization.cpp b/Dynamic Programming/longest_common_subsequence_memoization.cpp similarity index 97% rename from Dynamic_Programming/longest_common_subsequence_memoization.cpp rename to Dynamic Programming/longest_common_subsequence_memoization.cpp index dbfc4c1d..39bd7f76 100644 --- a/Dynamic_Programming/longest_common_subsequence_memoization.cpp +++ b/Dynamic Programming/longest_common_subsequence_memoization.cpp @@ -1,47 +1,47 @@ -// Memoization : Find Longest Common Subsequence of two string -// Program Author : Abhisek Kumar Gupta -/* - To avoid computation of subproblem many times we use memoization - here we take 2D array of size n*m memoization[n][m] - when length of lcs of first i characters of a and j characters of b is - computed for first time it is stored in cell memoization[i][j] - if function is called with n = i and m = j then LCS is not computed from scratch - and stored value is returned from table -*/ -#include -using namespace std; -const int maxi = 10000; -int get_max(int x, int y){ - return (x > y) ? x : y; -} -int find_longest_common_subsequence(string a, string b, int n, int m, int memoization[][maxi]){ - if(m == 0 || n == 0) - return 0; - // if value is already computed then return the value - if(memoization[n][m] != -1){ - return memoization[n][m]; - } - if(a[n - 1] == b[m - 1]){ - // memoize the solution in order to avoid recomputation - memoization[n][m] = 1 + find_longest_common_subsequence(a, b, n - 1, m - 1, memoization); - } - else{ - // memoize the solution in order to avoid recomputation - memoization[n][m] = get_max(find_longest_common_subsequence(a, b, n - 1, m, memoization), - find_longest_common_subsequence(a, b, n, m -1, memoization)); - } - return memoization[n][m]; -} -int main(){ - string a = "DABCEFIHKST"; - string b = "DCEFKAAAQST"; - int n = a.length(); - int m = b.length(); - int memoization[n+1][maxi]; - memset(memoization, -1, sizeof(memoization)); - int result = find_longest_common_subsequence(a, b, n, m, memoization); - cout << result; - return 0; -} -// Time complexity from exponential to polynomial O(N * M) +// Memoization : Find Longest Common Subsequence of two string +// Program Author : Abhisek Kumar Gupta +/* + To avoid computation of subproblem many times we use memoization + here we take 2D array of size n*m memoization[n][m] + when length of lcs of first i characters of a and j characters of b is + computed for first time it is stored in cell memoization[i][j] + if function is called with n = i and m = j then LCS is not computed from scratch + and stored value is returned from table +*/ +#include +using namespace std; +const int maxi = 10000; +int get_max(int x, int y){ + return (x > y) ? x : y; +} +int find_longest_common_subsequence(string a, string b, int n, int m, int memoization[][maxi]){ + if(m == 0 || n == 0) + return 0; + // if value is already computed then return the value + if(memoization[n][m] != -1){ + return memoization[n][m]; + } + if(a[n - 1] == b[m - 1]){ + // memoize the solution in order to avoid recomputation + memoization[n][m] = 1 + find_longest_common_subsequence(a, b, n - 1, m - 1, memoization); + } + else{ + // memoize the solution in order to avoid recomputation + memoization[n][m] = get_max(find_longest_common_subsequence(a, b, n - 1, m, memoization), + find_longest_common_subsequence(a, b, n, m -1, memoization)); + } + return memoization[n][m]; +} +int main(){ + string a = "DABCEFIHKST"; + string b = "DCEFKAAAQST"; + int n = a.length(); + int m = b.length(); + int memoization[n+1][maxi]; + memset(memoization, -1, sizeof(memoization)); + int result = find_longest_common_subsequence(a, b, n, m, memoization); + cout << result; + return 0; +} +// Time complexity from exponential to polynomial O(N * M) // Space complexity O(N * M) \ No newline at end of file diff --git a/Dynamic_Programming/longest_common_subsequence_recursive.cpp b/Dynamic Programming/longest_common_subsequence_recursive.cpp similarity index 97% rename from Dynamic_Programming/longest_common_subsequence_recursive.cpp rename to Dynamic Programming/longest_common_subsequence_recursive.cpp index a7097908..4991affa 100644 --- a/Dynamic_Programming/longest_common_subsequence_recursive.cpp +++ b/Dynamic Programming/longest_common_subsequence_recursive.cpp @@ -1,49 +1,49 @@ -// Recursion : Find Longest Common Subsequence of two string -// Program Author : Abhisek Kumar Gupta -/* - This problem exemplify optimal substructure property and the - bigger problem can be defined in terms of mini subprobs of same type - hence recursion -*/ - -#include -using namespace std; -int get_max(int x, int y){ - return (x > y) ? x : y; -} -int find_longest_common_subsequence(string a, string b, int n, int m){ - if(m == 0 || n == 0) - return 0; - // we start by comparing last two characters of strings and there are two - // possibilities - // 1) both are same [means we already have found one character in LCS so - // add 1 and make recursive call with modified strings] - if(a[n - 1] == b[m - 1]){ - return 1 + find_longest_common_subsequence(a, b, n-1, m-1); - } - // 2) both are different [find length of tow lcs, first haveing n-1 character from first string - // and m characters from second string, and another with m characters from first string and - // m - 1 characters from second string and return the max of two] - else{ - return get_max(find_longest_common_subsequence(a, b, n-1,m), - find_longest_common_subsequence(a, b, n, m-1)); - } -} -int main(){ - string a = "ABCEFIHST"; - string b = "DCEFKAAAQST"; - int n = a.length(); - int m = b.length(); - int result = find_longest_common_subsequence(a, b, n, m); - cout << result; -} -// Code takes exponential time 2^n in the worst case i.e when all -// two characters are different -// ACB | ABC -// ACB | AB AC | ABC -// AC | A A | AB -// A | A AC | A | A | AB -// BECAUSE WE ARE SOLVING ONE SUB PROBLEM MULTIPLE TIMES SO LCS PROBLEM -// DEMONSTRATES OPTIMAL SUBSTRUCTURE PROPERTY AND THERE ARE OVERLAPPING -// SUBPROBLEMS TOO, SO WE WILL USE MEMOIZATION / DP TO SOLVE THIS PROBLEM +// Recursion : Find Longest Common Subsequence of two string +// Program Author : Abhisek Kumar Gupta +/* + This problem exemplify optimal substructure property and the + bigger problem can be defined in terms of mini subprobs of same type + hence recursion +*/ + +#include +using namespace std; +int get_max(int x, int y){ + return (x > y) ? x : y; +} +int find_longest_common_subsequence(string a, string b, int n, int m){ + if(m == 0 || n == 0) + return 0; + // we start by comparing last two characters of strings and there are two + // possibilities + // 1) both are same [means we already have found one character in LCS so + // add 1 and make recursive call with modified strings] + if(a[n - 1] == b[m - 1]){ + return 1 + find_longest_common_subsequence(a, b, n-1, m-1); + } + // 2) both are different [find length of tow lcs, first haveing n-1 character from first string + // and m characters from second string, and another with m characters from first string and + // m - 1 characters from second string and return the max of two] + else{ + return get_max(find_longest_common_subsequence(a, b, n-1,m), + find_longest_common_subsequence(a, b, n, m-1)); + } +} +int main(){ + string a = "ABCEFIHST"; + string b = "DCEFKAAAQST"; + int n = a.length(); + int m = b.length(); + int result = find_longest_common_subsequence(a, b, n, m); + cout << result; +} +// Code takes exponential time 2^n in the worst case i.e when all +// two characters are different +// ACB | ABC +// ACB | AB AC | ABC +// AC | A A | AB +// A | A AC | A | A | AB +// BECAUSE WE ARE SOLVING ONE SUB PROBLEM MULTIPLE TIMES SO LCS PROBLEM +// DEMONSTRATES OPTIMAL SUBSTRUCTURE PROPERTY AND THERE ARE OVERLAPPING +// SUBPROBLEMS TOO, SO WE WILL USE MEMOIZATION / DP TO SOLVE THIS PROBLEM // OPTIMALLY \ No newline at end of file diff --git a/Dynamic_Programming/longest_increasing_subsequence.cpp b/Dynamic Programming/longest_increasing_subsequence.cpp similarity index 96% rename from Dynamic_Programming/longest_increasing_subsequence.cpp rename to Dynamic Programming/longest_increasing_subsequence.cpp index 3d806881..fa7bd5f1 100644 --- a/Dynamic_Programming/longest_increasing_subsequence.cpp +++ b/Dynamic Programming/longest_increasing_subsequence.cpp @@ -1,36 +1,36 @@ -/* - Longest Increasing Subsequence - Input : 1 2 1 3 1 4 - Output : 4 -*/ -// Dynamic Programming Approach : TC O(n^2) -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; - -int find_longest_increasing_subsequence(vector V, int n){ - int dp[1004]; - for(int i = 0; i < 1000; i++) dp[i] = 1; - int best = INT_MIN; - for(int i = 1; i < n; i++){ - for(int j = 0; j < i; j++){ - if(V[j] <= V[i]){ // this means its in increasing order and we can take value stored at dp[j] and add 1 to it - int curr_len = 1 + dp[j]; - dp[i] = max(curr_len, dp[i]); - } - } - best = max(dp[i], best); - } - return best; -} -int main(){ - int n; - cout << "Enter a number"; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int result = find_longest_increasing_subsequence(V, n); - cout << result; -} +/* + Longest Increasing Subsequence + Input : 1 2 1 3 1 4 + Output : 4 +*/ +// Dynamic Programming Approach : TC O(n^2) +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; + +int find_longest_increasing_subsequence(vector V, int n){ + int dp[1004]; + for(int i = 0; i < 1000; i++) dp[i] = 1; + int best = INT_MIN; + for(int i = 1; i < n; i++){ + for(int j = 0; j < i; j++){ + if(V[j] <= V[i]){ // this means its in increasing order and we can take value stored at dp[j] and add 1 to it + int curr_len = 1 + dp[j]; + dp[i] = max(curr_len, dp[i]); + } + } + best = max(dp[i], best); + } + return best; +} +int main(){ + int n; + cout << "Enter a number"; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + int result = find_longest_increasing_subsequence(V, n); + cout << result; +} diff --git a/Dynamic_Programming/min_cost_travel_in_a_grid.cpp b/Dynamic Programming/min_cost_travel_in_a_grid.cpp similarity index 96% rename from Dynamic_Programming/min_cost_travel_in_a_grid.cpp rename to Dynamic Programming/min_cost_travel_in_a_grid.cpp index 1e64e4af..2a3038b9 100644 --- a/Dynamic_Programming/min_cost_travel_in_a_grid.cpp +++ b/Dynamic Programming/min_cost_travel_in_a_grid.cpp @@ -1,53 +1,53 @@ -/* - Given a cost matrix cost[][] and a position (m, n) in cost[][], - write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). - Each cell of the matrix represents a cost to traverse through that cell. - The total cost of a path to reach (m, n) is the sum of all the costs on that path - (including both source and destination). You can only traverse down and right - from a given cell, i.e., from a given cell (i, j), cells - (i+1, j), (i, j+1) can be traversed. You may assume that all - costs are positive integers. - Input : {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9, 10, 11, 12} - Output : 30 [Path : 1->2->3->4->8->12] -*/ -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -int dp[100][100] = {}; -int min_cost_path_in_a_grid(int grid[][100], int m, int n){ - - dp[0][0] = grid[0][0]; - //row - for(int i = 1; i < m; i++){ - dp[i][0] = grid[i][0] + dp[i - 1][0]; - } - //col - for(int i = 1; i < n; i++){ - dp[0][i] = grid[0][i] + dp[0][i - 1]; - } - - for(int i = 1; i < m; i++){ - for(int j = 1; j < n; j++){ - dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[m-1][n-1]; -} -int main(){ - int grid[100][100] = { - {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9, 10, 11, 12} - }; - int m = 3, n = 4; - int result = min_cost_path_in_a_grid(grid, m, n); - for(int i = 0; i < m; i++){ - for(int j = 0; j < n; j++){ - cout << setw(5) <2->3->4->8->12] +*/ +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +int dp[100][100] = {}; +int min_cost_path_in_a_grid(int grid[][100], int m, int n){ + + dp[0][0] = grid[0][0]; + //row + for(int i = 1; i < m; i++){ + dp[i][0] = grid[i][0] + dp[i - 1][0]; + } + //col + for(int i = 1; i < n; i++){ + dp[0][i] = grid[0][i] + dp[0][i - 1]; + } + + for(int i = 1; i < m; i++){ + for(int j = 1; j < n; j++){ + dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]); + } + } + return dp[m-1][n-1]; +} +int main(){ + int grid[100][100] = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12} + }; + int m = 3, n = 4; + int result = min_cost_path_in_a_grid(grid, m, n); + for(int i = 0; i < m; i++){ + for(int j = 0; j < n; j++){ + cout << setw(5) < -using namespace std; -int dp[10000]; -int find_min_steps(int number){ - int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - dp[0] = 0; - dp[1] = 0; - dp[2] = 1; - dp[3] = 1; - for(int i = 4; i <= number; i++){ - r1 = 1 + dp[i - 1]; - if(i % 2 == 0) - r2 = 1 + dp[i / 2]; - if(i % 3 == 0) - r3 = 1 + dp[i / 3]; - dp[i] = min(r1, min(r2, r3)); - r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - } - - return dp[number]; -} -int main(){ - int number; - cin >> number; - memset(dp, 0, sizeof(dp)); - int result = find_min_steps(number); - cout << result; - return 0; -} +// Minimum steps to reduce a number to one conditions are as follows +// a) subtract 1 [one operation] +// b) divide by 2 [one operation] +// c) divide by 3 [one operation] + +// Dynamic Programming solution +// Program Author : Abhisek Kumar Gupta +/* + Input : 10 + Output : 3 + Explanation : 10 reduced to 9 reduced to 3 reduced to 1 [total 3 operations] + Input : 15 + Output : 4 +*/ +#include +using namespace std; +int dp[10000]; +int find_min_steps(int number){ + int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; + dp[0] = 0; + dp[1] = 0; + dp[2] = 1; + dp[3] = 1; + for(int i = 4; i <= number; i++){ + r1 = 1 + dp[i - 1]; + if(i % 2 == 0) + r2 = 1 + dp[i / 2]; + if(i % 3 == 0) + r3 = 1 + dp[i / 3]; + dp[i] = min(r1, min(r2, r3)); + r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; + } + + return dp[number]; +} +int main(){ + int number; + cin >> number; + memset(dp, 0, sizeof(dp)); + int result = find_min_steps(number); + cout << result; + return 0; +} diff --git a/Dynamic_Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp b/Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp similarity index 96% rename from Dynamic_Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp rename to Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp index 5b33c8c5..cc80fe1b 100644 --- a/Dynamic_Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp +++ b/Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp @@ -1,39 +1,39 @@ -// Minimum steps to reduce a number to one conditions are as follows -// a) subtract 1 [one operation] -// b) divide by 2 [one operation] -// c) divide by 3 [one operation] -// Recursive + Memoized solution -// Program Author : Abhisek Kumar Gupta -/* - Input : 10 - Output : 3 - Explanation : 10 reduced to 9 reduced to 3 reduced to 1 [total 3 operations] - Input : 15 - Output : 4 -*/ -#include -using namespace std; -int memoized[10004]; -int find_min_steps(int number){ - if(number == 1) - return 0; - int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - if(memoized[number] != -1) return memoized[number]; - r1 = 1 + find_min_steps(number - 1); - if(number % 2 == 0) - r2 = 1 + find_min_steps(number / 2); - if(number % 3 == 0) - r3 = 1 + find_min_steps(number / 3); - memoized[number] = min(r1, min(r2, r3)); - return memoized[number]; -} - - -int main(){ - int number; - cin >> number; - memset(memoized, -1, sizeof(memoized)); - int result = find_min_steps(number); - cout << result; - return 0; -} +// Minimum steps to reduce a number to one conditions are as follows +// a) subtract 1 [one operation] +// b) divide by 2 [one operation] +// c) divide by 3 [one operation] +// Recursive + Memoized solution +// Program Author : Abhisek Kumar Gupta +/* + Input : 10 + Output : 3 + Explanation : 10 reduced to 9 reduced to 3 reduced to 1 [total 3 operations] + Input : 15 + Output : 4 +*/ +#include +using namespace std; +int memoized[10004]; +int find_min_steps(int number){ + if(number == 1) + return 0; + int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; + if(memoized[number] != -1) return memoized[number]; + r1 = 1 + find_min_steps(number - 1); + if(number % 2 == 0) + r2 = 1 + find_min_steps(number / 2); + if(number % 3 == 0) + r3 = 1 + find_min_steps(number / 3); + memoized[number] = min(r1, min(r2, r3)); + return memoized[number]; +} + + +int main(){ + int number; + cin >> number; + memset(memoized, -1, sizeof(memoized)); + int result = find_min_steps(number); + cout << result; + return 0; +} diff --git a/Dynamic_Programming/rod_cutting_problem_dp.cpp b/Dynamic Programming/rod_cutting_problem_dp.cpp similarity index 97% rename from Dynamic_Programming/rod_cutting_problem_dp.cpp rename to Dynamic Programming/rod_cutting_problem_dp.cpp index 938da9ab..93096ff3 100644 --- a/Dynamic_Programming/rod_cutting_problem_dp.cpp +++ b/Dynamic Programming/rod_cutting_problem_dp.cpp @@ -1,35 +1,35 @@ - /* - Given a rod of length n inches and an array of prices that contains prices of all - pieces of size smaller than n. Determine the maximum value obtainable by cutting - up the rod and selling the pieces. For example, if length of the rod is 8 and the - values of different pieces are given as following, then the maximum obtainable - value is 22 (by cutting in two pieces of lengths 2 and 6) - Input : 8 - : 1 5 8 9 10 17 17 20 - Output : 22 -*/ -// Dynamic Programming solution TC : O(n^2) -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -int max_profit(vector profit, int total_length){ - int dp[100] = {}; - for(int length = 1; length <= total_length; length++){ - int best = 0; - for(int cut = 1; cut <= length; cut++){ - best = max(best, profit[cut] + dp[length - cut]); - } - dp[length] = best; - } - return dp[total_length]; -} -int main(){ - int total_length; - cin >> total_length; - vector profit(total_length + 1); - for(int length = 1; length <= total_length; length++) - cin >> profit[length]; - int result = max_profit(profit, total_length); - cout << result; - return 0; + /* + Given a rod of length n inches and an array of prices that contains prices of all + pieces of size smaller than n. Determine the maximum value obtainable by cutting + up the rod and selling the pieces. For example, if length of the rod is 8 and the + values of different pieces are given as following, then the maximum obtainable + value is 22 (by cutting in two pieces of lengths 2 and 6) + Input : 8 + : 1 5 8 9 10 17 17 20 + Output : 22 +*/ +// Dynamic Programming solution TC : O(n^2) +// Program Author: Abhisek Kumar Gupta +#include +using namespace std; +int max_profit(vector profit, int total_length){ + int dp[100] = {}; + for(int length = 1; length <= total_length; length++){ + int best = 0; + for(int cut = 1; cut <= length; cut++){ + best = max(best, profit[cut] + dp[length - cut]); + } + dp[length] = best; + } + return dp[total_length]; +} +int main(){ + int total_length; + cin >> total_length; + vector profit(total_length + 1); + for(int length = 1; length <= total_length; length++) + cin >> profit[length]; + int result = max_profit(profit, total_length); + cout << result; + return 0; } \ No newline at end of file diff --git a/Dynamic_Programming/rod_cutting_problem_memoized.cpp b/Dynamic Programming/rod_cutting_problem_memoized.cpp similarity index 97% rename from Dynamic_Programming/rod_cutting_problem_memoized.cpp rename to Dynamic Programming/rod_cutting_problem_memoized.cpp index 94d51ccb..3b15e569 100644 --- a/Dynamic_Programming/rod_cutting_problem_memoized.cpp +++ b/Dynamic Programming/rod_cutting_problem_memoized.cpp @@ -1,37 +1,37 @@ -/* - Given a rod of length n inches and an array of prices that contains prices of all - pieces of size smaller than n. Determine the maximum value obtainable by cutting - up the rod and selling the pieces. For example, if length of the rod is 8 and the - values of different pieces are given as following, then the maximum obtainable - value is 22 (by cutting in two pieces of lengths 2 and 6) - Input : 8 - : 1 5 8 9 10 17 17 20 - Output : 22 -*/ -// Memoized solution TC : O(n^2) -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -int memoized[1000]; -int max_profit(vector length, int n){ - if(n == 0) return 0; - int best = 0; - if(memoized[n] != -1) return memoized[n]; - for(int i = 0; i < n; i++){ - int total_profit = length[i] + max_profit(length, n - (i + 1)); - best = max(best, total_profit); - memoized[n] = best; - } - return memoized[n]; -} -int main(){ - memset(memoized, -1, sizeof(memoized)); - int n; - cin >> n; - vector length(n); - for(int i = 0; i < n; i++) - cin >> length[i]; - int result = max_profit(length, n); - cout << result; - return 0; +/* + Given a rod of length n inches and an array of prices that contains prices of all + pieces of size smaller than n. Determine the maximum value obtainable by cutting + up the rod and selling the pieces. For example, if length of the rod is 8 and the + values of different pieces are given as following, then the maximum obtainable + value is 22 (by cutting in two pieces of lengths 2 and 6) + Input : 8 + : 1 5 8 9 10 17 17 20 + Output : 22 +*/ +// Memoized solution TC : O(n^2) +// Program Author: Abhisek Kumar Gupta +#include +using namespace std; +int memoized[1000]; +int max_profit(vector length, int n){ + if(n == 0) return 0; + int best = 0; + if(memoized[n] != -1) return memoized[n]; + for(int i = 0; i < n; i++){ + int total_profit = length[i] + max_profit(length, n - (i + 1)); + best = max(best, total_profit); + memoized[n] = best; + } + return memoized[n]; +} +int main(){ + memset(memoized, -1, sizeof(memoized)); + int n; + cin >> n; + vector length(n); + for(int i = 0; i < n; i++) + cin >> length[i]; + int result = max_profit(length, n); + cout << result; + return 0; } \ No newline at end of file diff --git a/Dynamic_Programming/rod_cutting_problem_recursive.cpp b/Dynamic Programming/rod_cutting_problem_recursive.cpp similarity index 97% rename from Dynamic_Programming/rod_cutting_problem_recursive.cpp rename to Dynamic Programming/rod_cutting_problem_recursive.cpp index 154f30b8..59009a48 100644 --- a/Dynamic_Programming/rod_cutting_problem_recursive.cpp +++ b/Dynamic Programming/rod_cutting_problem_recursive.cpp @@ -1,33 +1,33 @@ -/* - Given a rod of length n inches and an array of prices that contains prices of all - pieces of size smaller than n. Determine the maximum value obtainable by cutting - up the rod and selling the pieces. For example, if length of the rod is 8 and the - values of different pieces are given as following, then the maximum obtainable - value is 22 (by cutting in two pieces of lengths 2 and 6) - Input : 8 - : 1 5 8 9 10 17 17 20 - Output : 22 -*/ -// Recursive solution TC : O(2^n) -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -int max_profit(vector length, int n){ - if(n == 0) return 0; - int best = 0; - for(int i = 0; i < n; i++){ - int total_profit = length[i] + max_profit(length, n - (i + 1)); - best = max(best, total_profit); - } - return best; -} -int main(){ - int n; - cin >> n; - vector length(n); - for(int i = 0; i < n; i++) - cin >> length[i]; - int result = max_profit(length, n); - cout << result; - return 0; -} +/* + Given a rod of length n inches and an array of prices that contains prices of all + pieces of size smaller than n. Determine the maximum value obtainable by cutting + up the rod and selling the pieces. For example, if length of the rod is 8 and the + values of different pieces are given as following, then the maximum obtainable + value is 22 (by cutting in two pieces of lengths 2 and 6) + Input : 8 + : 1 5 8 9 10 17 17 20 + Output : 22 +*/ +// Recursive solution TC : O(2^n) +// Program Author: Abhisek Kumar Gupta +#include +using namespace std; +int max_profit(vector length, int n){ + if(n == 0) return 0; + int best = 0; + for(int i = 0; i < n; i++){ + int total_profit = length[i] + max_profit(length, n - (i + 1)); + best = max(best, total_profit); + } + return best; +} +int main(){ + int n; + cin >> n; + vector length(n); + for(int i = 0; i < n; i++) + cin >> length[i]; + int result = max_profit(length, n); + cout << result; + return 0; +} diff --git a/Dynamic_Programming/trapping_rain_water.cpp b/Dynamic Programming/trapping_rain_water.cpp similarity index 100% rename from Dynamic_Programming/trapping_rain_water.cpp rename to Dynamic Programming/trapping_rain_water.cpp diff --git a/Dynamic_Programming/wine_selling_problem_dp.cpp b/Dynamic Programming/wine_selling_problem_dp.cpp similarity index 96% rename from Dynamic_Programming/wine_selling_problem_dp.cpp rename to Dynamic Programming/wine_selling_problem_dp.cpp index f8ebbf59..48b7f751 100644 --- a/Dynamic_Programming/wine_selling_problem_dp.cpp +++ b/Dynamic Programming/wine_selling_problem_dp.cpp @@ -1,57 +1,57 @@ -/* - Given n wines in a row, with integers denoting the cost of each wine respectively. - Each year you can sale the first or the last wine in the row. However, the price - of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. - On the Yth year, the profit from the ith wine will be Y*Pi. - Calculate the maximum profit from all the wines. - - Input : 5 - : 2 4 6 2 5 - Output : 64 -*/ -// Dynamic Programming Approach TC : O(N^2) -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -int find_max_profit(int *A, int n){ - int dp[100][100] = {}; - int year = n; - for(int i = 0; i < n; i++){ - dp[i][i] = year * A[i]; - } - year--; - for(int i = 2; i <= n; i++){ - int start = 0; - int end = n - i; - while(start <= end){ - int end_window = start + i - 1; - int x = A[start] * year + dp[start + 1][end_window]; - int y = A[end_window]* year + dp[start][end_window - 1]; - dp[start][end_window] = max(x, y); - start++; - } - year--; - } - /* for(int i = 0; i < n; i++){ - for(int j = 0; j < n; j++){ - cout << setw(5) << dp[i][j] << " "; - } - cout << "\n"; - } - */ - return dp[0][n-1]; -} -int main(){ - int n; - cin >> n; - int *A; - for(int i = 0; i < n; i++) - cin >> A[i]; - int start = 0; - int end = n - 1; - int year = 1; - int result = find_max_profit(A, n); - cout << result; - return 0; -} +/* + Given n wines in a row, with integers denoting the cost of each wine respectively. + Each year you can sale the first or the last wine in the row. However, the price + of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. + On the Yth year, the profit from the ith wine will be Y*Pi. + Calculate the maximum profit from all the wines. + + Input : 5 + : 2 4 6 2 5 + Output : 64 +*/ +// Dynamic Programming Approach TC : O(N^2) +// Program Author : Abhisek Kumar Gupta + +#include +using namespace std; +int find_max_profit(int *A, int n){ + int dp[100][100] = {}; + int year = n; + for(int i = 0; i < n; i++){ + dp[i][i] = year * A[i]; + } + year--; + for(int i = 2; i <= n; i++){ + int start = 0; + int end = n - i; + while(start <= end){ + int end_window = start + i - 1; + int x = A[start] * year + dp[start + 1][end_window]; + int y = A[end_window]* year + dp[start][end_window - 1]; + dp[start][end_window] = max(x, y); + start++; + } + year--; + } + /* for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cout << setw(5) << dp[i][j] << " "; + } + cout << "\n"; + } + */ + return dp[0][n-1]; +} +int main(){ + int n; + cin >> n; + int *A; + for(int i = 0; i < n; i++) + cin >> A[i]; + int start = 0; + int end = n - 1; + int year = 1; + int result = find_max_profit(A, n); + cout << result; + return 0; +} diff --git a/Dynamic_Programming/wine_selling_problem_memoized.cpp b/Dynamic Programming/wine_selling_problem_memoized.cpp similarity index 96% rename from Dynamic_Programming/wine_selling_problem_memoized.cpp rename to Dynamic Programming/wine_selling_problem_memoized.cpp index 6cf1321b..1c773de5 100644 --- a/Dynamic_Programming/wine_selling_problem_memoized.cpp +++ b/Dynamic Programming/wine_selling_problem_memoized.cpp @@ -1,42 +1,42 @@ -/* - Given n wines in a row, with integers denoting the cost of each wine respectively. - Each year you can sale the first or the last wine in the row. However, the price - of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. - On the Yth year, the profit from the ith wine will be Y*Pi. - Calculate the maximum profit from all the wines. - - Input : 5 - : 2 4 6 2 5 - Output : 64 -*/ -// Memoized Approach TC : O(N^2) -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -int memoized[1000][1000]; -int find_max_profit(int *A, int start, int end, int year){ - if(start > end) - return 0; - if(memoized[start][end] != -1) - return memoized[start][end]; - int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); - int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); - int answer = max(r1, r2); ; - memoized[start][end] = answer; - return memoized[start][end]; -} -int main(){ - memset(memoized, -1, sizeof(memoized)); - int n; - cin >> n; - int *A; - for(int i = 0; i < n; i++) - cin >> A[i]; - int start = 0; - int end = n - 1; - int year = 1; - int result = find_max_profit(A, start, end, year); - cout << result; - return 0; +/* + Given n wines in a row, with integers denoting the cost of each wine respectively. + Each year you can sale the first or the last wine in the row. However, the price + of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. + On the Yth year, the profit from the ith wine will be Y*Pi. + Calculate the maximum profit from all the wines. + + Input : 5 + : 2 4 6 2 5 + Output : 64 +*/ +// Memoized Approach TC : O(N^2) +// Program Author : Abhisek Kumar Gupta + +#include +using namespace std; +int memoized[1000][1000]; +int find_max_profit(int *A, int start, int end, int year){ + if(start > end) + return 0; + if(memoized[start][end] != -1) + return memoized[start][end]; + int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); + int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); + int answer = max(r1, r2); ; + memoized[start][end] = answer; + return memoized[start][end]; +} +int main(){ + memset(memoized, -1, sizeof(memoized)); + int n; + cin >> n; + int *A; + for(int i = 0; i < n; i++) + cin >> A[i]; + int start = 0; + int end = n - 1; + int year = 1; + int result = find_max_profit(A, start, end, year); + cout << result; + return 0; } \ No newline at end of file diff --git a/Dynamic_Programming/wine_selling_problem_recursive.cpp b/Dynamic Programming/wine_selling_problem_recursive.cpp similarity index 96% rename from Dynamic_Programming/wine_selling_problem_recursive.cpp rename to Dynamic Programming/wine_selling_problem_recursive.cpp index 7bb0ec80..3879d21b 100644 --- a/Dynamic_Programming/wine_selling_problem_recursive.cpp +++ b/Dynamic Programming/wine_selling_problem_recursive.cpp @@ -1,36 +1,36 @@ -/* - Given n wines in a row, with integers denoting the cost of each wine respectively. - Each year you can sale the first or the last wine in the row. However, the price - of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. - On the Yth year, the profit from the ith wine will be Y*Pi. - Calculate the maximum profit from all the wines. - - Input : 5 - : 2 4 6 2 5 - Output : 64 -*/ -// Recursive Approach TC : O(2^n) -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -int find_max_profit(int *A, int start, int end, int year){ - if(start > end) - return 0; - int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); - int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); - return max(r1, r2); -} -int main(){ - int n; - cin >> n; - int *A; - for(int i = 0; i < n; i++) - cin >> A[i]; - int start = 0; - int end = n - 1; - int year = 1; - int result = find_max_profit(A, start, end, year); - cout << result; - return 0; +/* + Given n wines in a row, with integers denoting the cost of each wine respectively. + Each year you can sale the first or the last wine in the row. However, the price + of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. + On the Yth year, the profit from the ith wine will be Y*Pi. + Calculate the maximum profit from all the wines. + + Input : 5 + : 2 4 6 2 5 + Output : 64 +*/ +// Recursive Approach TC : O(2^n) +// Program Author : Abhisek Kumar Gupta + +#include +using namespace std; +int find_max_profit(int *A, int start, int end, int year){ + if(start > end) + return 0; + int r1 = A[start] * year + find_max_profit(A, start + 1, end, year + 1); + int r2 = A[end] * year + find_max_profit(A, start, end - 1, year + 1); + return max(r1, r2); +} +int main(){ + int n; + cin >> n; + int *A; + for(int i = 0; i < n; i++) + cin >> A[i]; + int start = 0; + int end = n - 1; + int year = 1; + int result = find_max_profit(A, start, end, year); + cout << result; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_floyds_cycle_detection.cpp b/Linked List/linked_floyds_cycle_detection.cpp similarity index 96% rename from Linked_List/linked_floyds_cycle_detection.cpp rename to Linked List/linked_floyds_cycle_detection.cpp index bd62ffc2..4f28ef38 100644 --- a/Linked_List/linked_floyds_cycle_detection.cpp +++ b/Linked List/linked_floyds_cycle_detection.cpp @@ -1,80 +1,80 @@ -// Floyds Cycle detection and removal -// Program Author : Abhisek Kumar Gupta -// The cycle detection problem is to find the cycle in a sequence, -// and Floyd’s cycle detection algorithm, aka Tortoise and Hare algorithm, -// is a two-pointer algorithm to detect the cycle and locate the start of the cycle as well. -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } - head->next->next->next = head; -} -bool detect_cycle(node *head){ - node *slow = head; - node *fast = head; - while(fast != NULL && fast->next != NULL){ - fast = fast->next->next; - slow = slow->next; - if(fast == slow){ - //return true; - slow = head; - if(slow == fast){ - while(fast->next != slow) fast = fast->next; - } - else{ - while(slow->next != fast->next){ - slow = slow->next; - fast = fast->next; - } - } - fast->next = NULL; - cout << "Cycle Detected and Removed \n"; - } - } - return false; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - //print_linked_list(head); - if(detect_cycle(head)){ - cout << "Cycle detected \n"; - } - else { - cout << "No cycle \n"; - } - print_linked_list(head); - return 0; +// Floyds Cycle detection and removal +// Program Author : Abhisek Kumar Gupta +// The cycle detection problem is to find the cycle in a sequence, +// and Floyd’s cycle detection algorithm, aka Tortoise and Hare algorithm, +// is a two-pointer algorithm to detect the cycle and locate the start of the cycle as well. +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } + head->next->next->next = head; +} +bool detect_cycle(node *head){ + node *slow = head; + node *fast = head; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + if(fast == slow){ + //return true; + slow = head; + if(slow == fast){ + while(fast->next != slow) fast = fast->next; + } + else{ + while(slow->next != fast->next){ + slow = slow->next; + fast = fast->next; + } + } + fast->next = NULL; + cout << "Cycle Detected and Removed \n"; + } + } + return false; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + //print_linked_list(head); + if(detect_cycle(head)){ + cout << "Cycle detected \n"; + } + else { + cout << "No cycle \n"; + } + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list.go b/Linked List/linked_list.go similarity index 100% rename from Linked_List/linked_list.go rename to Linked List/linked_list.go diff --git a/Linked_List/linked_list_compute_midpoint.cpp b/Linked List/linked_list_compute_midpoint.cpp similarity index 96% rename from Linked_List/linked_list_compute_midpoint.cpp rename to Linked List/linked_list_compute_midpoint.cpp index 1348dd7c..9d908695 100644 --- a/Linked_List/linked_list_compute_midpoint.cpp +++ b/Linked List/linked_list_compute_midpoint.cpp @@ -1,62 +1,62 @@ -// Finding Midpoint of a LinkedList -// Program Author : Abhisek Kumar Gupta -// Naive Approach: Find the length of the linked list and return the (length/2)th node. -// One pass Approach: Use two pointers, the 2nd pointer should traverse twice as fast at the first. -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* compute_midpoint(node *head){ - if(head->next == NULL || head == NULL){ - return head; - } - node *slow = head; - node *fast = head->next; - while(fast != NULL && fast->next != NULL){ - fast = fast->next->next; - slow = slow->next; - } - return slow; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - node *midpoint = compute_midpoint(head); - cout << endl; - cout << midpoint->data << endl; - return 0; +// Finding Midpoint of a LinkedList +// Program Author : Abhisek Kumar Gupta +// Naive Approach: Find the length of the linked list and return the (length/2)th node. +// One pass Approach: Use two pointers, the 2nd pointer should traverse twice as fast at the first. +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +node* compute_midpoint(node *head){ + if(head->next == NULL || head == NULL){ + return head; + } + node *slow = head; + node *fast = head->next; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + } + return slow; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + node *midpoint = compute_midpoint(head); + cout << endl; + cout << midpoint->data << endl; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_dalete_at_tail.cpp b/Linked List/linked_list_dalete_at_tail.cpp similarity index 95% rename from Linked_List/linked_list_dalete_at_tail.cpp rename to Linked List/linked_list_dalete_at_tail.cpp index 39b9c10d..1ce28b3b 100644 --- a/Linked_List/linked_list_dalete_at_tail.cpp +++ b/Linked List/linked_list_dalete_at_tail.cpp @@ -1,59 +1,59 @@ -// Delete from Tail in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void delete_at_tail(node *&head){ - node *prev = NULL; - node *temp = head; - while(temp->next != NULL){ - prev = temp; - temp = temp->next; - } - prev->next = NULL; - delete temp; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_tail(head, 20); - insert_at_tail(head, 33); - insert_at_tail(head, 100); - insert_at_tail(head, 200); - insert_at_tail(head, 201); - insert_at_tail(head, 202); - print_linked_list(head); - cout << endl; - delete_at_tail(head); - delete_at_tail(head); - - print_linked_list(head); - return 0; -} +// Delete from Tail in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void delete_at_tail(node *&head){ + node *prev = NULL; + node *temp = head; + while(temp->next != NULL){ + prev = temp; + temp = temp->next; + } + prev->next = NULL; + delete temp; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_tail(head, 20); + insert_at_tail(head, 33); + insert_at_tail(head, 100); + insert_at_tail(head, 200); + insert_at_tail(head, 201); + insert_at_tail(head, 202); + print_linked_list(head); + cout << endl; + delete_at_tail(head); + delete_at_tail(head); + + print_linked_list(head); + return 0; +} diff --git a/Linked_List/linked_list_delete_at_any_pos.cpp b/Linked List/linked_list_delete_at_any_pos.cpp similarity index 95% rename from Linked_List/linked_list_delete_at_any_pos.cpp rename to Linked List/linked_list_delete_at_any_pos.cpp index 798bc483..664d8f9f 100644 --- a/Linked_List/linked_list_delete_at_any_pos.cpp +++ b/Linked List/linked_list_delete_at_any_pos.cpp @@ -1,122 +1,122 @@ -// Insert at any position in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -int length(node* head){ - int len = 0; - while(head != NULL){ - head = head->next; - len++; - } - return len; -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void insert_at_anypos(node *&head, int data, int pos){ - if(head == NULL || pos == 0){ - insert_at_head(head, data); - } - else if(pos > length(head)){ - insert_at_tail(head, data); - } - else{ - node* temp = head; - node *n = new node(data); - for(int i = 0; i < pos - 1; i++){ - temp = temp->next; - } - n->next = temp->next; - temp->next = n; - } -} -void delete_at_head(node *&head){ - if(head == NULL){ - return; - } - node *temp = head; - head = head->next; - delete temp; -} -void delete_at_tail(node *&head){ - node *prev = NULL; - node *temp = head; - while(temp->next != NULL){ - prev = temp; - temp = temp->next; - } - prev->next = NULL; - delete temp; -} -void delete_at_any_pos(node *&head, int pos){ - if(pos == 0 || pos == 1){ - delete_at_head(head); - return; - } - else if(pos > length(head)){ - delete_at_tail(head); - } - else{ - node *prev = NULL; - node *temp = head; - for(int i = 0; i < pos - 1; i++){ - prev = temp; - temp = temp->next; - } - prev->next = temp->next; - delete temp; - } -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - insert_at_anypos(head, 6, 10); - insert_at_tail(head, 33); - insert_at_head(head, 44); - insert_at_anypos(head, 66, 4); - insert_at_tail(head, 100); - insert_at_anypos(head, 11, 3); - print_linked_list(head); - delete_at_any_pos(head, 2); - delete_at_any_pos(head, 3); - delete_at_any_pos(head, 4); - insert_at_anypos(head, 22, 2); - cout << endl; - print_linked_list(head); - delete_at_any_pos(head, 2); - cout << endl; - print_linked_list(head); - return 0; +// Insert at any position in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +int length(node* head){ + int len = 0; + while(head != NULL){ + head = head->next; + len++; + } + return len; +} +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void insert_at_anypos(node *&head, int data, int pos){ + if(head == NULL || pos == 0){ + insert_at_head(head, data); + } + else if(pos > length(head)){ + insert_at_tail(head, data); + } + else{ + node* temp = head; + node *n = new node(data); + for(int i = 0; i < pos - 1; i++){ + temp = temp->next; + } + n->next = temp->next; + temp->next = n; + } +} +void delete_at_head(node *&head){ + if(head == NULL){ + return; + } + node *temp = head; + head = head->next; + delete temp; +} +void delete_at_tail(node *&head){ + node *prev = NULL; + node *temp = head; + while(temp->next != NULL){ + prev = temp; + temp = temp->next; + } + prev->next = NULL; + delete temp; +} +void delete_at_any_pos(node *&head, int pos){ + if(pos == 0 || pos == 1){ + delete_at_head(head); + return; + } + else if(pos > length(head)){ + delete_at_tail(head); + } + else{ + node *prev = NULL; + node *temp = head; + for(int i = 0; i < pos - 1; i++){ + prev = temp; + temp = temp->next; + } + prev->next = temp->next; + delete temp; + } +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + insert_at_anypos(head, 6, 10); + insert_at_tail(head, 33); + insert_at_head(head, 44); + insert_at_anypos(head, 66, 4); + insert_at_tail(head, 100); + insert_at_anypos(head, 11, 3); + print_linked_list(head); + delete_at_any_pos(head, 2); + delete_at_any_pos(head, 3); + delete_at_any_pos(head, 4); + insert_at_anypos(head, 22, 2); + cout << endl; + print_linked_list(head); + delete_at_any_pos(head, 2); + cout << endl; + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_delete_at_head.cpp b/Linked List/linked_list_delete_at_head.cpp similarity index 95% rename from Linked_List/linked_list_delete_at_head.cpp rename to Linked List/linked_list_delete_at_head.cpp index 1a793e38..54717b17 100644 --- a/Linked_List/linked_list_delete_at_head.cpp +++ b/Linked List/linked_list_delete_at_head.cpp @@ -1,45 +1,45 @@ -// Delete from Head in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void delete_at_head(node *&head){ - if(head == NULL){ - return; - } - node *temp = head; - head = head->next; - delete temp; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - cout << endl; - delete_at_head(head); - delete_at_head(head); - print_linked_list(head); - return 0; +// Delete from Head in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void delete_at_head(node *&head){ + if(head == NULL){ + return; + } + node *temp = head; + head = head->next; + delete temp; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + print_linked_list(head); + cout << endl; + delete_at_head(head); + delete_at_head(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_find_length.cpp b/Linked List/linked_list_find_length.cpp similarity index 95% rename from Linked_List/linked_list_find_length.cpp rename to Linked List/linked_list_find_length.cpp index 1ebd3d6e..9097c7cd 100644 --- a/Linked_List/linked_list_find_length.cpp +++ b/Linked List/linked_list_find_length.cpp @@ -1,44 +1,44 @@ -// Find length of a LinkedList -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -int length(node* head){ - int len = 0; - while(head != NULL){ - head = head->next; - len++; - } - return len; -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - int len = length(head); - cout << endl < +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +int length(node* head){ + int len = 0; + while(head != NULL){ + head = head->next; + len++; + } + return len; +} +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + print_linked_list(head); + int len = length(head); + cout << endl < -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -int length(node* head){ - int len = 0; - while(head != NULL){ - head = head->next; - len++; - } - return len; -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void insert_at_anypos(node *&head, int data, int pos){ - if(head == NULL || pos == 0){ - insert_at_head(head, data); - } - else if(pos > length(head)){ - insert_at_tail(head, data); - } - else{ - node* temp = head; - node *n = new node(data); - for(int i = 0; i < pos - 1; i++){ - temp = temp->next; - } - n->next = temp->next; - temp->next = n; - } -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - insert_at_anypos(head, 6, 10); - insert_at_tail(head, 33); - insert_at_head(head, 44); - insert_at_anypos(head, 66, 4); - insert_at_tail(head, 100); - insert_at_anypos(head, 11, 3); - print_linked_list(head); - return 0; +// Insert at any position in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +int length(node* head){ + int len = 0; + while(head != NULL){ + head = head->next; + len++; + } + return len; +} +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void insert_at_anypos(node *&head, int data, int pos){ + if(head == NULL || pos == 0){ + insert_at_head(head, data); + } + else if(pos > length(head)){ + insert_at_tail(head, data); + } + else{ + node* temp = head; + node *n = new node(data); + for(int i = 0; i < pos - 1; i++){ + temp = temp->next; + } + n->next = temp->next; + temp->next = n; + } +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + insert_at_anypos(head, 6, 10); + insert_at_tail(head, 33); + insert_at_head(head, 44); + insert_at_anypos(head, 66, 4); + insert_at_tail(head, 100); + insert_at_anypos(head, 11, 3); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_insert_at_head.cpp b/Linked List/linked_list_insert_at_head.cpp similarity index 95% rename from Linked_List/linked_list_insert_at_head.cpp rename to Linked List/linked_list_insert_at_head.cpp index 4879f46b..f2b7a50c 100644 --- a/Linked_List/linked_list_insert_at_head.cpp +++ b/Linked List/linked_list_insert_at_head.cpp @@ -1,34 +1,34 @@ -// Search recursively in a LinkedList -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - return 0; +// Search recursively in a LinkedList +// Program Author : Abhisek Kumar Gupta + +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_insert_at_tail.cpp b/Linked List/linked_list_insert_at_tail.cpp similarity index 95% rename from Linked_List/linked_list_insert_at_tail.cpp rename to Linked List/linked_list_insert_at_tail.cpp index 653adf27..55b93bed 100644 --- a/Linked_List/linked_list_insert_at_tail.cpp +++ b/Linked List/linked_list_insert_at_tail.cpp @@ -1,43 +1,43 @@ -// Insert at Tail in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_tail(head, 20); - insert_at_tail(head, 33); - insert_at_tail(head, 100); - insert_at_tail(head, 200); - print_linked_list(head); - - return 0; +// Insert at Tail in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_tail(head, 20); + insert_at_tail(head, 33); + insert_at_tail(head, 100); + insert_at_tail(head, 200); + print_linked_list(head); + + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_kth_node_from_end.cpp b/Linked List/linked_list_kth_node_from_end.cpp similarity index 95% rename from Linked_List/linked_list_kth_node_from_end.cpp rename to Linked List/linked_list_kth_node_from_end.cpp index 726a3124..b64e5c47 100644 --- a/Linked_List/linked_list_kth_node_from_end.cpp +++ b/Linked List/linked_list_kth_node_from_end.cpp @@ -1,65 +1,65 @@ -// Finding Kth node from end of a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* kth_node_from_end(node *head, int k){ - if(head->next == NULL || head == NULL){ - return head; - } - node *slow = head; - node *fast = head; - while(k--){ - fast = fast->next; - } - while(fast){ - fast = fast->next; - slow = slow->next; - } - return slow; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - int k; - cin >> k; - node *kth_node = kth_node_from_end(head, k); - cout << endl; - cout << kth_node->data << endl; - return 0; +// Finding Kth node from end of a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +node* kth_node_from_end(node *head, int k){ + if(head->next == NULL || head == NULL){ + return head; + } + node *slow = head; + node *fast = head; + while(k--){ + fast = fast->next; + } + while(fast){ + fast = fast->next; + slow = slow->next; + } + return slow; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + int k; + cin >> k; + node *kth_node = kth_node_from_end(head, k); + cout << endl; + cout << kth_node->data << endl; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_linear_search.cpp b/Linked List/linked_list_linear_search.cpp similarity index 95% rename from Linked_List/linked_list_linear_search.cpp rename to Linked List/linked_list_linear_search.cpp index 91997de8..e9f2eff8 100644 --- a/Linked_List/linked_list_linear_search.cpp +++ b/Linked List/linked_list_linear_search.cpp @@ -1,55 +1,55 @@ -// Search linearly in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -bool linear_search(node *head, int key){ - if(head == NULL){ - return false; - } - else{ - node *temp = head; - while(temp != NULL){ - if(temp->data == key){ - return true; - } - temp = temp->next; - } - } - return false; -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - cout << endl; - if(linear_search(head, 1)){ - cout << "Found"; - } - else{ - cout << "Not Found"; - } - return 0; +// Search linearly in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +bool linear_search(node *head, int key){ + if(head == NULL){ + return false; + } + else{ + node *temp = head; + while(temp != NULL){ + if(temp->data == key){ + return true; + } + temp = temp->next; + } + } + return false; +} +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + print_linked_list(head); + cout << endl; + if(linear_search(head, 1)){ + cout << "Found"; + } + else{ + cout << "Not Found"; + } + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_merge_k_sorted_lists.cpp b/Linked List/linked_list_merge_k_sorted_lists.cpp similarity index 95% rename from Linked_List/linked_list_merge_k_sorted_lists.cpp rename to Linked List/linked_list_merge_k_sorted_lists.cpp index d8a30f91..47519766 100644 --- a/Linked_List/linked_list_merge_k_sorted_lists.cpp +++ b/Linked List/linked_list_merge_k_sorted_lists.cpp @@ -1,99 +1,99 @@ -// Merge K sorted LinkedLists -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -node* merge_two_lists(node *a, node *b){ - if(a == NULL){ - return b; - } - else if(b == NULL){ - return a; - } - node *c = NULL; - if(a->data < b->data){ - c = a; - c->next = merge_two_lists(a->next, b); - } - else{ - c = b; - c->next = merge_two_lists(a, b->next); - } - return c; -} -node* merge_k_lists(node *arr[], int last){ - while(last != 0){ - int i = 0, j = last; - while(i < j){ - arr[i] = merge_two_lists(arr[i], arr[j]); - i++; - j--; - if(i >= j) - last = j; - } - } - return arr[0]; -} -int main(){ - - int n; - cin >> n; - node *arr[n]; - for(int i = 0; i < n; i++){ - arr[i] = NULL; - } - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - cout << endl; - for(int i = 0; i < n; i++){ - cout << arr[i] << endl;; - } - node *head = merge_k_lists(arr, n-1); - cout << head; - return 0; +// Merge K sorted LinkedLists +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +istream& operator>>(istream &is, node *&head){ + makeLinkedList(head); + return is; +} +ostream& operator<<(ostream &os, node *&head){ + print_linked_list(head); + return os; +} +node* merge_two_lists(node *a, node *b){ + if(a == NULL){ + return b; + } + else if(b == NULL){ + return a; + } + node *c = NULL; + if(a->data < b->data){ + c = a; + c->next = merge_two_lists(a->next, b); + } + else{ + c = b; + c->next = merge_two_lists(a, b->next); + } + return c; +} +node* merge_k_lists(node *arr[], int last){ + while(last != 0){ + int i = 0, j = last; + while(i < j){ + arr[i] = merge_two_lists(arr[i], arr[j]); + i++; + j--; + if(i >= j) + last = j; + } + } + return arr[0]; +} +int main(){ + + int n; + cin >> n; + node *arr[n]; + for(int i = 0; i < n; i++){ + arr[i] = NULL; + } + for(int i = 0; i < n; i++){ + cin >> arr[i]; + } + cout << endl; + for(int i = 0; i < n; i++){ + cout << arr[i] << endl;; + } + node *head = merge_k_lists(arr, n-1); + cout << head; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_merge_two_sorted_linked_list.cpp b/Linked List/linked_list_merge_two_sorted_linked_list.cpp similarity index 95% rename from Linked_List/linked_list_merge_two_sorted_linked_list.cpp rename to Linked List/linked_list_merge_two_sorted_linked_list.cpp index aa2219f0..275ba9d7 100644 --- a/Linked_List/linked_list_merge_two_sorted_linked_list.cpp +++ b/Linked List/linked_list_merge_two_sorted_linked_list.cpp @@ -1,77 +1,77 @@ -// Merge two sorted LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -node* merge_two_lists(node *a, node *b){ - if(a == NULL){ - return b; - } - else if(b == NULL){ - return a; - } - node *c = NULL; - if(a->data < b->data){ - c = a; - c->next = merge_two_lists(a->next, b); - } - else{ - c = b; - c->next = merge_two_lists(a, b->next); - } - return c; -} -int main(){ - node *head = NULL; - node *head2 = NULL; - cin >> head >> head2; - cout << head << endl << head2; - cout << endl; - node *x = merge_two_lists(head, head2); - cout << x << endl; - return 0; +// Merge two sorted LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +istream& operator>>(istream &is, node *&head){ + makeLinkedList(head); + return is; +} +ostream& operator<<(ostream &os, node *&head){ + print_linked_list(head); + return os; +} +node* merge_two_lists(node *a, node *b){ + if(a == NULL){ + return b; + } + else if(b == NULL){ + return a; + } + node *c = NULL; + if(a->data < b->data){ + c = a; + c->next = merge_two_lists(a->next, b); + } + else{ + c = b; + c->next = merge_two_lists(a, b->next); + } + return c; +} +int main(){ + node *head = NULL; + node *head2 = NULL; + cin >> head >> head2; + cout << head << endl << head2; + cout << endl; + node *x = merge_two_lists(head, head2); + cout << x << endl; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_mergesort_an_unsorted_list.cpp b/Linked List/linked_list_mergesort_an_unsorted_list.cpp similarity index 95% rename from Linked_List/linked_list_mergesort_an_unsorted_list.cpp rename to Linked List/linked_list_mergesort_an_unsorted_list.cpp index ff9217b5..d1ccd804 100644 --- a/Linked_List/linked_list_mergesort_an_unsorted_list.cpp +++ b/Linked List/linked_list_mergesort_an_unsorted_list.cpp @@ -1,100 +1,100 @@ -// MergeSort an unsorted LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* compute_midpoint(node *head){ - if(head->next == NULL || head == NULL){ - return head; - } - node *slow = head; - node *fast = head->next; - while(fast != NULL && fast->next != NULL){ - fast = fast->next->next; - slow = slow->next; - } - return slow; -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -node* merge_two_lists(node *a, node *b){ - if(a == NULL){ - return b; - } - else if(b == NULL){ - return a; - } - node *c = NULL; - if(a->data < b->data){ - c = a; - c->next = merge_two_lists(a->next, b); - } - else{ - c = b; - c->next = merge_two_lists(a, b->next); - } - return c; -} -node* mergeSort(node* head){ - if(head == NULL || head->next == NULL){ - return head; - } - node *mid = compute_midpoint(head); - node *a = head; - node *b = mid->next; - mid->next = NULL; - a = mergeSort(a); - b = mergeSort(b); - node *c = merge_two_lists(a, b); - return c; -} -int main(){ - node *head = NULL; - node *head2 = NULL; - cin >> head; - cout << head << endl; - node *x = mergeSort(head); - cout << x << endl; - return 0; +// MergeSort an unsorted LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +node* compute_midpoint(node *head){ + if(head->next == NULL || head == NULL){ + return head; + } + node *slow = head; + node *fast = head->next; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + } + return slow; +} +istream& operator>>(istream &is, node *&head){ + makeLinkedList(head); + return is; +} +ostream& operator<<(ostream &os, node *&head){ + print_linked_list(head); + return os; +} +node* merge_two_lists(node *a, node *b){ + if(a == NULL){ + return b; + } + else if(b == NULL){ + return a; + } + node *c = NULL; + if(a->data < b->data){ + c = a; + c->next = merge_two_lists(a->next, b); + } + else{ + c = b; + c->next = merge_two_lists(a, b->next); + } + return c; +} +node* mergeSort(node* head){ + if(head == NULL || head->next == NULL){ + return head; + } + node *mid = compute_midpoint(head); + node *a = head; + node *b = mid->next; + mid->next = NULL; + a = mergeSort(a); + b = mergeSort(b); + node *c = merge_two_lists(a, b); + return c; +} +int main(){ + node *head = NULL; + node *head2 = NULL; + cin >> head; + cout << head << endl; + node *x = mergeSort(head); + cout << x << endl; + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_odd_even.cpp b/Linked List/linked_list_odd_even.cpp similarity index 95% rename from Linked_List/linked_list_odd_even.cpp rename to Linked List/linked_list_odd_even.cpp index dccf988e..eca1423d 100644 --- a/Linked_List/linked_list_odd_even.cpp +++ b/Linked List/linked_list_odd_even.cpp @@ -1,64 +1,64 @@ -// OddEven LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - cout << endl; - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* oddEvenLinkedList(node *head){ - if(head == NULL || head->next == NULL){ - return head; - } - node *odd = head; - node *even = head->next; - node *evenhead = even; - while(even != NULL && even->next != NULL){ - odd->next = even->next; - odd = odd->next; - even->next = odd->next; - even = even->next; - } - odd->next = evenhead; - return head; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - oddEvenLinkedList(head); - print_linked_list(head); - return 0; +// OddEven LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + cout << endl; + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +node* oddEvenLinkedList(node *head){ + if(head == NULL || head->next == NULL){ + return head; + } + node *odd = head; + node *even = head->next; + node *evenhead = even; + while(even != NULL && even->next != NULL){ + odd->next = even->next; + odd = odd->next; + even->next = odd->next; + even = even->next; + } + odd->next = evenhead; + return head; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + oddEvenLinkedList(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_recursive_search.cpp b/Linked List/linked_list_recursive_search.cpp similarity index 95% rename from Linked_List/linked_list_recursive_search.cpp rename to Linked List/linked_list_recursive_search.cpp index ebf8cc9d..39c1cce8 100644 --- a/Linked_List/linked_list_recursive_search.cpp +++ b/Linked List/linked_list_recursive_search.cpp @@ -1,51 +1,51 @@ -// Search recursively in a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -bool recursive_search(node *head, int key){ - if(head == NULL){ - return false; - } - if(head->data == key){ - return true; - } - else{ - recursive_search(head->next, key); - } -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - cout << endl; - if(recursive_search(head, 3)){ - cout << "Found"; - } - else{ - cout << "Not Found"; - } - return 0; +// Search recursively in a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +bool recursive_search(node *head, int key){ + if(head == NULL){ + return false; + } + if(head->data == key){ + return true; + } + else{ + recursive_search(head->next, key); + } +} +void insert_at_head(node *&head, int data){ + node *n = new node(data); + n->next = head; + head = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +int main(){ + node *head = NULL; + insert_at_head(head, 1); + insert_at_head(head, 2); + insert_at_head(head, 3); + print_linked_list(head); + cout << endl; + if(recursive_search(head, 3)){ + cout << "Found"; + } + else{ + cout << "Not Found"; + } + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_remove_dups.cpp b/Linked List/linked_list_remove_dups.cpp similarity index 95% rename from Linked_List/linked_list_remove_dups.cpp rename to Linked List/linked_list_remove_dups.cpp index ab0ae0ec..a00d3343 100644 --- a/Linked_List/linked_list_remove_dups.cpp +++ b/Linked List/linked_list_remove_dups.cpp @@ -1,91 +1,91 @@ -// Remove duplicates from an unsorted linked list -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class Node{ - public: - int data; - Node *next; - - Node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(Node *&head, int data){ - if(head == NULL){ - head = new Node(data); - return; - } - Node *n = new Node(data); - Node *temp = head; - while(temp->next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(Node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void make_linked_list(Node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -void remove_duplicates(Node *&head){ - set S; - Node *temp = head; - Node *prev = NULL; - Node *remove = NULL; - while(temp != NULL){ - if(S.find(temp->data) != S.end()){ - remove = temp; - prev->next = temp->next; - } - else{ - S.insert(temp->data); - prev = temp; - } - temp = temp->next; - delete remove; - } -} -void remove_duplicates_without_buffer(Node *&head){ - Node *current = head; - Node *remove = NULL; - while(current != NULL){ - Node *runner = current; - while(runner->next != NULL){ - if(runner->next->data == current->data){ - remove = runner->next; - runner->next = runner->next->next; - delete remove; - } - else{ - runner = runner->next; - } - } - current = current->next; - } -} -int main(){ - Node *head = NULL; - /* - make_linked_list(head); - print_linked_list(head); - cout << endl; - remove_duplicates(head); - print_linked_list(head); - */ - make_linked_list(head); - print_linked_list(head); - cout << endl; - remove_duplicates_without_buffer(head); - print_linked_list(head); +// Remove duplicates from an unsorted linked list +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class Node{ + public: + int data; + Node *next; + + Node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(Node *&head, int data){ + if(head == NULL){ + head = new Node(data); + return; + } + Node *n = new Node(data); + Node *temp = head; + while(temp->next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(Node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void make_linked_list(Node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +void remove_duplicates(Node *&head){ + set S; + Node *temp = head; + Node *prev = NULL; + Node *remove = NULL; + while(temp != NULL){ + if(S.find(temp->data) != S.end()){ + remove = temp; + prev->next = temp->next; + } + else{ + S.insert(temp->data); + prev = temp; + } + temp = temp->next; + delete remove; + } +} +void remove_duplicates_without_buffer(Node *&head){ + Node *current = head; + Node *remove = NULL; + while(current != NULL){ + Node *runner = current; + while(runner->next != NULL){ + if(runner->next->data == current->data){ + remove = runner->next; + runner->next = runner->next->next; + delete remove; + } + else{ + runner = runner->next; + } + } + current = current->next; + } +} +int main(){ + Node *head = NULL; + /* + make_linked_list(head); + print_linked_list(head); + cout << endl; + remove_duplicates(head); + print_linked_list(head); + */ + make_linked_list(head); + print_linked_list(head); + cout << endl; + remove_duplicates_without_buffer(head); + print_linked_list(head); } \ No newline at end of file diff --git a/Linked_List/linked_list_reverse.cpp b/Linked List/linked_list_reverse.cpp similarity index 95% rename from Linked_List/linked_list_reverse.cpp rename to Linked List/linked_list_reverse.cpp index 25305aa0..ee05d3fe 100644 --- a/Linked_List/linked_list_reverse.cpp +++ b/Linked List/linked_list_reverse.cpp @@ -1,61 +1,61 @@ -// Reverse a linkedlist iteratively -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -void reverse_linked_list(node *&head){ - node *current = head; - node *next = NULL; - node *prev = NULL; - while(current != NULL){ - next = current->next; - current->next = prev; - prev = current; - current = next; - } - head = prev; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - cout << endl; - reverse_linked_list(head); - print_linked_list(head); - return 0; +// Reverse a linkedlist iteratively +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +void reverse_linked_list(node *&head){ + node *current = head; + node *next = NULL; + node *prev = NULL; + while(current != NULL){ + next = current->next; + current->next = prev; + prev = current; + current = next; + } + head = prev; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + cout << endl; + reverse_linked_list(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_reverse_recursive.cpp b/Linked List/linked_list_reverse_recursive.cpp similarity index 95% rename from Linked_List/linked_list_reverse_recursive.cpp rename to Linked List/linked_list_reverse_recursive.cpp index 5ff12cb3..8375bfa6 100644 --- a/Linked_List/linked_list_reverse_recursive.cpp +++ b/Linked List/linked_list_reverse_recursive.cpp @@ -1,60 +1,60 @@ -// Reverse a linkedlist recursively -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} - -node* recursive_reverse(node *head){ - if(head->next == NULL || head == NULL){ - return head; - } - node *mini_head = recursive_reverse(head->next); - node *current = head; - current->next->next = current; - current->next = NULL; - return mini_head; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - cout << endl; - head = recursive_reverse(head); - print_linked_list(head); - return 0; +// Reverse a linkedlist recursively +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} + +node* recursive_reverse(node *head){ + if(head->next == NULL || head == NULL){ + return head; + } + node *mini_head = recursive_reverse(head->next); + node *current = head; + current->next->next = current; + current->next = NULL; + return mini_head; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + cout << endl; + head = recursive_reverse(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_swap_nodes_in_pair.cpp b/Linked List/linked_list_swap_nodes_in_pair.cpp similarity index 95% rename from Linked_List/linked_list_swap_nodes_in_pair.cpp rename to Linked List/linked_list_swap_nodes_in_pair.cpp index 39cbc3e5..669175cc 100644 --- a/Linked_List/linked_list_swap_nodes_in_pair.cpp +++ b/Linked List/linked_list_swap_nodes_in_pair.cpp @@ -1,58 +1,58 @@ -// Swap adjacant Nodes in pair Recursive -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - cout << endl; - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* swapNodesInPairRecursive(node *head){ - if(head == NULL || head->next == NULL){ - return head; - } - node *newHead = swapNodesInPairRecursive(head->next->next); - node *temp = head->next; - temp->next = head; - head->next = newHead; - return temp; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - head = swapNodesInPairRecursive(head); - print_linked_list(head); - return 0; +// Swap adjacant Nodes in pair Recursive +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + cout << endl; + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +node* swapNodesInPairRecursive(node *head){ + if(head == NULL || head->next == NULL){ + return head; + } + node *newHead = swapNodesInPairRecursive(head->next->next); + node *temp = head->next; + temp->next = head; + head->next = newHead; + return temp; +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + head = swapNodesInPairRecursive(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_swap_nodes_in_pair_iterative.cpp b/Linked List/linked_list_swap_nodes_in_pair_iterative.cpp similarity index 95% rename from Linked_List/linked_list_swap_nodes_in_pair_iterative.cpp rename to Linked List/linked_list_swap_nodes_in_pair_iterative.cpp index 88d1efa4..c9e3b332 100644 --- a/Linked_List/linked_list_swap_nodes_in_pair_iterative.cpp +++ b/Linked List/linked_list_swap_nodes_in_pair_iterative.cpp @@ -1,69 +1,69 @@ -// Swap adjacant Nodes in Pair Iterative -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - cout << endl; - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} - -node* swapNodesInPairIterative(node *head){ - node *dummy = new node(0); - node *prev = dummy; - node *curr = head; - node *second = NULL; - node *nextPair = NULL; - while(curr && curr->next){ - nextPair = curr->next->next; - second = curr->next; - - second->next = curr; - curr->next = nextPair; - prev->next = second; - - prev = curr; - curr = nextPair; - } - return dummy->next; - -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - head = swapNodesInPairIterative(head); - print_linked_list(head); - return 0; +// Swap adjacant Nodes in Pair Iterative +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + cout << endl; + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} + +node* swapNodesInPairIterative(node *head){ + node *dummy = new node(0); + node *prev = dummy; + node *curr = head; + node *second = NULL; + node *nextPair = NULL; + while(curr && curr->next){ + nextPair = curr->next->next; + second = curr->next; + + second->next = curr; + curr->next = nextPair; + prev->next = second; + + prev = curr; + curr = nextPair; + } + return dummy->next; + +} +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + head = swapNodesInPairIterative(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_take_input.cpp b/Linked List/linked_list_take_input.cpp similarity index 95% rename from Linked_List/linked_list_take_input.cpp rename to Linked List/linked_list_take_input.cpp index e8c85807..ef47f964 100644 --- a/Linked_List/linked_list_take_input.cpp +++ b/Linked List/linked_list_take_input.cpp @@ -1,47 +1,47 @@ -// Finding Midpoint of a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - cout << endl; - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} - -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - return 0; +// Finding Midpoint of a LinkedList +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + node(int d){ + data = d; + next = NULL; + } +}; +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + cout << endl; + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} + +int main(){ + node *head = NULL; + makeLinkedList(head); + print_linked_list(head); + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_take_input_as_array_operator_overloading.cpp b/Linked List/linked_list_take_input_as_array_operator_overloading.cpp similarity index 95% rename from Linked_List/linked_list_take_input_as_array_operator_overloading.cpp rename to Linked List/linked_list_take_input_as_array_operator_overloading.cpp index ef989709..6caf8eab 100644 --- a/Linked_List/linked_list_take_input_as_array_operator_overloading.cpp +++ b/Linked List/linked_list_take_input_as_array_operator_overloading.cpp @@ -1,66 +1,66 @@ -// Take Input in a LinkedList as an array with "Operator overloading" -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -int main(){ - - int n; - cin >> n; - node *arr[n]; - for(int i = 0; i < n; i++){ - arr[i] = NULL; - } - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - cout << endl; - for(int i = 0; i < n; i++){ - cout << arr[i] << endl;; - } - return 0; +// Take Input in a LinkedList as an array with "Operator overloading" +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +istream& operator>>(istream &is, node *&head){ + makeLinkedList(head); + return is; +} +ostream& operator<<(ostream &os, node *&head){ + print_linked_list(head); + return os; +} +int main(){ + + int n; + cin >> n; + node *arr[n]; + for(int i = 0; i < n; i++){ + arr[i] = NULL; + } + for(int i = 0; i < n; i++){ + cin >> arr[i]; + } + cout << endl; + for(int i = 0; i < n; i++){ + cout << arr[i] << endl;; + } + return 0; } \ No newline at end of file diff --git a/Linked_List/linked_list_take_input_operator_overloading.cpp b/Linked List/linked_list_take_input_operator_overloading.cpp similarity index 95% rename from Linked_List/linked_list_take_input_operator_overloading.cpp rename to Linked List/linked_list_take_input_operator_overloading.cpp index 1bece2f1..3115b970 100644 --- a/Linked_List/linked_list_take_input_operator_overloading.cpp +++ b/Linked List/linked_list_take_input_operator_overloading.cpp @@ -1,70 +1,70 @@ -// Take Input in a LinkedList with "Operator overloading" -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -int main(){ - /*node *head = NULL; - node *head2 = NULL; - cin >> head >> head2; - cout << head << endl << head2; - */ - int n; - cin >> n; - node *arr[n]; - for(int i = 0; i < n; i++){ - arr[i] = NULL; - } - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - cout << endl; - for(int i = 0; i < n; i++){ - cout << arr[i] << endl;; - } - return 0; +// Take Input in a LinkedList with "Operator overloading" +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +class node{ + public: + int data; + node* next; + + node(int d){ + data = d; + next = NULL; + } +}; + +void insert_at_tail(node *&head, int data){ + if(head == NULL){ + head = new node(data); + return; + } + node *n = new node(data); + node * temp = head; + while(temp -> next != NULL){ + temp = temp->next; + } + temp->next = n; +} +void print_linked_list(node *head){ + while(head != NULL){ + cout << head->data << "->"; + head = head->next; + } +} +void makeLinkedList(node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_tail(head, data); + cin >> data; + } +} +istream& operator>>(istream &is, node *&head){ + makeLinkedList(head); + return is; +} +ostream& operator<<(ostream &os, node *&head){ + print_linked_list(head); + return os; +} +int main(){ + /*node *head = NULL; + node *head2 = NULL; + cin >> head >> head2; + cout << head << endl << head2; + */ + int n; + cin >> n; + node *arr[n]; + for(int i = 0; i < n; i++){ + arr[i] = NULL; + } + for(int i = 0; i < n; i++){ + cin >> arr[i]; + } + cout << endl; + for(int i = 0; i < n; i++){ + cout << arr[i] << endl;; + } + return 0; } \ No newline at end of file diff --git a/Linked_List/sll.go b/Linked List/sll.go similarity index 100% rename from Linked_List/sll.go rename to Linked List/sll.go diff --git a/Linked_List/sort_linked_list.cpp b/Linked List/sort_linked_list.cpp similarity index 100% rename from Linked_List/sort_linked_list.cpp rename to Linked List/sort_linked_list.cpp diff --git a/Linked_List/tempCodeRunnerFile.cpp b/Linked List/tempCodeRunnerFile.cpp similarity index 96% rename from Linked_List/tempCodeRunnerFile.cpp rename to Linked List/tempCodeRunnerFile.cpp index 766f4d7b..0d12bb3c 100644 --- a/Linked_List/tempCodeRunnerFile.cpp +++ b/Linked List/tempCodeRunnerFile.cpp @@ -1 +1 @@ - print_linked_list(head); + print_linked_list(head); diff --git a/Random_Problems/bubble_sort_recursive.cpp b/Random Problems/bubble_sort_recursive.cpp similarity index 97% rename from Random_Problems/bubble_sort_recursive.cpp rename to Random Problems/bubble_sort_recursive.cpp index bea86c51..6dd79965 100644 --- a/Random_Problems/bubble_sort_recursive.cpp +++ b/Random Problems/bubble_sort_recursive.cpp @@ -1,34 +1,34 @@ -// Implementation of Recursive Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort - -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case - -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -void bubble_sort(int *A, int len){ - if(len == 1) - return; - for(int i = 0; i < len - 1; i++){ - if(A[i] > A[i+1]){ - swap(A[i], A[i+1]); - } - } - bubble_sort(A, len-1); -} -int main(){ - int A[] = {5, 4, 3, 2, 1, 7}; - int len = sizeof(A) / sizeof(int); - bubble_sort(A, len); - for(int x : A){ - cout << x << " "; - } - return 0; +// Implementation of Recursive Bubble sort. +// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm +// that repeatedly steps through the input list element by element, +// comparing the current element with the one after it, swapping their values if needed. +// These passes through the list are repeated until no swaps had to be performed during a pass, +// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort + +// Time Complexity worst-case and average complexity O(n^{2}) +// Bubble sort is O(n) on a list that is already sorted i.e. Best case + +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +void bubble_sort(int *A, int len){ + if(len == 1) + return; + for(int i = 0; i < len - 1; i++){ + if(A[i] > A[i+1]){ + swap(A[i], A[i+1]); + } + } + bubble_sort(A, len-1); +} +int main(){ + int A[] = {5, 4, 3, 2, 1, 7}; + int len = sizeof(A) / sizeof(int); + bubble_sort(A, len); + for(int x : A){ + cout << x << " "; + } + return 0; } \ No newline at end of file diff --git a/Random_Problems/check_permutations.cpp b/Random Problems/check_permutations.cpp similarity index 96% rename from Random_Problems/check_permutations.cpp rename to Random Problems/check_permutations.cpp index 05f794f3..1223ec08 100644 --- a/Random_Problems/check_permutations.cpp +++ b/Random Problems/check_permutations.cpp @@ -1,30 +1,30 @@ -// Check if a string is a permutation of other -#include -using namespace std; -bool check_permutations(string a, string b){ - vector Freq(26, 0); - for(int i = 0; i < a.length(); i++){ - Freq[a[i] - 'a']++; - } - for(int x : Freq) cout << x << ","; - cout << endl; - for(int i = 0; i < b.length(); i++){ - if(Freq[b[i] - 'a'] > 0) - Freq[b[i] - 'a']--; - else - Freq[b[i] - 'a']++; - } - for(int x : Freq) cout << x << ","; - cout << endl; - int res = accumulate(Freq.begin(), Freq.end(), 0); - return res == 0 ? true : false; -} -int main(){ - string a, b; - cin >> a >> b; - if(check_permutations(a, b)) - cout << "TRUE"; - else - cout << "FALSE"; - return 0; +// Check if a string is a permutation of other +#include +using namespace std; +bool check_permutations(string a, string b){ + vector Freq(26, 0); + for(int i = 0; i < a.length(); i++){ + Freq[a[i] - 'a']++; + } + for(int x : Freq) cout << x << ","; + cout << endl; + for(int i = 0; i < b.length(); i++){ + if(Freq[b[i] - 'a'] > 0) + Freq[b[i] - 'a']--; + else + Freq[b[i] - 'a']++; + } + for(int x : Freq) cout << x << ","; + cout << endl; + int res = accumulate(Freq.begin(), Freq.end(), 0); + return res == 0 ? true : false; +} +int main(){ + string a, b; + cin >> a >> b; + if(check_permutations(a, b)) + cout << "TRUE"; + else + cout << "FALSE"; + return 0; } \ No newline at end of file diff --git a/Random_Problems/linear_search_string.cpp b/Random Problems/linear_search_string.cpp similarity index 95% rename from Random_Problems/linear_search_string.cpp rename to Random Problems/linear_search_string.cpp index 282f5f17..83b43947 100644 --- a/Random_Problems/linear_search_string.cpp +++ b/Random Problems/linear_search_string.cpp @@ -1,25 +1,25 @@ -// Linear search in an array of strings -#include -using namespace std; -int main(){ - char a[10][100]; - int n; - cin >> n; - cin.ignore(); - for(int i = 0 ; i < n; i++){ - cin.getline(a[i], 100); - } - char key[100]; - cout << "Enter string to search : "; - cin.getline(key, 100); - int i = 0; - for(i = 0; i < n; i++){ - if(strcmp(key, a[i]) == 0){ - cout << "Found at index : " << i; - break; - } - } - if(i == n) - cout << "Not Found" < +using namespace std; +int main(){ + char a[10][100]; + int n; + cin >> n; + cin.ignore(); + for(int i = 0 ; i < n; i++){ + cin.getline(a[i], 100); + } + char key[100]; + cout << "Enter string to search : "; + cin.getline(key, 100); + int i = 0; + for(i = 0; i < n; i++){ + if(strcmp(key, a[i]) == 0){ + cout << "Found at index : " << i; + break; + } + } + if(i == n) + cout << "Not Found" < -using namespace std; -int main(){ - int Mat[10][10], R, C, value = 1; - cin >> R >> C; - // creating matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - Mat[i][j] = value++; - } - } - // Transposing matrix - for(int i = 0; i < R; i++){ - for(int j = i + 1; j < C; j++){ - swap(Mat[i][j], Mat[j][i]); - } - } - //Rotate matrix 90 degrees anti clockwise - for(int i = 0; i < R; i++){ - int start = 0; - int end = C-1; - while(start < end){ - swap(Mat[start][i], Mat[end][i]); - start++; - end--; - } - } - // Display matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - return 0; +#include +using namespace std; +int main(){ + int Mat[10][10], R, C, value = 1; + cin >> R >> C; + // creating matrix + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + Mat[i][j] = value++; + } + } + // Transposing matrix + for(int i = 0; i < R; i++){ + for(int j = i + 1; j < C; j++){ + swap(Mat[i][j], Mat[j][i]); + } + } + //Rotate matrix 90 degrees anti clockwise + for(int i = 0; i < R; i++){ + int start = 0; + int end = C-1; + while(start < end){ + swap(Mat[start][i], Mat[end][i]); + start++; + end--; + } + } + // Display matrix + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cout << Mat[i][j] << " "; + } + cout << endl; + } + return 0; } \ No newline at end of file diff --git a/Random_Problems/matrix_rotate_90_clockwise.cpp b/Random Problems/matrix_rotate_90_clockwise.cpp similarity index 96% rename from Random_Problems/matrix_rotate_90_clockwise.cpp rename to Random Problems/matrix_rotate_90_clockwise.cpp index 47709a32..cb300cbd 100644 --- a/Random_Problems/matrix_rotate_90_clockwise.cpp +++ b/Random Problems/matrix_rotate_90_clockwise.cpp @@ -1,36 +1,36 @@ -#include -using namespace std; -int main(){ - int Mat[10][10], R, C, value = 1; - cin >> R >> C; - // creating matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - Mat[i][j] = value++; - } - } - // Transposing matrix - for(int i = 0; i < R; i++){ - for(int j = i + 1; j < C; j++){ - swap(Mat[i][j], Mat[j][i]); - } - } - //Rotate matrix 90 degrees clockwise - for(int i = 0; i < R; i++){ - int start = 0; - int end = C-1; - while(start < end){ - swap(Mat[i][start], Mat[i][end]); - start++; - end--; - } - } - // Display matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - return 0; +#include +using namespace std; +int main(){ + int Mat[10][10], R, C, value = 1; + cin >> R >> C; + // creating matrix + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + Mat[i][j] = value++; + } + } + // Transposing matrix + for(int i = 0; i < R; i++){ + for(int j = i + 1; j < C; j++){ + swap(Mat[i][j], Mat[j][i]); + } + } + //Rotate matrix 90 degrees clockwise + for(int i = 0; i < R; i++){ + int start = 0; + int end = C-1; + while(start < end){ + swap(Mat[i][start], Mat[i][end]); + start++; + end--; + } + } + // Display matrix + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cout << Mat[i][j] << " "; + } + cout << endl; + } + return 0; } \ No newline at end of file diff --git a/Random_Problems/matrix_search_in_sorted_mat.cpp b/Random Problems/matrix_search_in_sorted_mat.cpp similarity index 96% rename from Random_Problems/matrix_search_in_sorted_mat.cpp rename to Random Problems/matrix_search_in_sorted_mat.cpp index cf034b43..a28ef305 100644 --- a/Random_Problems/matrix_search_in_sorted_mat.cpp +++ b/Random Problems/matrix_search_in_sorted_mat.cpp @@ -1,37 +1,37 @@ -// Search in a rowwise/colwise sorted matrix O(n + m) -#include -using namespace std; -bool search_in_sorted_mat(int Mat[][10], int R, int C, int key){ - int i = 0, flag = 0, j = C-1; - while(j >= 0 && i < R){ - if(Mat[i][j] == key){ - cout << "Found at position " << i << " " << j << endl; - flag = 1; - break; - } - else if(Mat[i][j] < key) - i++; - else if(Mat[i][j] > key){ - j--; - } - } - return flag == 1 ? true : false; -} -int main(){ - int Mat[10][10], R, C; - cin >> R >> C; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> Mat[i][j]; - } - } - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - int key; - cin >> key; - cout << search_in_sorted_mat(Mat, R, C, key); +// Search in a rowwise/colwise sorted matrix O(n + m) +#include +using namespace std; +bool search_in_sorted_mat(int Mat[][10], int R, int C, int key){ + int i = 0, flag = 0, j = C-1; + while(j >= 0 && i < R){ + if(Mat[i][j] == key){ + cout << "Found at position " << i << " " << j << endl; + flag = 1; + break; + } + else if(Mat[i][j] < key) + i++; + else if(Mat[i][j] > key){ + j--; + } + } + return flag == 1 ? true : false; +} +int main(){ + int Mat[10][10], R, C; + cin >> R >> C; + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cin >> Mat[i][j]; + } + } + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cout << Mat[i][j] << " "; + } + cout << endl; + } + int key; + cin >> key; + cout << search_in_sorted_mat(Mat, R, C, key); } \ No newline at end of file diff --git a/Random_Problems/matrix_spiral_print.cpp b/Random Problems/matrix_spiral_print.cpp similarity index 96% rename from Random_Problems/matrix_spiral_print.cpp rename to Random Problems/matrix_spiral_print.cpp index 185d237d..41241c72 100644 --- a/Random_Problems/matrix_spiral_print.cpp +++ b/Random Problems/matrix_spiral_print.cpp @@ -1,49 +1,49 @@ -// Printing Matrix in spiral order -#include -using namespace std; -void print_spiral(int Mat[][10], int R, int C){ - int startRow = 0, endRow = R-1, startCol = 0, endCol = C-1; - while(startRow <= endRow && startCol <= endCol){ - // Print first row - for(int i = startCol; i <= endCol; i++){ - cout << Mat[startRow][i]; - } - startRow++; - // print end col - for(int i = startRow; i <= endRow; i++){ - cout << Mat[i][endCol]; - } - endCol--; - // Print end row - if(endRow > startRow){ - for(int i = endCol; i >= startCol; i--){ - cout << Mat[endRow][i]; - } - endRow--; - } - // print start row - if(startCol < endCol){ - for(int i = endRow; i >= startRow; i--){ - cout << Mat[i][startCol]; - } - startCol++; - } - } -} -int main(){ - int Mat[10][10], R, C; - cin >> R >> C; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> Mat[i][j]; - } - } - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - print_spiral(Mat, R, C); - return 0; +// Printing Matrix in spiral order +#include +using namespace std; +void print_spiral(int Mat[][10], int R, int C){ + int startRow = 0, endRow = R-1, startCol = 0, endCol = C-1; + while(startRow <= endRow && startCol <= endCol){ + // Print first row + for(int i = startCol; i <= endCol; i++){ + cout << Mat[startRow][i]; + } + startRow++; + // print end col + for(int i = startRow; i <= endRow; i++){ + cout << Mat[i][endCol]; + } + endCol--; + // Print end row + if(endRow > startRow){ + for(int i = endCol; i >= startCol; i--){ + cout << Mat[endRow][i]; + } + endRow--; + } + // print start row + if(startCol < endCol){ + for(int i = endRow; i >= startRow; i--){ + cout << Mat[i][startCol]; + } + startCol++; + } + } +} +int main(){ + int Mat[10][10], R, C; + cin >> R >> C; + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cin >> Mat[i][j]; + } + } + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cout << Mat[i][j] << " "; + } + cout << endl; + } + print_spiral(Mat, R, C); + return 0; } \ No newline at end of file diff --git a/Random_Problems/matrix_wave_print.cpp b/Random Problems/matrix_wave_print.cpp similarity index 95% rename from Random_Problems/matrix_wave_print.cpp rename to Random Problems/matrix_wave_print.cpp index a71a4d16..8092e35d 100644 --- a/Random_Problems/matrix_wave_print.cpp +++ b/Random Problems/matrix_wave_print.cpp @@ -1,33 +1,33 @@ -// Prints a matrix in wave form -#include -using namespace std; -void wave_print(int Mat[][10], int R, int C){ - for(int j = 0; j < C; j++){ - if(j & 1){ - for(int i = R - 1; i >= 0; i--){ - cout << Mat[i][j] << " "; - } - } - else{ - for(int i = 0; i < R; i++){ - cout << Mat[i][j] << " "; - } - } - } -} -int main(){ - int Mat[10][10], R, C; - cin >> R >> C; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> Mat[i][j]; - } - } - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - wave_print(Mat, R, C); +// Prints a matrix in wave form +#include +using namespace std; +void wave_print(int Mat[][10], int R, int C){ + for(int j = 0; j < C; j++){ + if(j & 1){ + for(int i = R - 1; i >= 0; i--){ + cout << Mat[i][j] << " "; + } + } + else{ + for(int i = 0; i < R; i++){ + cout << Mat[i][j] << " "; + } + } + } +} +int main(){ + int Mat[10][10], R, C; + cin >> R >> C; + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cin >> Mat[i][j]; + } + } + for(int i = 0; i < R; i++){ + for(int j = 0; j < C; j++){ + cout << Mat[i][j] << " "; + } + cout << endl; + } + wave_print(Mat, R, C); } \ No newline at end of file diff --git a/Random_Problems/maximum_subarray.cpp b/Random Problems/maximum_subarray.cpp similarity index 96% rename from Random_Problems/maximum_subarray.cpp rename to Random Problems/maximum_subarray.cpp index 44e3670f..4f143c55 100644 --- a/Random_Problems/maximum_subarray.cpp +++ b/Random Problems/maximum_subarray.cpp @@ -1,31 +1,31 @@ -// Subarray with maximum sum O(n^3) -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int current_sum = 0, left = 0, right = 0; - int maximum_sum = INT_MIN; - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - current_sum = 0; - for(int k = i; k <= j; k++){ - current_sum += V[k]; - } - if(current_sum > maximum_sum){ - maximum_sum = current_sum; - left = i; - right = j; - } - //maximum_sum = max(maximum_sum, current_sum); - } - } - cout << maximum_sum << endl; - for(int i = left; i <= right; i++) - cout << V[i]; - return 0; +// Subarray with maximum sum O(n^3) +#include +using namespace std; +int main(){ + int n; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + int current_sum = 0, left = 0, right = 0; + int maximum_sum = INT_MIN; + for(int i = 0; i < n; i++){ + for(int j = i; j < n; j++){ + current_sum = 0; + for(int k = i; k <= j; k++){ + current_sum += V[k]; + } + if(current_sum > maximum_sum){ + maximum_sum = current_sum; + left = i; + right = j; + } + //maximum_sum = max(maximum_sum, current_sum); + } + } + cout << maximum_sum << endl; + for(int i = left; i <= right; i++) + cout << V[i]; + return 0; } \ No newline at end of file diff --git a/Random_Problems/maximum_subarray_cumulative.cpp b/Random Problems/maximum_subarray_cumulative.cpp similarity index 96% rename from Random_Problems/maximum_subarray_cumulative.cpp rename to Random Problems/maximum_subarray_cumulative.cpp index 607d0e37..d6d1b295 100644 --- a/Random_Problems/maximum_subarray_cumulative.cpp +++ b/Random Problems/maximum_subarray_cumulative.cpp @@ -1,36 +1,36 @@ -// Subarray with maximum sum using cumulative sum O(n^2) -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - vector W(n); - for(int i = 0; i < n; i++) W[i] = 0; - cin >> V[0]; - W[0] = V[0]; - for(int i = 1; i < n; i++){ - cin >> V[i]; - W[i] = W[i-1] + V[i]; - } - for(int i = 0; i < n; i++) cout << W[i] << " "; - cout << endl; - int current_sum = 0, left = 0, right = 0; - int maximum_sum = INT_MIN; - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - current_sum = 0; - current_sum = W[j] - W[i - 1]; - if(current_sum > maximum_sum){ - maximum_sum = current_sum; - left = i; - right = j; - } - //maximum_sum = max(maximum_sum, current_sum); - } - } - cout << maximum_sum << endl; - for(int i = left; i <= right; i++) - cout << V[i]; - return 0; +// Subarray with maximum sum using cumulative sum O(n^2) +#include +using namespace std; +int main(){ + int n; + cin >> n; + vector V(n); + vector W(n); + for(int i = 0; i < n; i++) W[i] = 0; + cin >> V[0]; + W[0] = V[0]; + for(int i = 1; i < n; i++){ + cin >> V[i]; + W[i] = W[i-1] + V[i]; + } + for(int i = 0; i < n; i++) cout << W[i] << " "; + cout << endl; + int current_sum = 0, left = 0, right = 0; + int maximum_sum = INT_MIN; + for(int i = 0; i < n; i++){ + for(int j = i; j < n; j++){ + current_sum = 0; + current_sum = W[j] - W[i - 1]; + if(current_sum > maximum_sum){ + maximum_sum = current_sum; + left = i; + right = j; + } + //maximum_sum = max(maximum_sum, current_sum); + } + } + cout << maximum_sum << endl; + for(int i = left; i <= right; i++) + cout << V[i]; + return 0; } \ No newline at end of file diff --git a/Random_Problems/maximum_subarray_kadanes.cpp b/Random Problems/maximum_subarray_kadanes.cpp similarity index 97% rename from Random_Problems/maximum_subarray_kadanes.cpp rename to Random Problems/maximum_subarray_kadanes.cpp index d50b768a..ecd54587 100644 --- a/Random_Problems/maximum_subarray_kadanes.cpp +++ b/Random Problems/maximum_subarray_kadanes.cpp @@ -1,22 +1,22 @@ -// In computer science, the maximum sum subarray problem, also known as the maximum segment sum problem, -// is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers -// Subarray with maximum sum using kadane's algo O(n) -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int curr_sum = 0; - int max_sum_so_far = INT_MIN; - for(int x : V){ - curr_sum += x; - max_sum_so_far = max(curr_sum, max_sum_so_far); - curr_sum = max(curr_sum, 0); - } - cout << max_sum_so_far; - return 0; +// In computer science, the maximum sum subarray problem, also known as the maximum segment sum problem, +// is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers +// Subarray with maximum sum using kadane's algo O(n) +#include +using namespace std; +int main(){ + int n; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + int curr_sum = 0; + int max_sum_so_far = INT_MIN; + for(int x : V){ + curr_sum += x; + max_sum_so_far = max(curr_sum, max_sum_so_far); + curr_sum = max(curr_sum, 0); + } + cout << max_sum_so_far; + return 0; } \ No newline at end of file diff --git a/Random_Problems/move_zeros.cpp b/Random Problems/move_zeros.cpp similarity index 95% rename from Random_Problems/move_zeros.cpp rename to Random Problems/move_zeros.cpp index 7d59fc85..8b7a9c06 100644 --- a/Random_Problems/move_zeros.cpp +++ b/Random Problems/move_zeros.cpp @@ -1,28 +1,28 @@ -// Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. -// Input : [1, 0, 0, 4, 3] -// Output : [1, 4, 3, 0, 0] -#include -using namespace std; - -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int x = 0; - for(int i = 0; i < n; i++){ - if(V[i] != 0){ - V[x] = V[i]; - x++; - } - } - for(int i = x; i < n; i++){ - V[i] = 0; - } - for(int i = 0; i < n; i++){ - cout << V[i] << " "; - } - return 0; +// Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. +// Input : [1, 0, 0, 4, 3] +// Output : [1, 4, 3, 0, 0] +#include +using namespace std; + +int main(){ + int n; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + int x = 0; + for(int i = 0; i < n; i++){ + if(V[i] != 0){ + V[x] = V[i]; + x++; + } + } + for(int i = x; i < n; i++){ + V[i] = 0; + } + for(int i = 0; i < n; i++){ + cout << V[i] << " "; + } + return 0; } \ No newline at end of file diff --git a/Random_Problems/printing_all_subarrays.cpp b/Random Problems/printing_all_subarrays.cpp similarity index 95% rename from Random_Problems/printing_all_subarrays.cpp rename to Random Problems/printing_all_subarrays.cpp index 5556dc2d..5fc18e33 100644 --- a/Random_Problems/printing_all_subarrays.cpp +++ b/Random Problems/printing_all_subarrays.cpp @@ -1,19 +1,19 @@ -// Printing all subarrays of an array -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - for(int k = i; k <= j; k++){ - cout << V[k] << ","; - } - cout << endl; - } - } +// Printing all subarrays of an array +#include +using namespace std; +int main(){ + int n; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + for(int i = 0; i < n; i++){ + for(int j = i; j < n; j++){ + for(int k = i; k <= j; k++){ + cout << V[k] << ","; + } + cout << endl; + } + } } \ No newline at end of file diff --git a/Random_Problems/rev_string.go b/Random Problems/rev_string.go similarity index 94% rename from Random_Problems/rev_string.go rename to Random Problems/rev_string.go index 8f1af1d9..3464d3b4 100644 --- a/Random_Problems/rev_string.go +++ b/Random Problems/rev_string.go @@ -1,18 +1,18 @@ -// Reverse a string -// Program Author : Abhisek Kumar Gupta - -package main -import "fmt" - -func reverse(s string) string { - chars := []rune(s) - for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { - chars[i], chars[j] = chars[j], chars[i] - } - return string(chars) -} - -func main() { - fmt.Printf("%v\n", reverse("abcdefg")) -} - +// Reverse a string +// Program Author : Abhisek Kumar Gupta + +package main +import "fmt" + +func reverse(s string) string { + chars := []rune(s) + for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { + chars[i], chars[j] = chars[j], chars[i] + } + return string(chars) +} + +func main() { + fmt.Printf("%v\n", reverse("abcdefg")) +} + diff --git a/Random_Problems/rotate_string.cpp b/Random Problems/rotate_string.cpp similarity index 94% rename from Random_Problems/rotate_string.cpp rename to Random Problems/rotate_string.cpp index 0a6fc619..7c0127dd 100644 --- a/Random_Problems/rotate_string.cpp +++ b/Random Problems/rotate_string.cpp @@ -1,27 +1,27 @@ -// Rotating a string -#include -using namespace std; - -void rotate(char *a, int k){ - int len = strlen(a); - while(len >= 0){ - a[len + k] = a[len]; - len--; - } - len = strlen(a); - int j = len - k; - int s = 0; - while(j < len){ - a[s] = a[j]; - s++; - j++; - } - a[len - k] = '\0'; -} -int main(){ - char a[100] = "abhisekkumar"; - int k = 5; - rotate(a, k); - cout << a << endl; - return 0; +// Rotating a string +#include +using namespace std; + +void rotate(char *a, int k){ + int len = strlen(a); + while(len >= 0){ + a[len + k] = a[len]; + len--; + } + len = strlen(a); + int j = len - k; + int s = 0; + while(j < len){ + a[s] = a[j]; + s++; + j++; + } + a[len - k] = '\0'; +} +int main(){ + char a[100] = "abhisekkumar"; + int k = 5; + rotate(a, k); + cout << a << endl; + return 0; } \ No newline at end of file diff --git a/Random_Problems/set_bits.cpp b/Random Problems/set_bits.cpp similarity index 96% rename from Random_Problems/set_bits.cpp rename to Random Problems/set_bits.cpp index 40e2b75c..079fe25d 100644 --- a/Random_Problems/set_bits.cpp +++ b/Random Problems/set_bits.cpp @@ -1,17 +1,17 @@ -// Count the number of bits that are set in an integer -#include -using namespace std; -short check_set_bits(unsigned int x){ - short num_bits = 0; - while(x){ - num_bits += x & 1; - x >>= 1; - } - return num_bits; -} -int main(){ - cout << check_set_bits(1) << endl; - cout << check_set_bits(7) << endl; - cout << check_set_bits(15) << endl; - return 0; +// Count the number of bits that are set in an integer +#include +using namespace std; +short check_set_bits(unsigned int x){ + short num_bits = 0; + while(x){ + num_bits += x & 1; + x >>= 1; + } + return num_bits; +} +int main(){ + cout << check_set_bits(1) << endl; + cout << check_set_bits(7) << endl; + cout << check_set_bits(15) << endl; + return 0; } \ No newline at end of file diff --git a/Random_Problems/spiral_print.cpp b/Random Problems/spiral_print.cpp similarity index 96% rename from Random_Problems/spiral_print.cpp rename to Random Problems/spiral_print.cpp index aa6a26ab..beaf49ff 100644 --- a/Random_Problems/spiral_print.cpp +++ b/Random Problems/spiral_print.cpp @@ -1,45 +1,45 @@ -#include -using namespace std; -int main(){ - int mat[100][100]; - int row, col; - cin >> row >> col; - for(int i = 0; i < row; i++){ - for(int j = 0; j < col; j++){ - cin >> mat[i][j]; - } - } - // spiral print - int start_row = 0; - int start_col = 0; - int end_row = row - 1; - int end_col = col - 1; - while(start_row <= end_row && start_col <= end_col){ - // print first row - for(int i = start_col; i <= end_col; i++){ - cout << mat[start_row][i] << " "; - } - start_row++; - // print last col - for(int i = start_row; i <= end_row; i++){ - cout << mat[i][end_col] << " "; - } - end_col--; - // last row - if(end_row > start_row){ - for(int i = end_col; i >= start_col; i--){ - cout << mat[end_row][i] << " "; - } - end_row--; - } - // start column - if(end_col > start_col){ - for(int i = end_row; i >= start_row; i--){ - cout << mat[i][start_col] << " "; - } - start_col++; - } - } - return 0; -} +#include +using namespace std; +int main(){ + int mat[100][100]; + int row, col; + cin >> row >> col; + for(int i = 0; i < row; i++){ + for(int j = 0; j < col; j++){ + cin >> mat[i][j]; + } + } + // spiral print + int start_row = 0; + int start_col = 0; + int end_row = row - 1; + int end_col = col - 1; + while(start_row <= end_row && start_col <= end_col){ + // print first row + for(int i = start_col; i <= end_col; i++){ + cout << mat[start_row][i] << " "; + } + start_row++; + // print last col + for(int i = start_row; i <= end_row; i++){ + cout << mat[i][end_col] << " "; + } + end_col--; + // last row + if(end_row > start_row){ + for(int i = end_col; i >= start_col; i--){ + cout << mat[end_row][i] << " "; + } + end_row--; + } + // start column + if(end_col > start_col){ + for(int i = end_row; i >= start_row; i--){ + cout << mat[i][start_col] << " "; + } + start_col++; + } + } + return 0; +} \ No newline at end of file diff --git a/Random_Problems/tempCodeRunnerFile.cpp b/Random Problems/tempCodeRunnerFile.cpp similarity index 100% rename from Random_Problems/tempCodeRunnerFile.cpp rename to Random Problems/tempCodeRunnerFile.cpp diff --git a/Random_Problems/unique_occurences.cpp b/Random Problems/unique_occurences.cpp similarity index 96% rename from Random_Problems/unique_occurences.cpp rename to Random Problems/unique_occurences.cpp index 90372302..d7bc8f2f 100644 --- a/Random_Problems/unique_occurences.cpp +++ b/Random Problems/unique_occurences.cpp @@ -1,36 +1,36 @@ -/* - Given an array of integers arr, write a function that returns true - if and only if the number of occurrences of each value in the array is unique. - Input: arr = [1,2,2,1,1,3] - Output: true - Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. -*/ -#include -using namespace std; -bool check_unique(vector& V, int n){ - map M; - for(int x : V){ - M[x]++; - } - map second_map; - for(auto x : M){ - if(second_map[x.second] > 0) // if same map value encountered then return false - return false; - else - second_map[x.second]++; - } - return true; -} -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - if(check_unique(V, n)) - cout << "True"; - else - cout << "False"; - return 0; -} +/* + Given an array of integers arr, write a function that returns true + if and only if the number of occurrences of each value in the array is unique. + Input: arr = [1,2,2,1,1,3] + Output: true + Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. +*/ +#include +using namespace std; +bool check_unique(vector& V, int n){ + map M; + for(int x : V){ + M[x]++; + } + map second_map; + for(auto x : M){ + if(second_map[x.second] > 0) // if same map value encountered then return false + return false; + else + second_map[x.second]++; + } + return true; +} +int main(){ + int n; + cin >> n; + vector V(n); + for(int i = 0; i < n; i++){ + cin >> V[i]; + } + if(check_unique(V, n)) + cout << "True"; + else + cout << "False"; + return 0; +} diff --git a/Sliding_Window/longest-substring-without-repeating-characters.go b/Sliding Window/longest-substring-without-repeating-characters.go similarity index 100% rename from Sliding_Window/longest-substring-without-repeating-characters.go rename to Sliding Window/longest-substring-without-repeating-characters.go From 9360d92f1111e27827a6f78a1c875bb2d27df1f0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Sat, 11 Feb 2023 12:16:06 +0530 Subject: [PATCH 0081/1894] Update CONTRIBUTING.md --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c28f8441..aefb4295 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,3 +14,7 @@ Contributions are always welcome! ## What if the problem you want to add is not present in the issue? - You can suggest an idea for this project under issues tab (add list of questions you think it is important, it will be assigned to you) - You can directly make a PR against dev branch with the proposed problems with appropriate comments and description + +## What if the changes are inconsistent? +- keep pulling from origin/main see below, this way you will be up to date with the latest changes in main branch +- git pull origin main From 7ad963195a937d853b869396b2b1ce566e110aab Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Sat, 11 Feb 2023 12:16:26 +0530 Subject: [PATCH 0082/1894] Update CONTRIBUTING.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aefb4295..b65b3775 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,5 +16,5 @@ Contributions are always welcome! - You can directly make a PR against dev branch with the proposed problems with appropriate comments and description ## What if the changes are inconsistent? -- keep pulling from origin/main see below, this way you will be up to date with the latest changes in main branch +- Keep pulling from origin/main see below, this way you will be up to date with the latest changes in main branch - git pull origin main From 1506730b41f2f39727a12dfbeb5ae0b977d0a46e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Feb 2023 12:18:08 +0530 Subject: [PATCH 0083/1894] rename folder --- {HashTable => Hash Table}/LongestSubstring.java | 0 {HashTable => Hash Table}/SmallerNumberThanCurrent.java | 0 {HashTable => Hash Table}/SumOfUniqueElements.java | 0 {HashTable => Hash Table}/col_sum.java | 0 {HashTable => Hash Table}/equilbrium_array.java | 0 {HashTable => Hash Table}/first_repeated_character.go | 0 {HashTable => Hash Table}/first_repeating_character.go | 0 {HashTable => Hash Table}/four_number_sum.java | 0 {HashTable => Hash Table}/integer_to_roman.cpp | 0 {HashTable => Hash Table}/integer_to_roman.java | 0 {HashTable => Hash Table}/remove_duplicates.go | 0 {HashTable => Hash Table}/roman_to_integer.cpp | 0 {HashTable => Hash Table}/row_sum.java | 0 {HashTable => Hash Table}/three_number_sum.java | 0 {HashTable => Hash Table}/two_number_sum.java | 0 {HashTable => Hash Table}/twosum.go | 0 16 files changed, 0 insertions(+), 0 deletions(-) rename {HashTable => Hash Table}/LongestSubstring.java (100%) rename {HashTable => Hash Table}/SmallerNumberThanCurrent.java (100%) rename {HashTable => Hash Table}/SumOfUniqueElements.java (100%) rename {HashTable => Hash Table}/col_sum.java (100%) rename {HashTable => Hash Table}/equilbrium_array.java (100%) rename {HashTable => Hash Table}/first_repeated_character.go (100%) rename {HashTable => Hash Table}/first_repeating_character.go (100%) rename {HashTable => Hash Table}/four_number_sum.java (100%) rename {HashTable => Hash Table}/integer_to_roman.cpp (100%) rename {HashTable => Hash Table}/integer_to_roman.java (100%) rename {HashTable => Hash Table}/remove_duplicates.go (100%) rename {HashTable => Hash Table}/roman_to_integer.cpp (100%) rename {HashTable => Hash Table}/row_sum.java (100%) rename {HashTable => Hash Table}/three_number_sum.java (100%) rename {HashTable => Hash Table}/two_number_sum.java (100%) rename {HashTable => Hash Table}/twosum.go (100%) diff --git a/HashTable/LongestSubstring.java b/Hash Table/LongestSubstring.java similarity index 100% rename from HashTable/LongestSubstring.java rename to Hash Table/LongestSubstring.java diff --git a/HashTable/SmallerNumberThanCurrent.java b/Hash Table/SmallerNumberThanCurrent.java similarity index 100% rename from HashTable/SmallerNumberThanCurrent.java rename to Hash Table/SmallerNumberThanCurrent.java diff --git a/HashTable/SumOfUniqueElements.java b/Hash Table/SumOfUniqueElements.java similarity index 100% rename from HashTable/SumOfUniqueElements.java rename to Hash Table/SumOfUniqueElements.java diff --git a/HashTable/col_sum.java b/Hash Table/col_sum.java similarity index 100% rename from HashTable/col_sum.java rename to Hash Table/col_sum.java diff --git a/HashTable/equilbrium_array.java b/Hash Table/equilbrium_array.java similarity index 100% rename from HashTable/equilbrium_array.java rename to Hash Table/equilbrium_array.java diff --git a/HashTable/first_repeated_character.go b/Hash Table/first_repeated_character.go similarity index 100% rename from HashTable/first_repeated_character.go rename to Hash Table/first_repeated_character.go diff --git a/HashTable/first_repeating_character.go b/Hash Table/first_repeating_character.go similarity index 100% rename from HashTable/first_repeating_character.go rename to Hash Table/first_repeating_character.go diff --git a/HashTable/four_number_sum.java b/Hash Table/four_number_sum.java similarity index 100% rename from HashTable/four_number_sum.java rename to Hash Table/four_number_sum.java diff --git a/HashTable/integer_to_roman.cpp b/Hash Table/integer_to_roman.cpp similarity index 100% rename from HashTable/integer_to_roman.cpp rename to Hash Table/integer_to_roman.cpp diff --git a/HashTable/integer_to_roman.java b/Hash Table/integer_to_roman.java similarity index 100% rename from HashTable/integer_to_roman.java rename to Hash Table/integer_to_roman.java diff --git a/HashTable/remove_duplicates.go b/Hash Table/remove_duplicates.go similarity index 100% rename from HashTable/remove_duplicates.go rename to Hash Table/remove_duplicates.go diff --git a/HashTable/roman_to_integer.cpp b/Hash Table/roman_to_integer.cpp similarity index 100% rename from HashTable/roman_to_integer.cpp rename to Hash Table/roman_to_integer.cpp diff --git a/HashTable/row_sum.java b/Hash Table/row_sum.java similarity index 100% rename from HashTable/row_sum.java rename to Hash Table/row_sum.java diff --git a/HashTable/three_number_sum.java b/Hash Table/three_number_sum.java similarity index 100% rename from HashTable/three_number_sum.java rename to Hash Table/three_number_sum.java diff --git a/HashTable/two_number_sum.java b/Hash Table/two_number_sum.java similarity index 100% rename from HashTable/two_number_sum.java rename to Hash Table/two_number_sum.java diff --git a/HashTable/twosum.go b/Hash Table/twosum.go similarity index 100% rename from HashTable/twosum.go rename to Hash Table/twosum.go From 1306aaf7d321d96a168b2e2ddc6302d6f6149df3 Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 11 Feb 2023 12:51:34 +0530 Subject: [PATCH 0084/1894] Add Hashing Problems Solution --- HashTable/coloful_number.java | 105 +++++++++++++++++++++ HashTable/count_distinct_elements.java | 60 ++++++++++++ HashTable/count_elements.java | 103 ++++++++++++++++++++ HashTable/count_subarray_zero_sum.java | 60 ++++++++++++ HashTable/count_unique_elements.java | 105 +++++++++++++++++++++ HashTable/first_non_repeating_element.java | 30 ++++++ HashTable/first_repeating_number.java | 83 ++++++++++++++++ HashTable/frequency_of_elements.java | 90 ++++++++++++++++++ 8 files changed, 636 insertions(+) create mode 100644 HashTable/coloful_number.java create mode 100644 HashTable/count_distinct_elements.java create mode 100644 HashTable/count_elements.java create mode 100644 HashTable/count_subarray_zero_sum.java create mode 100644 HashTable/count_unique_elements.java create mode 100644 HashTable/first_non_repeating_element.java create mode 100644 HashTable/first_repeating_number.java create mode 100644 HashTable/frequency_of_elements.java diff --git a/HashTable/coloful_number.java b/HashTable/coloful_number.java new file mode 100644 index 00000000..30fc5cd9 --- /dev/null +++ b/HashTable/coloful_number.java @@ -0,0 +1,105 @@ +/** + * Problem Description + * Given a number A, find if it is COLORFUL number or not. + * + * If number A is a COLORFUL number return 1 else, return 0. + * + * What is a COLORFUL Number: + * + * A number can be broken into different consecutive sequence of digits. + * The number 3245 can be broken into sequences like 3, 2, 4, 5, 32, 24, 45, 324 and 245. + * This number is a COLORFUL number, since the product of every consecutive sequence of digits is different + * + * + * Problem Constraints + * 1 <= A <= 2 * 109 + * + * + * + * Input Format + * The first and only argument is an integer A. + * + * + * + * Output Format + * Return 1 if integer A is COLORFUL else return 0. + * + * + * + * Example Input + * Input 1: + * + * A = 23 + * Input 2: + * + * A = 236 + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * 0 + * + * + * Example Explanation + * Explanation 1: + * + * Possible Sub-sequences: [2, 3, 23] where + * 2 -> 2 + * 3 -> 3 + * 23 -> 6 (product of digits) + * This number is a COLORFUL number since product of every digit of a sub-sequence are different. + * Explanation 2: + * + * Possible Sub-sequences: [2, 3, 6, 23, 36, 236] where + * 2 -> 2 + * 3 -> 3 + * 6 -> 6 + * 23 -> 6 (product of digits) + * 36 -> 18 (product of digits) + * 236 -> 36 (product of digits) + * This number is not a COLORFUL number since the product sequence 23 and sequence 6 is same. + */ + +package Hashing; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +public class ColorfulNumber { + public static void main(String[] args) { + int num = 236; + + int res = solve(num); + System.out.println(res); + } + public static int solve(int num) { + // O(DIGITS ^ 2) time | O(DIGITS ^ 2) space + HashSet hashSet = new HashSet<>(); + ArrayList numbers = new ArrayList<>(); + + int currentNum = num; + while (currentNum != 0) { + int digit = currentNum % 10; + numbers.add(digit); + currentNum /= 10; + } + + Collections.reverse(numbers); + int len = numbers.size(); + for (int i = 0; i < len; i++) { + int product = 1; + for (int j = i; j < len; j++) { + + product *= numbers.get(j); + if (hashSet.contains(product)) return 0; + hashSet.add(product); + } + } + return 1; + } +} diff --git a/HashTable/count_distinct_elements.java b/HashTable/count_distinct_elements.java new file mode 100644 index 00000000..7bfee076 --- /dev/null +++ b/HashTable/count_distinct_elements.java @@ -0,0 +1,60 @@ +/** + * Problem Description + * You are given an array A of N integers. You will have to return number of distinct elements of the array. + * + * Problem Constraints + * 1 <= N <= 105 + * 1 <= A[i] <= 109 + * + * + * Input Format + * First argument A is an array of integers. + * + * + * Output Format + * Return an integer. + * + * + * Example Input + * Input 1: + * A = [3, 4, 3, 6, 6] + * Input 2: + * A = [3, 3, 3, 9, 0, 1, 0] + * + * + * Example Output + * Output 1: + * 3 + * Output 2: + * 4 + * + * + * Example Explanation + * For Input 1: + * The distinct elements of the array are 3, 4 and 6. + * For Input 2: + * The distinct elements of the array are 3, 9, 0 and 1. + */ + +package Hashing; + +import java.util.HashSet; + +public class CountDistinctElements { + public static void main(String[] args) { + int[] array = {3, 4, 3, 6, 6}; + + int res = solve(array); + System.out.println(res); + } + public static int solve(int[] array) { + // O(N) time | O(N) space + + HashSet hashSet = new HashSet<>(); + + for (int num : array) + hashSet.add((long) num); + + return (int) hashSet.size(); + } +} diff --git a/HashTable/count_elements.java b/HashTable/count_elements.java new file mode 100644 index 00000000..edab1d8b --- /dev/null +++ b/HashTable/count_elements.java @@ -0,0 +1,103 @@ +/** + * Given two integer arrays, A and B of size N and M, respectively. Your task is to find all the common elements in both the array. + * + * NOTE: + * + * Each element in the result should appear as many times as it appears in both arrays. + * The result can be in any order. + * + * + * Problem Constraints + * 1 <= N, M <= 105 + * + * 1 <= A[i] <= 109 + * + * + * + * Input Format + * First argument is an integer array A of size N. + * + * Second argument is an integer array B of size M. + * + * + * + * Output Format + * Return an integer array denoting the common elements. + * + * + * + * Example Input + * Input 1: + * + * A = [1, 2, 2, 1] + * B = [2, 3, 1, 2] + * Input 2: + * + * A = [2, 1, 4, 10] + * B = [3, 6, 2, 10, 10] + * + * + * Example Output + * Output 1: + * + * [1, 2, 2] + * Output 2: + * + * [2, 10] + * + * + * Example Explanation + * Explanation 1: + * + * Elements (1, 2, 2) appears in both the array. Note 2 appears twice in both the array. + * Explantion 2: + * + * Elements (2, 10) appears in both the array. + */ + +package Hashing; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +public class CountElements { + public static void main(String[] args) { + int[] array1 = {2, 1, 4, 10, 10}; + int[] array2 = {3, 6, 2, 10, 10, 10}; + + int[] res = solve(array1, array2); + System.out.println(Arrays.toString(res)); + } + + public static int[] solve(int[] array1, int[] array2) { + // O(N + M) time | O(N + M) space + + HashMap hashMap1 = new HashMap<>(); + HashMap hashMap2 = new HashMap<>(); + + for (int num : array1) { + hashMap1.put(num, hashMap1.getOrDefault(num, 0) + 1); + } + + for (int num : array2) { + hashMap2.put(num, hashMap2.getOrDefault(num, 0) + 1); + } + + ArrayList res = new ArrayList<>(); + + for (int key: hashMap1.keySet()) { + + if (hashMap2.containsKey(key)) { + + for (int i = 0; i < Math.min(hashMap1.get(key), hashMap2.get(key)); ++i) { // to get common elements + res.add(key); + } + } + } + + return res.stream().mapToInt(i -> i).toArray(); + + } +} + diff --git a/HashTable/count_subarray_zero_sum.java b/HashTable/count_subarray_zero_sum.java new file mode 100644 index 00000000..7bfee076 --- /dev/null +++ b/HashTable/count_subarray_zero_sum.java @@ -0,0 +1,60 @@ +/** + * Problem Description + * You are given an array A of N integers. You will have to return number of distinct elements of the array. + * + * Problem Constraints + * 1 <= N <= 105 + * 1 <= A[i] <= 109 + * + * + * Input Format + * First argument A is an array of integers. + * + * + * Output Format + * Return an integer. + * + * + * Example Input + * Input 1: + * A = [3, 4, 3, 6, 6] + * Input 2: + * A = [3, 3, 3, 9, 0, 1, 0] + * + * + * Example Output + * Output 1: + * 3 + * Output 2: + * 4 + * + * + * Example Explanation + * For Input 1: + * The distinct elements of the array are 3, 4 and 6. + * For Input 2: + * The distinct elements of the array are 3, 9, 0 and 1. + */ + +package Hashing; + +import java.util.HashSet; + +public class CountDistinctElements { + public static void main(String[] args) { + int[] array = {3, 4, 3, 6, 6}; + + int res = solve(array); + System.out.println(res); + } + public static int solve(int[] array) { + // O(N) time | O(N) space + + HashSet hashSet = new HashSet<>(); + + for (int num : array) + hashSet.add((long) num); + + return (int) hashSet.size(); + } +} diff --git a/HashTable/count_unique_elements.java b/HashTable/count_unique_elements.java new file mode 100644 index 00000000..30fc5cd9 --- /dev/null +++ b/HashTable/count_unique_elements.java @@ -0,0 +1,105 @@ +/** + * Problem Description + * Given a number A, find if it is COLORFUL number or not. + * + * If number A is a COLORFUL number return 1 else, return 0. + * + * What is a COLORFUL Number: + * + * A number can be broken into different consecutive sequence of digits. + * The number 3245 can be broken into sequences like 3, 2, 4, 5, 32, 24, 45, 324 and 245. + * This number is a COLORFUL number, since the product of every consecutive sequence of digits is different + * + * + * Problem Constraints + * 1 <= A <= 2 * 109 + * + * + * + * Input Format + * The first and only argument is an integer A. + * + * + * + * Output Format + * Return 1 if integer A is COLORFUL else return 0. + * + * + * + * Example Input + * Input 1: + * + * A = 23 + * Input 2: + * + * A = 236 + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * 0 + * + * + * Example Explanation + * Explanation 1: + * + * Possible Sub-sequences: [2, 3, 23] where + * 2 -> 2 + * 3 -> 3 + * 23 -> 6 (product of digits) + * This number is a COLORFUL number since product of every digit of a sub-sequence are different. + * Explanation 2: + * + * Possible Sub-sequences: [2, 3, 6, 23, 36, 236] where + * 2 -> 2 + * 3 -> 3 + * 6 -> 6 + * 23 -> 6 (product of digits) + * 36 -> 18 (product of digits) + * 236 -> 36 (product of digits) + * This number is not a COLORFUL number since the product sequence 23 and sequence 6 is same. + */ + +package Hashing; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +public class ColorfulNumber { + public static void main(String[] args) { + int num = 236; + + int res = solve(num); + System.out.println(res); + } + public static int solve(int num) { + // O(DIGITS ^ 2) time | O(DIGITS ^ 2) space + HashSet hashSet = new HashSet<>(); + ArrayList numbers = new ArrayList<>(); + + int currentNum = num; + while (currentNum != 0) { + int digit = currentNum % 10; + numbers.add(digit); + currentNum /= 10; + } + + Collections.reverse(numbers); + int len = numbers.size(); + for (int i = 0; i < len; i++) { + int product = 1; + for (int j = i; j < len; j++) { + + product *= numbers.get(j); + if (hashSet.contains(product)) return 0; + hashSet.add(product); + } + } + return 1; + } +} diff --git a/HashTable/first_non_repeating_element.java b/HashTable/first_non_repeating_element.java new file mode 100644 index 00000000..dbd7d510 --- /dev/null +++ b/HashTable/first_non_repeating_element.java @@ -0,0 +1,30 @@ +package Hashing; + +import java.util.HashMap; + +public class FirstNonRepeatingElement { + public static void main(String[] args) { + int[] array = {10, 5, 3, 4, 3, 5, 6}; + + int res = solve(array); + System.out.println(res); + } + public static int solve(int[] array) { + // O(N) time | O(N) space where N is length of array + + // Build HashMap + HashMap hashMap = new HashMap<>(); + + for (int num : array) { + + if (!hashMap.containsKey(num)) hashMap.put(num, 0); + hashMap.put(num, hashMap.get(num) + 1); + } + + for (int num : array) { + if (hashMap.get(num) == 1) return num; + } + + return -1; + } +} diff --git a/HashTable/first_repeating_number.java b/HashTable/first_repeating_number.java new file mode 100644 index 00000000..878bc0c2 --- /dev/null +++ b/HashTable/first_repeating_number.java @@ -0,0 +1,83 @@ +/** + * Problem Description + * Given an integer array A of size N, find the first repeating element in it. + * + * We need to find the element that occurs more than once and whose index of the first occurrence is the smallest. + * + * If there is no repeating element, return -1. + * + * + * + * Problem Constraints + * 1 <= N <= 105 + * + * 1 <= A[i] <= 109 + * + * + * + * Input Format + * The first and only argument is an integer array A of size N. + * + * + * + * Output Format + * Return an integer denoting the first repeating element. + * + * + * + * Example Input + * Input 1: + * + * A = [10, 5, 3, 4, 3, 5, 6] + * Input 2: + * + * A = [6, 10, 5, 4, 9, 120] + * + * + * Example Output + * Output 1: + * + * 5 + * Output 2: + * + * -1 + * + * + * Example Explanation + * Explanation 1: + * + * 5 is the first element that repeats + * Explanation 2: + * + * There is no repeating element, output -1 + */ +package Hashing; + +import java.util.HashMap; + +public class FirstRepeatingElement { + public static void main(String[] args) { + int[] array = {10, 5, 3, 4, 3, 5, 6}; + + int res = solve(array); + System.out.println(res); + } + public static int solve(int[] array) { + // O(N) time | O(N) space where N is length of array + + // Build HashMap + HashMap hashMap = new HashMap<>(); + + for (int num : array) { + + if (!hashMap.containsKey(num)) hashMap.put(num, 0); + hashMap.put(num, hashMap.get(num) + 1); + } + + for (int num : array) { + if (hashMap.get(num) > 1) return num; + } + + return -1; + } +} diff --git a/HashTable/frequency_of_elements.java b/HashTable/frequency_of_elements.java new file mode 100644 index 00000000..54f8f093 --- /dev/null +++ b/HashTable/frequency_of_elements.java @@ -0,0 +1,90 @@ +/** + * Problem Description + * Given an array A. You have some integers given in the array B. + * + * For the i-th number, find the frequency of B[i] in the array A and return a list containing all the frequencies. + * + * + * + * Problem Constraints + * 1 <= |A| <= 105 + * + * 1 <= |B| <= 105 + * + * 1 <= A[i] <= 105 + * + * 1 <= B[i] <= 105 + * + * + * + * Input Format + * First argument A is an array of integers. + * + * Second argument B is an array of integers denoting the queries. + * + * + * + * Output Format + * Return an array of integers containing frequency of the each element in B. + * + * + * + * Example Input + * Input 1: + * A = [1, 2, 1, 1] + * B = [1, 2] + * Input 2: + * A = [2, 5, 9, 2, 8] + * B = [3, 2] + * + * + * Example Output + * Output 1: + * [3, 1] + * Output 2: + * [0, 2] + * + * + * Example Explanation + * For Input 1: + * The frequency of 1 in the array A is 3. + * The frequency of 2 in the array A is 1. + * For Input 2: + * The frequency of 3 in the array A is 0. + * The frequency of 2 in the array A is 2. + */ +package Hashing; + +import java.util.Arrays; +import java.util.HashMap; + +public class FrequencyOfElements { + public static void main(String[] args) { + int[] array = {2, 5, 9, 2, 8}; + int[] queries = {3, 2}; + + int[] res = solve(array, queries); + System.out.println(Arrays.toString(res)); + } + + public static int[] solve(int[] nums, int[] queries) { + // O(N) time | O(Q) space where N is length of array , Q is length of queries + + HashMap hashMap = new HashMap<>(); + + for (int num : nums) { + if (!hashMap.containsKey(num)) hashMap.put(num, 0); + + hashMap.put(num, hashMap.get(num) + 1); + } + System.out.println(hashMap); + + int[] res = new int[queries.length]; + + for (int i = 0; i < queries.length; i++) + if (hashMap.containsKey(queries[i])) + res[i] = hashMap.get(queries[i]); + + return res; + } +} From 24af07e5cd63282dc85bf22b03120d2a0172a78e Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 11 Feb 2023 13:12:50 +0530 Subject: [PATCH 0085/1894] Add Hashing Problems Solution --- HashTable/number_of_good_pairs.java | 63 +++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 HashTable/number_of_good_pairs.java diff --git a/HashTable/number_of_good_pairs.java b/HashTable/number_of_good_pairs.java new file mode 100644 index 00000000..cca2a573 --- /dev/null +++ b/HashTable/number_of_good_pairs.java @@ -0,0 +1,63 @@ +/** + * Given an array of integers nums, return the number of good pairs. + * + * A pair (i, j) is called good if nums[i] == nums[j] and i < j. + * + * + * + * Example 1: + * + * Input: nums = [1,2,3,1,1,3] + * Output: 4 + * Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. + * Example 2: + * + * Input: nums = [1,1,1,1] + * Output: 6 + * Explanation: Each pair in the array are good. + * Example 3: + * + * Input: nums = [1,2,3] + * Output: 0 + * + * + * Constraints: + * + * 1 <= nums.length <= 100 + * 1 <= nums[i] <= 100 + */ + +package Hashing; + +import java.util.HashMap; + +public class NumberOfGoodPairs { + public static void main(String[] args) { + int[] array = {1, 1, 1, 1}; + + int res = solve(array); + System.out.println(res); + } + + public static int solve(int[] array) { + // O(N) time | O(N) space + int res = 0; + HashMap hashmap = new HashMap<>(); + + for (int num : array) { + + int numCount = hashmap.getOrDefault(num, 0); + res += numCount; + hashmap.put(num, numCount); + } + + // O(N^2) time | O(N) space +// for (int i = 0; i < array.length; i++) { +// for (int j = i + 1; j < array.length; j++) { +// if (array[i] == array[j]) res++; +// } +// } + + return res; + } +} From 9ff106de39e6d97815ee93de4a939b3bf0f2c8b8 Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 11 Feb 2023 14:13:33 +0530 Subject: [PATCH 0086/1894] Add Strings Problems Solution --- Strings/count_occurances.java | 79 +++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Strings/count_occurances.java diff --git a/Strings/count_occurances.java b/Strings/count_occurances.java new file mode 100644 index 00000000..7328fa4e --- /dev/null +++ b/Strings/count_occurances.java @@ -0,0 +1,79 @@ +/** + * Find the number of occurrences of bob in string A consisting of lowercase English alphabets. + * + * + * + * Problem Constraints + * 1 <= |A| <= 1000 + * + * + * Input Format + * The first and only argument contains the string A, consisting of lowercase English alphabets. + * + * + * Output Format + * Return an integer containing the answer. + * + * + * Example Input + * Input 1: + * + * "abobc" + * Input 2: + * + * "bobob" + * + * + * Example Output + * Output 1: + * + * 1 + * Output 2: + * + * 2 + * + * + * Example Explanation + * Explanation 1: + * + * The only occurrence is at second position. + * Explanation 2: + * + * Bob occures at first and third position. + */ + +package Strings; + +public class CountOccurrences { + public static void main(String[] args) { + String string = "bobob"; + + int res = solve(string); + System.out.println(res); + } + public static int solve(String string) { + + // O(N) time | O(1) space + int res = 0; + + for (int i = 0; i + 2 < string.length(); i++) { + if (string.charAt(i) == 'b' && + string.charAt(i + 1) == 'o' && + string.charAt(i + 2) == 'b') + ++res; + } + +// for (int i = 0; i < string.length(); i++) { +// char c = string.charAt(i); +// StringBuilder sb = new StringBuilder(); +// sb.append(c); +// for (int j = i + 1; j < string.length(); j++) { +// sb.append(string.charAt(j)); +// if (sb.toString().equals("bob")) { +// res++; +// } +// } +// } + return res; + } +} From 0a37ef874a8cf277ccebe509c73e14135dd65a98 Mon Sep 17 00:00:00 2001 From: uday510 Date: Sat, 11 Feb 2023 14:24:16 +0530 Subject: [PATCH 0087/1894] Add Strings Problems Solution --- Strings/check_anagrams.java | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Strings/check_anagrams.java diff --git a/Strings/check_anagrams.java b/Strings/check_anagrams.java new file mode 100644 index 00000000..59abfa74 --- /dev/null +++ b/Strings/check_anagrams.java @@ -0,0 +1,83 @@ +/** + * You are given two lowercase strings A and B each of length N. Return 1 if they are anagrams to each other and 0 if not. + * + * Note : Two strings A and B are called anagrams to each other if A can be formed after rearranging the letters of B. + * + * + * Problem Constraints + * 1 <= N <= 105 + * A and B are lowercase strings + * + * + * Input Format + * Both arguments A and B are a string. + * + * + * Output Format + * Return 1 if they are anagrams and 0 if not + * + * + * Example Input + * Input 1: + * A = "cat" + * B = "bat" + * Input 2: + * A = "secure" + * B = "rescue" + * + * + * Example Output + * Output 1: + * 0 + * Output 2: + * 1 + * + * + * Example Explanation + * For Input 1: + * The words cannot be rearranged to form the same word. So, they are not anagrams. + * For Input 2: + * They are an anagram. + */ +package Strings; + +public class CheckAnagrams { + public static void main(String[] args) { + String string1 = "secure"; + String string2 = "rescue"; + + int res = solve(string1, string2); + System.out.println(res); + } + + public static int solve(String string1, String string2) { + + // O(N) time | O(1) space + + int[] freq1 = new int[26]; + int[] freq2 = new int[26]; + + for (int i = 0; i < string1.length(); i++) { + freq1[string1.charAt(i) - 'a']++; + freq2[string2.charAt(i) - 'a']++; + } + + for (int i = 0; i < 26; i++) { + if (freq1[i] != freq2[i]) return 0; + } + + return 1; + +// char[] char1 = string1.toCharArray(); +// Arrays.sort(char1); +// +// char[] char2 = string2.toCharArray(); +// Arrays.sort(char2); +// +// String str1 = new String(char1); +// String str2 = new String(char2); +// +// if (str1.equals(str2)) return 1; +// return 0; + } +} From 4719482d3243cecf362f4d1fec889afcc7329434 Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Sat, 11 Feb 2023 17:38:12 +0530 Subject: [PATCH 0088/1894] Made few variable naming changes --- Leetcode/Median_of_Two_Sorted_Arrays.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Leetcode/Median_of_Two_Sorted_Arrays.cpp index 9dcdc6ca..93ee1600 100644 --- a/Leetcode/Median_of_Two_Sorted_Arrays.cpp +++ b/Leetcode/Median_of_Two_Sorted_Arrays.cpp @@ -30,7 +30,7 @@ class Solution { int mid2 = (n1 + n2 + 1)/2 - mid1; // why?? => suppose nums1[] is partitioned at index 3 => nums1[3] = 7. - std::pair maxleft, maxright; + std::pair maxleft, minright; maxleft.first = mid1 == 0 ? INT_MIN : nums1[mid1-1]; maxleft.second = mid2 == 0 ? INT_MIN : nums2[mid2-1]; @@ -68,7 +68,7 @@ int main(int argc, char const *argv[]) std::cin>>arr2[i]; } - const Solution sol = new Solution(); + Solution sol = Solution(); double res = sol.findMedianSortedArrays(arr1, arr2); std::cout< Date: Sat, 11 Feb 2023 17:58:07 +0530 Subject: [PATCH 0089/1894] Explanation betterment and some minor changes --- Leetcode/Median_of_Two_Sorted_Arrays.cpp | 25 ++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Leetcode/Median_of_Two_Sorted_Arrays.cpp index 93ee1600..00ff5919 100644 --- a/Leetcode/Median_of_Two_Sorted_Arrays.cpp +++ b/Leetcode/Median_of_Two_Sorted_Arrays.cpp @@ -6,13 +6,27 @@ This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) Now, lets optimise it. - So, the sorted form of the given array is [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. Now suppose, on partitioning the above merged-sorted array in the mid-point, we get 5 elements on left and 5 elements on the right. - Now, we can get 5 elements by selecting {4 from left, 1 from right}, {3 from left, 2 from right}, {2 from left, 3 from right} and {1 from left, 4 from right}. - Lets analyse case-wise: - case 1: 4 from left, 1 from right - + So, the sorted form of the given array is arr = [1, 2, 3, 3, 4, 6, 7, 10, 12, 15]. To find the median of the array, we need to select the 2 mid elements and average it out. + If we observe the sorted array carefully, then we notice that the 2 middle elements are arr[4] = 4 and arr[5] = 6, => arr[4] <= arr[5]. + + Thought process: + Now, since the arrays are sorted, so the binary searh may be able to solve the problem. + Observation 1: If we partition the sorted array arr into 2 halves, then for sure we know that there would be 5 elements on left half and 5 elements on right half. + Now, we can select 5 elements for right half from nums1 and nums2 combinedly and similarly the rest of the elements for the left half. + Example: + 1. left => [1, 3, 4, 7, 2], right => [10, 12, 3, 6, 15] + 2. left => [1, 3, 4, 2, 3], right => [7, 10, 12, 6, 15] + 3. left => [1, 3, 2, 3, 6], right => [4, 7, 10, 12, 15] + + Observation 2: All the elements on left half is lesser than all the elements on the right half. + Now, according to the observation, I have to check that all the elements in the left <= all the elements in the right. This can be done by just comparing the maximum of left half <= minimum of right half. + + Hence, the problem boils down to a searching problem; but how to identify the binary search approach?? + Suppose, we partition the element as example 1, then the max of left[] = 7 and min of right[] = 3, but according to the 2nd observation, it is not valid. So, in order to have a correct max in left, I need to reduce its value and consequestly, the min of right[] should be increased. That means, I have to move leftwards in nums1 to have a correct max value in left half. */ +// Leetcode link: https://leetcode.com/problems/median-of-two-sorted-arrays/ + #include class Solution { @@ -28,7 +42,6 @@ class Solution { while(lo <= hi){ int mid1 = (lo+hi)/2; // mid of nums1 int mid2 = (n1 + n2 + 1)/2 - mid1; - // why?? => suppose nums1[] is partitioned at index 3 => nums1[3] = 7. std::pair maxleft, minright; maxleft.first = mid1 == 0 ? INT_MIN : nums1[mid1-1]; From 2ec9f8883de9db0ae744507fc78d5d1088c6b68a Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Sat, 11 Feb 2023 17:59:25 +0530 Subject: [PATCH 0090/1894] Added alternative solution using merge sort technique --- .../Median_of_Two_Sorted_Arrays_MergeSort.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp diff --git a/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp b/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp new file mode 100644 index 00000000..81d81a2d --- /dev/null +++ b/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp @@ -0,0 +1,73 @@ +/** + * Approach: + let nums1 = [1, 3, 4, 7, 10, 12], nums2 = [2, 3, 6, 15] + + In order to find the median, we need a single sorted array. So a naive approach is that, just merge the 2 sorted arrays and find the median of that array. + This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) +*/ + +# include + +class Solution { + std::vector merge(std::vector& nums1, std::vector& nums2){ + int n1 = nums1.size(); + int n2 = nums2.size(); + + int i=0, j=0; + + std::vector res; + while(i < n1 and j < n2){ + if(nums1[i] < nums2[j]){ + res.push_back(nums1[i]); + i++; + } else { + res.push_back(nums2[j]); + j++; + } + } + + while(i < n1){ + res.push_back(nums1[i]); + i++; + } + + while(j < n2){ + res.push_back(nums2[j]); + j++; + } + + return res; + } +public: + double findMedianSortedArrays(std::vector& nums1, std::vector& nums2) { + std::vector sortedarr = merge(nums1, nums2); + + if(sortedarr.size() % 2 == 0){ + return (sortedarr[sortedarr.size()/2] + sortedarr[sortedarr.size()/2 - 1])/2.0; + } else { + return (double)sortedarr[sortedarr.size()/2]; + } + } +}; + +int main(int argc, char const* argv[]) { + int n; + + std::cin >> n; + std::vector arr1(n, 0); + for (int i = 0;i < n;i++) { + std::cin >> arr1[i]; + } + + std::cin >> n; + std::vector arr2(n, 0); + for (int i = 0;i < n;i++) { + std::cin >> arr2[i]; + } + + Solution sol = Solution(); + double res = sol.findMedianSortedArrays(arr1, arr2); + + std::cout << res << "\n"; + return 0; +} \ No newline at end of file From 7100c7ac300560c9b97edf04394bfea6a6842f0f Mon Sep 17 00:00:00 2001 From: Aditya Mukherjee Date: Sat, 11 Feb 2023 18:00:28 +0530 Subject: [PATCH 0091/1894] Updated .gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 9049112d..d93b707e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ .vscode .idea -.exe \ No newline at end of file +*.exe \ No newline at end of file From 72c1515e36560c5519c55534113e853ac923b37f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Feb 2023 19:33:44 +0530 Subject: [PATCH 0092/1894] keep single folder for hash table --- {HashTable => Hash Table}/coloful_number.java | 0 {HashTable => Hash Table}/count_distinct_elements.java | 0 {HashTable => Hash Table}/count_elements.java | 0 {HashTable => Hash Table}/count_subarray_zero_sum.java | 0 {HashTable => Hash Table}/count_unique_elements.java | 0 {HashTable => Hash Table}/first_non_repeating_element.java | 0 {HashTable => Hash Table}/first_repeating_number.java | 0 {HashTable => Hash Table}/frequency_of_elements.java | 0 {HashTable => Hash Table}/number_of_good_pairs.java | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename {HashTable => Hash Table}/coloful_number.java (100%) rename {HashTable => Hash Table}/count_distinct_elements.java (100%) rename {HashTable => Hash Table}/count_elements.java (100%) rename {HashTable => Hash Table}/count_subarray_zero_sum.java (100%) rename {HashTable => Hash Table}/count_unique_elements.java (100%) rename {HashTable => Hash Table}/first_non_repeating_element.java (100%) rename {HashTable => Hash Table}/first_repeating_number.java (100%) rename {HashTable => Hash Table}/frequency_of_elements.java (100%) rename {HashTable => Hash Table}/number_of_good_pairs.java (100%) diff --git a/HashTable/coloful_number.java b/Hash Table/coloful_number.java similarity index 100% rename from HashTable/coloful_number.java rename to Hash Table/coloful_number.java diff --git a/HashTable/count_distinct_elements.java b/Hash Table/count_distinct_elements.java similarity index 100% rename from HashTable/count_distinct_elements.java rename to Hash Table/count_distinct_elements.java diff --git a/HashTable/count_elements.java b/Hash Table/count_elements.java similarity index 100% rename from HashTable/count_elements.java rename to Hash Table/count_elements.java diff --git a/HashTable/count_subarray_zero_sum.java b/Hash Table/count_subarray_zero_sum.java similarity index 100% rename from HashTable/count_subarray_zero_sum.java rename to Hash Table/count_subarray_zero_sum.java diff --git a/HashTable/count_unique_elements.java b/Hash Table/count_unique_elements.java similarity index 100% rename from HashTable/count_unique_elements.java rename to Hash Table/count_unique_elements.java diff --git a/HashTable/first_non_repeating_element.java b/Hash Table/first_non_repeating_element.java similarity index 100% rename from HashTable/first_non_repeating_element.java rename to Hash Table/first_non_repeating_element.java diff --git a/HashTable/first_repeating_number.java b/Hash Table/first_repeating_number.java similarity index 100% rename from HashTable/first_repeating_number.java rename to Hash Table/first_repeating_number.java diff --git a/HashTable/frequency_of_elements.java b/Hash Table/frequency_of_elements.java similarity index 100% rename from HashTable/frequency_of_elements.java rename to Hash Table/frequency_of_elements.java diff --git a/HashTable/number_of_good_pairs.java b/Hash Table/number_of_good_pairs.java similarity index 100% rename from HashTable/number_of_good_pairs.java rename to Hash Table/number_of_good_pairs.java From d49cce2ebbfdcd4008c9a2b575ee162119117797 Mon Sep 17 00:00:00 2001 From: tsak Date: Sat, 11 Feb 2023 16:09:44 +0200 Subject: [PATCH 0093/1894] my first commit --- Math/countPrimes.java | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Math/countPrimes.java diff --git a/Math/countPrimes.java b/Math/countPrimes.java new file mode 100644 index 00000000..e92143d7 --- /dev/null +++ b/Math/countPrimes.java @@ -0,0 +1,56 @@ +/* Implement countPrimes(n), which calculates the number of primes that are strictly smaller than n. + +Example 1: +Input: n=0 +Output: 0 + +Example 2: +Input: n=10 +Output: 4 + +Example 3: +Input: n=155 +Output: 36 + +Example 4: +Input: n=5000000 +Ouput: 348513 + +Constraints: +0 <= n <= 5 * 10^6 + +*/ + +class Solution { + + int countPrimes(int n) { + if (n<=2) { + return 0; + } + + int counter = 0; + /* notPrimesArray: Array in which every cell represents whether + its index number is non-prime or not. Initially every number is + considered prime (default value: false), but the opposite might be + determined later. */ + boolean[] notPrimesArray = new boolean[n]; + + for (int i=2; i=2 multiplied by any integer j>=2 is not prime. + So the corresponding value of i*j in the array is changed to true. + This will only affect cells with an index number higher than the + current i, as i*j>i for any j>=2.*/ + for (int j=2; i*j Date: Sat, 11 Feb 2023 20:16:03 +0530 Subject: [PATCH 0094/1894] Added solution for count primes --- Leetcode/count_primes.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Leetcode/count_primes.py diff --git a/Leetcode/count_primes.py b/Leetcode/count_primes.py new file mode 100644 index 00000000..d0692e2a --- /dev/null +++ b/Leetcode/count_primes.py @@ -0,0 +1,39 @@ +# Given an integer n, return the number of prime numbers that are strictly less than n. +# Program Author: https://github.com/abhis1n + +# Solution- We will be using Sieve of Eratosthenes to solve the given problem + +class Solution: + def countPrimes(self, n: int) -> int: + # First we declare an array of + # size n and initialize all of + # its values with False + nums = [False] * n + + # Storing primes in ans variable + ans = 0 + + for num in range(2, n): + # if the num index in nums list + # is True, if block runs and loop + # is continued to next iteration + if nums[num]: + continue + + # else if the num index in nums list + # is False, ans variable is incremented + # by 1 and the indexes of all values + # greater than num and divisible by num + # are updated with True value, since they + # can not be prime + else: + ans += 1 + nums[num*num:n:num] = [True] * ((n - 1) // num - num + 1) + + return ans + +if __name__=='__main__': + n = int(input()) + solution = Solution() + answer = solution.countPrimes(n) + print(answer) \ No newline at end of file From 11c8ed35b05ce9dc18087b02320ed26b533f08b8 Mon Sep 17 00:00:00 2001 From: Ajay Patel <81469239+Ajay051839@users.noreply.github.com> Date: Sun, 12 Feb 2023 04:08:05 +0530 Subject: [PATCH 0095/1894] Added solution to Find number of good pairs in C++ --- Arrays/FindNumberOfGoodPairs_in_array.cpp | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Arrays/FindNumberOfGoodPairs_in_array.cpp diff --git a/Arrays/FindNumberOfGoodPairs_in_array.cpp b/Arrays/FindNumberOfGoodPairs_in_array.cpp new file mode 100644 index 00000000..5135c25c --- /dev/null +++ b/Arrays/FindNumberOfGoodPairs_in_array.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +//function to solve this problem +int solve(int arr[],int n){ + int count=0; + for(int i=0;i>n; + int arr[n];//defining array + + //inputs i.e. array elements-- + for(int i=0;i>arr[i]; + } + + //printing ans-- + cout< Date: Sun, 12 Feb 2023 04:21:01 +0530 Subject: [PATCH 0096/1894] Find_number_of_good_pairs.py --- FindNumberOfGoodPairs_in_array.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 FindNumberOfGoodPairs_in_array.py diff --git a/FindNumberOfGoodPairs_in_array.py b/FindNumberOfGoodPairs_in_array.py new file mode 100644 index 00000000..8b650cdf --- /dev/null +++ b/FindNumberOfGoodPairs_in_array.py @@ -0,0 +1,8 @@ +def solve(nums): + count=0 + n=len(nums) + for i in range(n): + for j in range(i+1,n): + if nums[i] == nums[j]: + count+=1 + return count From a7b91f67244b1f406210aed4dfaee247d0d4787b Mon Sep 17 00:00:00 2001 From: Ajay Patel <81469239+Ajay051839@users.noreply.github.com> Date: Sun, 12 Feb 2023 04:29:27 +0530 Subject: [PATCH 0097/1894] reverse_linked_list.cpp --- Linked List/reverse_linked_list.cpp | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Linked List/reverse_linked_list.cpp diff --git a/Linked List/reverse_linked_list.cpp b/Linked List/reverse_linked_list.cpp new file mode 100644 index 00000000..517f411f --- /dev/null +++ b/Linked List/reverse_linked_list.cpp @@ -0,0 +1,31 @@ +//iterative solution----- + +ListNode* reverseList(ListNode* head) { + if(head==NULL){ + return NULL; + } + ListNode* prev=NULL; + ListNode* curr=head; + ListNode* next; + while(curr!=NULL){ + next=curr->next; + curr->next=prev; + prev=curr; + curr=next; + } + curr=prev; + return curr; + + } + + +//recursive solution--- +ListNode* reverseList(ListNode* head) { + if (!head || !(head -> next)) { + return head; + } + ListNode* node = reverseList(head -> next); + head -> next -> next = head; + head -> next = NULL; + return node; + } From 26c694f6194e19be96d9ad5fd009c68caec341c6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 12:10:06 +0530 Subject: [PATCH 0098/1894] add longest common prefix --- Strings/longest_common_prefix.cpp | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Strings/longest_common_prefix.cpp diff --git a/Strings/longest_common_prefix.cpp b/Strings/longest_common_prefix.cpp new file mode 100644 index 00000000..8dea0140 --- /dev/null +++ b/Strings/longest_common_prefix.cpp @@ -0,0 +1,47 @@ +/* +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + + + +Example 1: + +Input: strs = ["flower","flow","flight"] +Output: "fl" +Example 2: + +Input: strs = ["dog","racecar","car"] +Output: "" +Explanation: There is no common prefix among the input strings. + + +Constraints: + +1 <= strs.length <= 200 +0 <= strs[i].length <= 200 +strs[i] consists of only lowercase English letters. + +Time complexity : O(strs) +*/ + +#include + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if(strs.size() == 0) return ""; + string ans = ""; + // fix one string and check the common prefix of this string with other strings + // s is the smallest string, so longest cant be greater than smallest string in array + string s = *min_element(strs.begin(), strs.end()); + for(int i = 0; i < s.size(); i++){ + for(int j = 0; j < strs.size(); j++){ + if(s[i] != strs[j][i]) + return ans; + } + ans.push_back(s[i]); + } + return ans; + } +}; \ No newline at end of file From 0f7b517ccb70d3b304b1b649197311eb028eac41 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 12:21:45 +0530 Subject: [PATCH 0099/1894] add remove nth node from end of list --- .../linked_list_remoev_nth_node_from_end.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Linked List/linked_list_remoev_nth_node_from_end.cpp diff --git a/Linked List/linked_list_remoev_nth_node_from_end.cpp b/Linked List/linked_list_remoev_nth_node_from_end.cpp new file mode 100644 index 00000000..8e2087fb --- /dev/null +++ b/Linked List/linked_list_remoev_nth_node_from_end.cpp @@ -0,0 +1,67 @@ +/* +Given the head of a linked list, remove the nth node from the end of the list and return its head. + +Input: head = [1,2,3,4,5], n = 2 +Output: [1,2,3,5] +Example 2: + +Input: head = [1], n = 1 +Output: [] +Example 3: + +Input: head = [1,2], n = 1 +Output: [1] + + +Constraints: + +The number of nodes in the list is sz. +1 <= sz <= 30 +0 <= Node.val <= 100 +1 <= n <= sz + +*/ +#include +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ + + +/* +In order to solve this problem in only one pass and O(1) extra space, +however, we would need to find a way to both reach the end of the list with one pointer +and also reach the n'th node from the end simultaneously with a second pointer. +To do that, we can simply stagger our two pointers by n nodes by giving the first pointer +(fast) a head start before starting the second pointer (slow). Doing this will cause +slow to reach the n'th node from the end at the same time that fast reaches the end. +*/ + +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode* slow = head; + ListNode* fast = head; + if(head == NULL || head->next == NULL) + return NULL; + while(n--){ + fast = fast->next; + } + if(fast == NULL) + return slow->next; + while(fast->next != NULL){ + slow = slow->next; + fast = fast->next; + } + ListNode* temp = slow->next; + slow->next = slow->next->next; + delete temp; + return head; + } +}; \ No newline at end of file From 20a11e897379467dc20893d2bb41b30d21f69215 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 12:21:58 +0530 Subject: [PATCH 0100/1894] rename file --- ...node_from_end.cpp => linked_list_remove_nth_node_from_end.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Linked List/{linked_list_remoev_nth_node_from_end.cpp => linked_list_remove_nth_node_from_end.cpp} (100%) diff --git a/Linked List/linked_list_remoev_nth_node_from_end.cpp b/Linked List/linked_list_remove_nth_node_from_end.cpp similarity index 100% rename from Linked List/linked_list_remoev_nth_node_from_end.cpp rename to Linked List/linked_list_remove_nth_node_from_end.cpp From 7d22a0768b0f6accde3bf7e93af547e5733af7e0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 12:28:06 +0530 Subject: [PATCH 0101/1894] add reduce number to zero --- Bit Manipulation/reduce_to_zero.cpp | 55 +++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Bit Manipulation/reduce_to_zero.cpp diff --git a/Bit Manipulation/reduce_to_zero.cpp b/Bit Manipulation/reduce_to_zero.cpp new file mode 100644 index 00000000..fb0a8674 --- /dev/null +++ b/Bit Manipulation/reduce_to_zero.cpp @@ -0,0 +1,55 @@ +/* +Given an integer num, return the number of steps to reduce it to zero. + +In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + + +Example 1: + +Input: num = 14 +Output: 6 +Explanation: +Step 1) 14 is even; divide by 2 and obtain 7. +Step 2) 7 is odd; subtract 1 and obtain 6. +Step 3) 6 is even; divide by 2 and obtain 3. +Step 4) 3 is odd; subtract 1 and obtain 2. +Step 5) 2 is even; divide by 2 and obtain 1. +Step 6) 1 is odd; subtract 1 and obtain 0. +Example 2: + +Input: num = 8 +Output: 4 +Explanation: +Step 1) 8 is even; divide by 2 and obtain 4. +Step 2) 4 is even; divide by 2 and obtain 2. +Step 3) 2 is even; divide by 2 and obtain 1. +Step 4) 1 is odd; subtract 1 and obtain 0. +Example 3: + +Input: num = 123 +Output: 12 + + +Constraints: + +0 <= num <= 106 +*/ + +#include +class Solution { +public: + int numberOfSteps (int num) { + int count = 0; + while(num){ + if(!(num & 1)){ + num = num >> 1; + } + else{ + num--; + } + count++; + } + return count; + } +}; \ No newline at end of file From 2b4a2c21d8a413041e65fa721c33b59193acc8d3 Mon Sep 17 00:00:00 2001 From: Ajay Patel <81469239+Ajay051839@users.noreply.github.com> Date: Sun, 12 Feb 2023 12:32:21 +0530 Subject: [PATCH 0102/1894] Find_number_good_pairs_in_array.cpp --- Arrays/FindNumberOfGoodPairs_in_array.cpp | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Arrays/FindNumberOfGoodPairs_in_array.cpp diff --git a/Arrays/FindNumberOfGoodPairs_in_array.cpp b/Arrays/FindNumberOfGoodPairs_in_array.cpp new file mode 100644 index 00000000..662bb172 --- /dev/null +++ b/Arrays/FindNumberOfGoodPairs_in_array.cpp @@ -0,0 +1,42 @@ +//Given an array of integers nums,we have to return the number of good pairs. + +//A pair (i, j) is called good if nums[i] == nums[j] and i < j. means our search space will start from i+1 for nums[i] as it is mentioned that i Date: Sun, 12 Feb 2023 18:44:41 +0530 Subject: [PATCH 0103/1894] Number_of_Substrings_With_Only_1s.cpp in reference to Issue #515 --- Math/Number_of_Substrings_With_Only_1s.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Math/Number_of_Substrings_With_Only_1s.cpp diff --git a/Math/Number_of_Substrings_With_Only_1s.cpp b/Math/Number_of_Substrings_With_Only_1s.cpp new file mode 100644 index 00000000..66535bcb --- /dev/null +++ b/Math/Number_of_Substrings_With_Only_1s.cpp @@ -0,0 +1,21 @@ +/* +first we count continuos number of ones and if we have n continuos 1's than total substring = (n*(n+1))/2. Using this we can count all substring and add them and return. +using this property (a*b)%mod = ((a%mod)*(b%mod))%mod +*/ +class Solution { +public: + int mod = 1000000007; + int numSub(string s) { + long long cnt = 0,ans=0; + for(int i = 0;i Date: Sun, 12 Feb 2023 21:15:42 +0530 Subject: [PATCH 0104/1894] add description --- Math/Number_of_Substrings_With_Only_1s.cpp | 31 +++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Math/Number_of_Substrings_With_Only_1s.cpp b/Math/Number_of_Substrings_With_Only_1s.cpp index 66535bcb..b118f7d5 100644 --- a/Math/Number_of_Substrings_With_Only_1s.cpp +++ b/Math/Number_of_Substrings_With_Only_1s.cpp @@ -1,5 +1,34 @@ /* -first we count continuos number of ones and if we have n continuos 1's than total substring = (n*(n+1))/2. Using this we can count all substring and add them and return. +Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. + + + +Example 1: + +Input: s = "0110111" +Output: 9 +Explanation: There are 9 substring in total with only 1's characters. +"1" -> 5 times. +"11" -> 3 times. +"111" -> 1 time. +Example 2: + +Input: s = "101" +Output: 2 +Explanation: Substring "1" is shown 2 times in s. +Example 3: + +Input: s = "111111" +Output: 21 +Explanation: Each substring contains only 1's characters. + + +Constraints: + +1 <= s.length <= 105 +s[i] is either '0' or '1'. + +Approach: First we count continuos number of ones and if we have n continuos 1's than total substring = (n*(n+1))/2. Using this we can count all substring and add them and return. using this property (a*b)%mod = ((a%mod)*(b%mod))%mod */ class Solution { From d503d9e2d96b1a62e996f93db233df71c78f752f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 21:16:16 +0530 Subject: [PATCH 0105/1894] modify name --- ...dPairs_in_array.cpp => find_number_of_good_pairs_in_array.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{FindNumberOfGoodPairs_in_array.cpp => find_number_of_good_pairs_in_array.cpp} (100%) diff --git a/Arrays/FindNumberOfGoodPairs_in_array.cpp b/Arrays/find_number_of_good_pairs_in_array.cpp similarity index 100% rename from Arrays/FindNumberOfGoodPairs_in_array.cpp rename to Arrays/find_number_of_good_pairs_in_array.cpp From 8b41570076422aa1335e1125c12ee3e490dff87a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 21:19:05 +0530 Subject: [PATCH 0106/1894] add description --- Linked List/reverse_linked_list.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Linked List/reverse_linked_list.cpp b/Linked List/reverse_linked_list.cpp index 517f411f..6bd9d91b 100644 --- a/Linked List/reverse_linked_list.cpp +++ b/Linked List/reverse_linked_list.cpp @@ -1,3 +1,32 @@ + +/* +Given the head of a singly linked list, reverse the list, and return the reversed list. + + + +Example 1: + + +Input: head = [1,2,3,4,5] +Output: [5,4,3,2,1] +Example 2: + + +Input: head = [1,2] +Output: [2,1] +Example 3: + +Input: head = [] +Output: [] + + +Constraints: + +The number of nodes in the list is the range [0, 5000]. +-5000 <= Node.val <= 5000 + +*/ + //iterative solution----- ListNode* reverseList(ListNode* head) { From 4593b4c154fd2d732c922ec86d7095b7f8ec680d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Feb 2023 21:22:35 +0530 Subject: [PATCH 0107/1894] move file in correct folder and add description --- Arrays/find_number_of_good_pairs_in_array.py | 39 ++++++++++++++++++++ FindNumberOfGoodPairs_in_array.py | 8 ---- 2 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 Arrays/find_number_of_good_pairs_in_array.py delete mode 100644 FindNumberOfGoodPairs_in_array.py diff --git a/Arrays/find_number_of_good_pairs_in_array.py b/Arrays/find_number_of_good_pairs_in_array.py new file mode 100644 index 00000000..83e79083 --- /dev/null +++ b/Arrays/find_number_of_good_pairs_in_array.py @@ -0,0 +1,39 @@ +''' +Given an array of integers nums,we have to return the number of good pairs. + +A pair (i, j) is called good if nums[i] == nums[j] and i < j. means our search space will start from i+1 for nums[i] as it is mentioned that i Date: Sun, 12 Feb 2023 21:25:43 +0530 Subject: [PATCH 0108/1894] remove duplicate file --- Arrays/FindNumberOfGoodPairs_in_array.cpp | 34 ------------------- Arrays/find_number_of_good_pairs_in_array.cpp | 34 +++++++++++++++---- 2 files changed, 28 insertions(+), 40 deletions(-) delete mode 100644 Arrays/FindNumberOfGoodPairs_in_array.cpp diff --git a/Arrays/FindNumberOfGoodPairs_in_array.cpp b/Arrays/FindNumberOfGoodPairs_in_array.cpp deleted file mode 100644 index 5135c25c..00000000 --- a/Arrays/FindNumberOfGoodPairs_in_array.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -using namespace std; - -//function to solve this problem -int solve(int arr[],int n){ - int count=0; - for(int i=0;i>n; - int arr[n];//defining array - - //inputs i.e. array elements-- - for(int i=0;i>arr[i]; - } - - //printing ans-- - cout< +using namespace std; + +//function to solve this problem +int solve(int arr[],int n){ + int count = 0; + for(int i = 0; i < n; i++){ + for(int j = i + 1; j < n; j++){ + if(arr[i] == arr[j]){ count++; } } } return count; } + + +int main() +{ + int n;//number of elements in array + cin >> n; + int arr[n];//defining array + + //inputs i.e. array elements-- + for(int i = 0; i < n; i++){ + cin >> arr[i]; + } + + //printing ans-- + cout << solve(arr,n); + + + return 0; +} From e9c1989444ca098df2feb46cc091ddb909593190 Mon Sep 17 00:00:00 2001 From: viraj-s15 Date: Sun, 12 Feb 2023 22:57:33 +0530 Subject: [PATCH 0109/1894] added-substring-with-1s --- Strings/no_of_substrings_with_1s.py | 104 ++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Strings/no_of_substrings_with_1s.py diff --git a/Strings/no_of_substrings_with_1s.py b/Strings/no_of_substrings_with_1s.py new file mode 100644 index 00000000..11ffe852 --- /dev/null +++ b/Strings/no_of_substrings_with_1s.py @@ -0,0 +1,104 @@ +# ---------------------------------------------------------------- +# 1513. Number of Substrings With Only 1s +# ---------------------------------------------------------------- + +""" +Input -> A binary string +Output -> An integer + +The goal of the problem is to find out the number of substrings in the +given binary string that consists of 1's only. For example : + +Sample Input: + +a) Input 1 = "0110111" + Output 1 = 9 + There are 9 substrings in total with only 1's characters + +b) Input 2 = "101" + Output 2 = 2 + There are 2 substrings in total with only 1's characters + +c) Input 3 = "1" + Output 3 = 1 + There is only one substring in this string that contains 1 + +d) Input 4 = "111111" + Output 4 = 21 + There is only 12 substrings in this string that contain only 1's + + +How to tackle this problem? + +Solution 1) + +This is the brute force solution and is extremely simple. We look at all +the substrings and simply decide which one ha only 1's by iterating +over each individual substring. This however is a tedious solution and +not very optimised. The time complexity for this solution would be +O(N^3). This is not a good solution. However, it is the first solution that +comes to mind. + +Solution 2) + +We can take advantage of a built in python function. This function is +str.slpit(), it splits a string into an array depending upon the breakpoint +that we provide it. What we can do is, split the string by 0's. This results +in an array that consists of all the substrings in the array that +consist of 1's only. We can now start to notice a pattern with. + +If Input = "1" Output = 1 +If Input = "11" Output = 2 +If Input = "111" Output = 6 +If Input = "1111" Output = 10 +If Input = "11111" Output = 15 + +By looking at the above results we can state that the number of +substrings in a given string can be calculated by using ((n*(n+1) )/ 2) + +This leads to another fact, that we dont really need to find all of the +substrings to find their total. The time complexity for this approach will be +O(N) which is much better than ourbrute force approach. + +**Note : This approach can be used in any other language as well + +Coding the second approach + +""" + + +class Solution: + def numSub(self, s: str) -> int: + # This will get us all the subtrings that contain 1's only + substrings = s.split("0") + + sub_sum = 0 + for substring in substrings: + sub_sum += len(substring) * (len(substring) + 1) // 2 + # Implementing the formula that we derived above + return sub_sum + # finally return the sum + + +""" +Another problem that we face is when we try to run the above code +on leetcode, it will not pass all the test cases. + +Short Answer: The numbers get too big and it simply overflows. +To avoid this overflow, we use the modulo operator. + +Long Answer: We use the expression -> num % (10 ** 9 + 7) calculates the remainder of +num divided by 10 ** 9 + 7. The value 10 ** 9 + 7 is a large constant that +is used as the modulo. The purpose of taking the modulo is to avoid large numbers that might +overflow the maximum value that can be stored in an integer data type. +When the result of an operation is larger than the maximum value that can +be stored in an integer, the result wraps around to a negative value. +Taking the modulo avoids this issue by reducing the result to a value that +can be stored in an integer data type. + + +To fix this issue simply replace the return statement with the below line + +return sub_sum % (10 ** 9 + 7) + +""" From 9ff67edae573aac5917e51141d62ac239a260bd7 Mon Sep 17 00:00:00 2001 From: naveenkumar Date: Mon, 13 Feb 2023 00:17:46 +0530 Subject: [PATCH 0110/1894] add java solution for finding number of good pairs in an array --- Arrays/FindNoOfGoodPairs.java | 132 ++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 Arrays/FindNoOfGoodPairs.java diff --git a/Arrays/FindNoOfGoodPairs.java b/Arrays/FindNoOfGoodPairs.java new file mode 100644 index 00000000..d279920a --- /dev/null +++ b/Arrays/FindNoOfGoodPairs.java @@ -0,0 +1,132 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Scanner; + +/* +Given an array of integers nums, return the number of good pairs. + +A pair (i, j) is called good if nums[i] == nums[j] and i < j. + +Example 1: + +Input: nums = [1,2,3,1,1,3] +Output: 4 +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. +Example 2: + +Input: nums = [1,1,1,1] +Output: 6 +Explanation: Each pair in the array are good. +Example 3: + +Input: nums = [1,2,3] +Output: 0 + +Constraints: + +1 <= nums.length <= 100 +1 <= nums[i] <= 100 + +*/ +public class FindNoOfGoodPairs{ + + /* + Brute Force solution: + time complexity : O(n^2) + space complexity : O(1) + */ + public static int countNoOfGoodPairsBF(List array){ + int len = array.size(); + int goodPairs=0; + + for(int i=0; i array){ + int len = array.size(); + int goodPairs = 0; + + HashMap occurence = new HashMap<>(); + + // construct the occurence map + for(int i=0; i 1){ + goodPairs += ( (freq-1)*(freq) / 2 ); + } + } + + return goodPairs; + } + + public static void main(String args[]){ + + Scanner sc = new Scanner(System.in); + int arrLen = sc.nextInt(); + + List array = new ArrayList<>(); + + for(int i=0; i Date: Sun, 12 Feb 2023 21:04:18 +0200 Subject: [PATCH 0111/1894] issues #491, #501 --- Math/countNumbersWithUniqueDigits.java | 58 ++++++++++++++++++++++++++ Math/countPrimes.java | 3 ++ 2 files changed, 61 insertions(+) create mode 100644 Math/countNumbersWithUniqueDigits.java diff --git a/Math/countNumbersWithUniqueDigits.java b/Math/countNumbersWithUniqueDigits.java new file mode 100644 index 00000000..fc395738 --- /dev/null +++ b/Math/countNumbersWithUniqueDigits.java @@ -0,0 +1,58 @@ +/* Implement countNumbersWithUniqueDigits(n), which calculates the number of +all numbers with unique digits, x, where 0 <= x < 10^n. + +Explanation: +- For n=0, the answer is 1 (only the number 0, here considered to have 0 digits). +- For n=1, the answer is the number of one-digit numbers with unique digits (9), + plus the result for n=0 (1). +- For n=2, the answer is the number of two-digit numbers with unique digits (between + 10 and 99), plus the result for n=1. The number of two-digit numbers with unique digits + is 9*9 (9 possible first digits between 1-9, then 9 possible second digits between 0-9 + that are different from the first digit). +- For n=3, the answer is the number of three-digit number with unique digits (between 100 + and 999), plus the result for n=2. The number of three-digit numbers with unique digits + is 9*9*8 (9 possible first digits between 1-9, then 9 possible second digits between 0-9 + that are different from the first digit, then 8 possible third digits between 0-9 that are + different from the first two). +- And so on, using recursive calls of the same function. +Note: There are no numbers with 11 or more digits that have unique digits. So for n>=10, the +result will be the same for any n. + +Example 1: +Input: n=3 +Output: 739 + +Example 2: +Input: n=6 +Output: 168571 + +Example 3: +Input: n=8 +Output: 2345851 + +Constraints: +n >= 0 + +Time complexity: O(n) +Space complexity: O(n) + +*/ + +class Solution { + + public int countNumbersWithUniqueDigits(int n) { + + if (n==0) { + return 1; + } + + int counter = 9; + for (int i=1; i Date: Mon, 13 Feb 2023 07:10:51 +0530 Subject: [PATCH 0112/1894] Add First and Last Position of x in array --- Binary_Search/FirstLastPos.java | 72 +++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Binary_Search/FirstLastPos.java diff --git a/Binary_Search/FirstLastPos.java b/Binary_Search/FirstLastPos.java new file mode 100644 index 00000000..4d9e8a94 --- /dev/null +++ b/Binary_Search/FirstLastPos.java @@ -0,0 +1,72 @@ +/* Given a sorted array arr containing n elements with possibly duplicate elements, +the task is to find indexes of first and last occurrences of an element x in the given array. + +Example 1: Input: arr [] = [ 1, 3, 5, 5, 5, 5, 67, 123, 125 ] , target = 5 +OUTPUT: [2 5] +Explanation: First occurrence of 5 is at index 2 and last occurrence of 5 is at index 5. + +Example 2: Input: arr[] = [1,2,3,,5,6,7,8],target = 4 +OUTPUT: [-1,-1] + +APPROACH: + #We will separately write methods for first occurence and last occurence of the element + + # Follows the standard binary search algorithm with little moddification for first and last occurence + # For the first occurence , return the start index at the end of the loop + # For the last occurence , return the end index at the end of loop*/ +import java.util.*; +public class FirstLastPos{ + public static int firstOccurence(int[] arr,int target){ + int start = 0,end=arr.length-1; + while(start <= end){ + int mid = start + (end-start)/2; + if (arr[mid]== target){ + end = mid -1; + } + else if(arr[mid] > target){ + end = mid -1; + } + else if(arr[mid] < target){ + start = mid + 1; + } + } + if(start < arr.length && arr[start] == target){ + return start; + } + else{ + return -1; + } + } + + public static int lastOccurence(int[] arr,int target){ + int start = 0,end=arr.length-1; + while(start <= end){ + int mid = start + (end-start)/2; + if (arr[mid]== target){ + start = mid + 1; + } + else if(arr[mid] > target){ + end = mid -1; + } + else if(arr[mid] < target){ + start = mid + 1; + } + } + if(end >= 0 && arr[end] == target){ + return end; + } + else{ + return -1; + } + } + + public static void main(String[] args){ + int[] arr = {1,5,7,7,7,9,11,14}; + int target = 7; + int[] result = new int[2]; + result[0] = firstOccurence(arr,target); + result[1] = lastOccurence(arr,target); + System.out.println(Arrays.toString(result)); + + } +} \ No newline at end of file From 9e59f2e3b6f65339f9a9f625eda013ac842620a9 Mon Sep 17 00:00:00 2001 From: Ajay Patel <81469239+Ajay051839@users.noreply.github.com> Date: Mon, 13 Feb 2023 17:02:30 +0530 Subject: [PATCH 0113/1894] Find_majority_element_in_C++.cpp --- Arrays/Find_Majority_Element_in_C++.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Arrays/Find_Majority_Element_in_C++.cpp diff --git a/Arrays/Find_Majority_Element_in_C++.cpp b/Arrays/Find_Majority_Element_in_C++.cpp new file mode 100644 index 00000000..1476273e --- /dev/null +++ b/Arrays/Find_Majority_Element_in_C++.cpp @@ -0,0 +1,20 @@ +//approach---- +//here we make a map which maintain the frequency of each array element while traversing through the element. +//and also check the frequency at the same time..if frequency(occurence) of any element is greater than (n/2) at anytime we will return that element. +// suppose if no such element exist return simply -1. + +code---- +Find Majority Element in C++ +class Solution { +public: + int majorityElement(vector& nums) { + + unordered_mapmp; + for(int i:nums){ + if(++mp[i]>nums.size()/2){ + return i; + } + } + return -1; + } +}; From 73f01e65de727311d01fc841ef6aa988e15f93d6 Mon Sep 17 00:00:00 2001 From: anestistsak <72695988+anestistsak@users.noreply.github.com> Date: Mon, 13 Feb 2023 19:03:47 +0200 Subject: [PATCH 0114/1894] Add files via upload --- Strings/lengthOfLongestSubstring.java | 49 +++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Strings/lengthOfLongestSubstring.java diff --git a/Strings/lengthOfLongestSubstring.java b/Strings/lengthOfLongestSubstring.java new file mode 100644 index 00000000..446cef52 --- /dev/null +++ b/Strings/lengthOfLongestSubstring.java @@ -0,0 +1,49 @@ +/* Implement lengthOfLongestSubstring(s), which calculates the length of the longest possible substring that does not contain repeating characters. + +Example 1: +Input: "abcabcbaba" +Output: 3 + +Example 2: +Input: "dddddddd" +Output: 1 + +Example 3: +Input: "pwwkewo" +Output: 4 + +Constraints: +0 <= s.length <= 5 * 10^4 + +Time complexity: O(n^2) +Space complexity: O(1) + +*/ + +class Solution { + public int lengthOfLongestSubstring(String s) { + int length = s.length(); + if (length==0) { + return 0; + } + + int max = 1; + // Aiming to find substring of s that starts at index i and ends at j-1. + int i = 0; + int j = i+1; + + while (j max) { + max = j-i; + } + + i++; + } + + return max; + } +} From a76fabe5f7991c0d648c57edefe3b769da73fd70 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Feb 2023 23:09:17 +0530 Subject: [PATCH 0115/1894] add description and change file name --- ...t_in_C++.cpp => find_majority_element.cpp} | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) rename Arrays/{Find_Majority_Element_in_C++.cpp => find_majority_element.cpp} (56%) diff --git a/Arrays/Find_Majority_Element_in_C++.cpp b/Arrays/find_majority_element.cpp similarity index 56% rename from Arrays/Find_Majority_Element_in_C++.cpp rename to Arrays/find_majority_element.cpp index 1476273e..88b8685d 100644 --- a/Arrays/Find_Majority_Element_in_C++.cpp +++ b/Arrays/find_majority_element.cpp @@ -1,9 +1,35 @@ +/* +Given an array nums of size n, return the majority element. + +The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. + + + +Example 1: + +Input: nums = [3,2,3] +Output: 3 +Example 2: + +Input: nums = [2,2,1,1,1,2,2] +Output: 2 + + +Constraints: + +n == nums.length +1 <= n <= 5 * 104 +-109 <= nums[i] <= 109 + + +Follow-up: Could you solve the problem in linear time and in O(1) space? +*/ + //approach---- //here we make a map which maintain the frequency of each array element while traversing through the element. //and also check the frequency at the same time..if frequency(occurence) of any element is greater than (n/2) at anytime we will return that element. // suppose if no such element exist return simply -1. -code---- Find Majority Element in C++ class Solution { public: From 2cb5107db499606737a00db396d8f989d1ad358a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Feb 2023 23:11:45 +0530 Subject: [PATCH 0116/1894] fmt code --- Arrays/find_majority_element.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Arrays/find_majority_element.cpp b/Arrays/find_majority_element.cpp index 88b8685d..561a2daa 100644 --- a/Arrays/find_majority_element.cpp +++ b/Arrays/find_majority_element.cpp @@ -30,14 +30,15 @@ Follow-up: Could you solve the problem in linear time and in O(1) space? //and also check the frequency at the same time..if frequency(occurence) of any element is greater than (n/2) at anytime we will return that element. // suppose if no such element exist return simply -1. -Find Majority Element in C++ +// Find Majority Element in C++ + class Solution { public: int majorityElement(vector& nums) { unordered_mapmp; - for(int i:nums){ - if(++mp[i]>nums.size()/2){ + for(int i : nums){ + if(++mp[i] > nums.size() / 2) { return i; } } From 98d4f0c70b014f6c2fd63cf3760e0d5661101f41 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Feb 2023 23:12:38 +0530 Subject: [PATCH 0117/1894] rename file --- Arrays/{FindNoOfGoodPairs.java => find_no_of_good_pairs.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{FindNoOfGoodPairs.java => find_no_of_good_pairs.java} (100%) diff --git a/Arrays/FindNoOfGoodPairs.java b/Arrays/find_no_of_good_pairs.java similarity index 100% rename from Arrays/FindNoOfGoodPairs.java rename to Arrays/find_no_of_good_pairs.java From ed7a1a3b196d7849e19e3d538abdabab928836d5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Feb 2023 23:12:58 +0530 Subject: [PATCH 0118/1894] rename folder --- {Queues => Queue}/queue.go | 0 {Queues => Queue}/queue_using_stack.js | 0 {Queues => Queue}/stack_using_queue.cpp | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {Queues => Queue}/queue.go (100%) rename {Queues => Queue}/queue_using_stack.js (100%) rename {Queues => Queue}/stack_using_queue.cpp (100%) diff --git a/Queues/queue.go b/Queue/queue.go similarity index 100% rename from Queues/queue.go rename to Queue/queue.go diff --git a/Queues/queue_using_stack.js b/Queue/queue_using_stack.js similarity index 100% rename from Queues/queue_using_stack.js rename to Queue/queue_using_stack.js diff --git a/Queues/stack_using_queue.cpp b/Queue/stack_using_queue.cpp similarity index 100% rename from Queues/stack_using_queue.cpp rename to Queue/stack_using_queue.cpp From 3f7570d1687a7b21bda7491a525a75a93e8a472f Mon Sep 17 00:00:00 2001 From: Kirill Onufrienko Date: Mon, 13 Feb 2023 21:10:53 +0300 Subject: [PATCH 0119/1894] Added hashed annograms solution --- Strings/group_anagrams.cpp | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Strings/group_anagrams.cpp diff --git a/Strings/group_anagrams.cpp b/Strings/group_anagrams.cpp new file mode 100644 index 00000000..07ef9fe8 --- /dev/null +++ b/Strings/group_anagrams.cpp @@ -0,0 +1,67 @@ +/* +Given an array of strings strs, group the anagrams together. You can return the answer in any order. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +Example 1: + +Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +Example 2: + +Input: strs = [""] +Output: [[""]] +Example 3: + +Input: strs = ["a"] +Output: [["a"]] + +Approach: +1. Go through the list of words +2. Sort each word. All annograms of the word would look the same being sorted. +3. Find matching bucket in map and put the word to it +4. When finished, convert the map to vector of vectors and return it + +*/ + +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> groupAnagrams(vector& strs) { + std::unordered_map> hashed_annograms; + + for (const string str: strs) { + string sorted_letters = sort_letters(str); + if (hashed_annograms.find(sorted_letters) == hashed_annograms.end()) { + hashed_annograms[sorted_letters] = vector(); + } + hashed_annograms[sorted_letters].emplace_back(str); + } + + vector> result; + result.reserve(hashed_annograms.size()); + for (const auto kv: hashed_annograms) { + result.emplace_back(kv.second); + } + + return result; + } +private: + string sort_letters(string input) { + vector chars; + chars.reserve(input.size()); + for (auto c: input) { + chars.emplace_back(c); + } + sort(chars.begin(), chars.end()); + string result(chars.begin(), chars.end()); + + return result; + } +}; From c51d978ae42e7ed5dc21a3d2b68218f66f3980b5 Mon Sep 17 00:00:00 2001 From: Prince-1110 <123498733+Prince-1110@users.noreply.github.com> Date: Tue, 14 Feb 2023 17:59:30 +0530 Subject: [PATCH 0120/1894] Sudoko solver in java --- Backtracking/sudokoSolver.java | 103 +++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Backtracking/sudokoSolver.java diff --git a/Backtracking/sudokoSolver.java b/Backtracking/sudokoSolver.java new file mode 100644 index 00000000..2651db9e --- /dev/null +++ b/Backtracking/sudokoSolver.java @@ -0,0 +1,103 @@ +/*Write a program to solve a Sudoku puzzle by filling the empty cells. + +A sudoku solution must satisfy all of the following rules: + +Each of the digits 1-9 must occur exactly once in each row. +Each of the digits 1-9 must occur exactly once in each column. +Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. +The '.' character indicates empty cells. + + + +Example 1: + + +Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] +Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] +Explanation: The input board is shown above and the only valid solution is shown below: + + */ +package Backtracking; + +public class sudokoSolver { + + + public void solveSudoku(char[][] board) { + Solver(board, 0); + } + + static boolean Solver(char[][] board , int total) + { + if(total==81) + { + return true; + } + int sr = total/9; + int sc = total%9; + + if(board[sr][sc]!='.') + { + return Solver(board, total+1); + } + for(int i=1 ; i<=9 ; i++) + { + char curr = (char) (i+'0'); + if(canElementBePlaced(board , sr , sc , curr)) + { + board[sr][sc]=curr; + if (Solver(board , total+1)) + { + return true; + } + board[sr][sc]='.'; + } + } + return false; + } + static void print(char[][] board) + { + for(int i=0; i<9 ;i++) + { + for(int j=0 ; j<9 ; j++) + { + System.out.print(board[i][j]+", "); + } + System.out.println(); + } + } + + static boolean canElementBePlaced(char[][] board , int r , int c , char k) + { + for(int i=0 ; i<9 ; i++) + { + if(board[r][i]==k) + { + return false; + } + } + + for(int j =0 ; j<9 ; j++) + { + if(board[j][c]==k) + { + return false; + } + } + + int sr = r-(r%3); + int sc = c-(c%3); + + for(int i=sr; i<=sr+2;i++) + { + for(int j=sc ; j<=sc+2; j++) + { + if (board[i][j]==k) + { + return false; + } + } + } + return true; + } + +} From 16e39defc144f1cd9f60cad3be0b4b3fb626957d Mon Sep 17 00:00:00 2001 From: Prince-1110 <123498733+Prince-1110@users.noreply.github.com> Date: Tue, 14 Feb 2023 18:00:20 +0530 Subject: [PATCH 0121/1894] Search in a rotated array. --- Binary Search/searchInRotatedArray.java | 98 +++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Binary Search/searchInRotatedArray.java diff --git a/Binary Search/searchInRotatedArray.java b/Binary Search/searchInRotatedArray.java new file mode 100644 index 00000000..467582ca --- /dev/null +++ b/Binary Search/searchInRotatedArray.java @@ -0,0 +1,98 @@ +/*There is an integer array nums sorted in ascending order (with distinct values). + +Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + +Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + +You must write an algorithm with O(log n) runtime complexity. + + + +Example 1: + +Input: nums = [4,5,6,7,0,1,2], target = 0 +Output: 4 +Example 2: + +Input: nums = [4,5,6,7,0,1,2], target = 3 +Output: -1 +Example 3: + +Input: nums = [1], target = 0 +Output: -1 + */ + + +public class searchInRotatedArray { + + //Brute force solution + + public static int searchTarget(int nums[] , int target) + { + int result = -1; + for(int i=0 ; i=target) + { + end = mid-1; + } + + else + { + start =mid+1; + } + } + + + else + { + if(nums[mid]<=target && target Date: Tue, 14 Feb 2023 18:16:56 +0530 Subject: [PATCH 0122/1894] Resolving - fixes ankit-95/data-structures-and-algorithms#374 --- sorting/MergeSort.java | 62 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sorting/MergeSort.java diff --git a/sorting/MergeSort.java b/sorting/MergeSort.java new file mode 100644 index 00000000..8fc62dcc --- /dev/null +++ b/sorting/MergeSort.java @@ -0,0 +1,62 @@ +// Merge Sort in Java + +// Merge sort is a sorting algorithm that works by dividing an array into smaller subarrays, sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array. +// In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each half, and then merge the sorted halves back together. This process is repeated until the entire array is sorted. + +// Time complexity = O(nlogn) and Space complexity = O(n). + +// Sample input = [ 4, 6, 2, 1, 3, 5] , Output = [1, 2, 3, 4, 5, 6] + +// Link for further Reading : [https://www.geeksforgeeks.org/merge-sort/] +class MergeSort { + + void mergeSort(int ar[], int p,int r){ + if(p Date: Tue, 14 Feb 2023 18:47:04 +0530 Subject: [PATCH 0123/1894] rename file --- Arrays/find_no_of_good_pairs.java | 3 +- .../{sudokoSolver.java => sudoko_solver.java} | 206 +++++++++--------- 2 files changed, 105 insertions(+), 104 deletions(-) rename Backtracking/{sudokoSolver.java => sudoko_solver.java} (96%) diff --git a/Arrays/find_no_of_good_pairs.java b/Arrays/find_no_of_good_pairs.java index d279920a..be63d9ca 100644 --- a/Arrays/find_no_of_good_pairs.java +++ b/Arrays/find_no_of_good_pairs.java @@ -10,7 +10,8 @@ A pair (i, j) is called good if nums[i] == nums[j] and i < j. Example 1: -Input: nums = [1,2,3,1,1,3] +Input: num +s = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: diff --git a/Backtracking/sudokoSolver.java b/Backtracking/sudoko_solver.java similarity index 96% rename from Backtracking/sudokoSolver.java rename to Backtracking/sudoko_solver.java index 2651db9e..c726d7e5 100644 --- a/Backtracking/sudokoSolver.java +++ b/Backtracking/sudoko_solver.java @@ -1,103 +1,103 @@ -/*Write a program to solve a Sudoku puzzle by filling the empty cells. - -A sudoku solution must satisfy all of the following rules: - -Each of the digits 1-9 must occur exactly once in each row. -Each of the digits 1-9 must occur exactly once in each column. -Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. -The '.' character indicates empty cells. - - - -Example 1: - - -Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] -Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] -Explanation: The input board is shown above and the only valid solution is shown below: - - */ -package Backtracking; - -public class sudokoSolver { - - - public void solveSudoku(char[][] board) { - Solver(board, 0); - } - - static boolean Solver(char[][] board , int total) - { - if(total==81) - { - return true; - } - int sr = total/9; - int sc = total%9; - - if(board[sr][sc]!='.') - { - return Solver(board, total+1); - } - for(int i=1 ; i<=9 ; i++) - { - char curr = (char) (i+'0'); - if(canElementBePlaced(board , sr , sc , curr)) - { - board[sr][sc]=curr; - if (Solver(board , total+1)) - { - return true; - } - board[sr][sc]='.'; - } - } - return false; - } - static void print(char[][] board) - { - for(int i=0; i<9 ;i++) - { - for(int j=0 ; j<9 ; j++) - { - System.out.print(board[i][j]+", "); - } - System.out.println(); - } - } - - static boolean canElementBePlaced(char[][] board , int r , int c , char k) - { - for(int i=0 ; i<9 ; i++) - { - if(board[r][i]==k) - { - return false; - } - } - - for(int j =0 ; j<9 ; j++) - { - if(board[j][c]==k) - { - return false; - } - } - - int sr = r-(r%3); - int sc = c-(c%3); - - for(int i=sr; i<=sr+2;i++) - { - for(int j=sc ; j<=sc+2; j++) - { - if (board[i][j]==k) - { - return false; - } - } - } - return true; - } - -} +/*Write a program to solve a Sudoku puzzle by filling the empty cells. + +A sudoku solution must satisfy all of the following rules: + +Each of the digits 1-9 must occur exactly once in each row. +Each of the digits 1-9 must occur exactly once in each column. +Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. +The '.' character indicates empty cells. + + + +Example 1: + + +Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] +Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] +Explanation: The input board is shown above and the only valid solution is shown below: + + */ +package Backtracking; + +public class sudokoSolver { + + + public void solveSudoku(char[][] board) { + Solver(board, 0); + } + + static boolean Solver(char[][] board , int total) + { + if(total==81) + { + return true; + } + int sr = total/9; + int sc = total%9; + + if(board[sr][sc]!='.') + { + return Solver(board, total+1); + } + for(int i=1 ; i<=9 ; i++) + { + char curr = (char) (i+'0'); + if(canElementBePlaced(board , sr , sc , curr)) + { + board[sr][sc]=curr; + if (Solver(board , total+1)) + { + return true; + } + board[sr][sc]='.'; + } + } + return false; + } + static void print(char[][] board) + { + for(int i=0; i<9 ;i++) + { + for(int j=0 ; j<9 ; j++) + { + System.out.print(board[i][j]+", "); + } + System.out.println(); + } + } + + static boolean canElementBePlaced(char[][] board , int r , int c , char k) + { + for(int i=0 ; i<9 ; i++) + { + if(board[r][i]==k) + { + return false; + } + } + + for(int j =0 ; j<9 ; j++) + { + if(board[j][c]==k) + { + return false; + } + } + + int sr = r-(r%3); + int sc = c-(c%3); + + for(int i=sr; i<=sr+2;i++) + { + for(int j=sc ; j<=sc+2; j++) + { + if (board[i][j]==k) + { + return false; + } + } + } + return true; + } + +} From dfb2c01060503d17171781508df979581aef8960 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Feb 2023 18:49:20 +0530 Subject: [PATCH 0124/1894] rename file --- ..._no_of_good_pairs.java => find_no_of_good_pairs_in_array.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{find_no_of_good_pairs.java => find_no_of_good_pairs_in_array.java} (100%) diff --git a/Arrays/find_no_of_good_pairs.java b/Arrays/find_no_of_good_pairs_in_array.java similarity index 100% rename from Arrays/find_no_of_good_pairs.java rename to Arrays/find_no_of_good_pairs_in_array.java From fa7a430f49a36b7ef613bf1752e39fd26782c802 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Feb 2023 18:50:19 +0530 Subject: [PATCH 0125/1894] rename file --- 2D Arrays/{search_el.cpp => search_element.cpp} | 0 Arrays/{majority_el.cpp => majority_element.cpp} | 0 Arrays/{majority_el.java => majority_element.java} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays/{search_el.cpp => search_element.cpp} (100%) rename Arrays/{majority_el.cpp => majority_element.cpp} (100%) rename Arrays/{majority_el.java => majority_element.java} (100%) diff --git a/2D Arrays/search_el.cpp b/2D Arrays/search_element.cpp similarity index 100% rename from 2D Arrays/search_el.cpp rename to 2D Arrays/search_element.cpp diff --git a/Arrays/majority_el.cpp b/Arrays/majority_element.cpp similarity index 100% rename from Arrays/majority_el.cpp rename to Arrays/majority_element.cpp diff --git a/Arrays/majority_el.java b/Arrays/majority_element.java similarity index 100% rename from Arrays/majority_el.java rename to Arrays/majority_element.java From 5ad21a55e84d74f98545584e76c1d65bb04671cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Feb 2023 18:52:03 +0530 Subject: [PATCH 0126/1894] rename file --- Leetcode/{ValidateIp.java => validate_ip.java} | 0 ...ithUniqueDigits.java => count_numbers_with_unique_digits.java} | 0 Math/{countPrimes.java => count_primes.java} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Leetcode/{ValidateIp.java => validate_ip.java} (100%) rename Math/{countNumbersWithUniqueDigits.java => count_numbers_with_unique_digits.java} (100%) rename Math/{countPrimes.java => count_primes.java} (100%) diff --git a/Leetcode/ValidateIp.java b/Leetcode/validate_ip.java similarity index 100% rename from Leetcode/ValidateIp.java rename to Leetcode/validate_ip.java diff --git a/Math/countNumbersWithUniqueDigits.java b/Math/count_numbers_with_unique_digits.java similarity index 100% rename from Math/countNumbersWithUniqueDigits.java rename to Math/count_numbers_with_unique_digits.java diff --git a/Math/countPrimes.java b/Math/count_primes.java similarity index 100% rename from Math/countPrimes.java rename to Math/count_primes.java From 7bdd340c026cab2131eeeae3a04815bf9c306d6d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Feb 2023 18:53:59 +0530 Subject: [PATCH 0127/1894] rename file --- sorting/{insertionsort.cpp => insertion_sort.cpp} | 0 sorting/{insertionsort.java => insertion_sort.java} | 0 sorting/{insertionsort.js => insertion_sort.js} | 0 sorting/{mergesort.cpp => merge_sort.cpp} | 0 sorting/{mergesort.go => merge_sort.go} | 0 sorting/{MergeSort.java => merge_sort.java} | 0 sorting/{mergesort.js => merge_sort.js} | 0 sorting/{selectionsort.cpp => selection_sort.cpp} | 0 sorting/{selectionsort.go => selection_sort.go} | 0 sorting/{selectionsort.java => selection_sort.java} | 0 sorting/{selectionsort.js => selection_sort.js} | 0 sorting/{selectionsort.py => selection_sort.py} | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename sorting/{insertionsort.cpp => insertion_sort.cpp} (100%) rename sorting/{insertionsort.java => insertion_sort.java} (100%) rename sorting/{insertionsort.js => insertion_sort.js} (100%) rename sorting/{mergesort.cpp => merge_sort.cpp} (100%) rename sorting/{mergesort.go => merge_sort.go} (100%) rename sorting/{MergeSort.java => merge_sort.java} (100%) rename sorting/{mergesort.js => merge_sort.js} (100%) rename sorting/{selectionsort.cpp => selection_sort.cpp} (100%) rename sorting/{selectionsort.go => selection_sort.go} (100%) rename sorting/{selectionsort.java => selection_sort.java} (100%) rename sorting/{selectionsort.js => selection_sort.js} (100%) rename sorting/{selectionsort.py => selection_sort.py} (100%) diff --git a/sorting/insertionsort.cpp b/sorting/insertion_sort.cpp similarity index 100% rename from sorting/insertionsort.cpp rename to sorting/insertion_sort.cpp diff --git a/sorting/insertionsort.java b/sorting/insertion_sort.java similarity index 100% rename from sorting/insertionsort.java rename to sorting/insertion_sort.java diff --git a/sorting/insertionsort.js b/sorting/insertion_sort.js similarity index 100% rename from sorting/insertionsort.js rename to sorting/insertion_sort.js diff --git a/sorting/mergesort.cpp b/sorting/merge_sort.cpp similarity index 100% rename from sorting/mergesort.cpp rename to sorting/merge_sort.cpp diff --git a/sorting/mergesort.go b/sorting/merge_sort.go similarity index 100% rename from sorting/mergesort.go rename to sorting/merge_sort.go diff --git a/sorting/MergeSort.java b/sorting/merge_sort.java similarity index 100% rename from sorting/MergeSort.java rename to sorting/merge_sort.java diff --git a/sorting/mergesort.js b/sorting/merge_sort.js similarity index 100% rename from sorting/mergesort.js rename to sorting/merge_sort.js diff --git a/sorting/selectionsort.cpp b/sorting/selection_sort.cpp similarity index 100% rename from sorting/selectionsort.cpp rename to sorting/selection_sort.cpp diff --git a/sorting/selectionsort.go b/sorting/selection_sort.go similarity index 100% rename from sorting/selectionsort.go rename to sorting/selection_sort.go diff --git a/sorting/selectionsort.java b/sorting/selection_sort.java similarity index 100% rename from sorting/selectionsort.java rename to sorting/selection_sort.java diff --git a/sorting/selectionsort.js b/sorting/selection_sort.js similarity index 100% rename from sorting/selectionsort.js rename to sorting/selection_sort.js diff --git a/sorting/selectionsort.py b/sorting/selection_sort.py similarity index 100% rename from sorting/selectionsort.py rename to sorting/selection_sort.py From 60a9460bc421b32a3f854efa19fb1f09be08726a Mon Sep 17 00:00:00 2001 From: Tarun Samanta Date: Tue, 14 Feb 2023 21:16:02 +0530 Subject: [PATCH 0128/1894] Added quick_sort --- sorting/quick_sort.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 sorting/quick_sort.cpp diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp new file mode 100644 index 00000000..9ee64530 --- /dev/null +++ b/sorting/quick_sort.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +int Hoare_partition(int arr[],int l,int h) +{ + // Here p is the Index of pivot element + // Here We consider first element as pivot, + // But if we Want to consider any element as pivot then just swap that index with the first element + int pivot=arr[l]; + int i=l-1,j=h+1; + + while(true) + { + do{ + i++; + }while(arr[i]pivot); + + if(i>=j) + return j; + swap(arr[i],arr[j]); + } +} + +void Quick_Sort(int arr[],int low,int high) +{ + + if(low Date: Tue, 14 Feb 2023 23:25:18 +0530 Subject: [PATCH 0129/1894] added timsort.cpp Created a file with implementation of timsort in c++. --- sorting/timsort.cpp | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 sorting/timsort.cpp diff --git a/sorting/timsort.cpp b/sorting/timsort.cpp new file mode 100644 index 00000000..b3d3cf99 --- /dev/null +++ b/sorting/timsort.cpp @@ -0,0 +1,89 @@ +//Implementation of Tim Sort +//Tim Sort makes use of insertionSort and Merge function of MergeSort +//The basic idea is to divide the input array into blocks called as runs +//The size of runs varies from 32 to 64, and perform insertion sort on the runs +//Then, The runs(blocks) are merged to form the final sorted array +// +//Time Complexity of this algorithm in Best case is O(n),Average case is O(n*log(n)) +//Time Complexity in Worst case is O(n*log(n)). +//This is a stable sorting algorithm +//This algorithm uses Space of O(n) +//This algorithm is used in languages like Java and Python for sorting. + +#include +using namespace std; +const int run=32; +void insertionSort(vector&array,int l,int r) +{ + for(int i=l+1;i<=r;i++) + { + int temp=array[i]; + int j=i-1; + while(j>=l and array[j]>temp) + { + array[j+1]=array[j]; + j--; + } + array[j+1]=temp; + } +} +void merge(vector&array,int l,int m,int r) +{ + int len1=m-l+1,len2=r-m; + vectorleft(len1),right(len2); + for(int i=0;i&array,int n) +{ + //calling insertion sort on blocks of size equal to run=32 + //if the size of array is less than defined run size, then the insertion sort would have sorted the array and there is no need of merging. + for(int i=0;iarray={9,8,7,6,5,4,3,2,1}; + int n=array.size(); + timSort(array,n);//call to TimSort function + return 0; +} From 30ea8bb411efbbb84dd23b29a832f9e71a21472c Mon Sep 17 00:00:00 2001 From: Harsh <115858346+harshprajapati460@users.noreply.github.com> Date: Wed, 15 Feb 2023 00:40:23 +0530 Subject: [PATCH 0130/1894] Add files via upload --- sorting/merge_two_sorted_array.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 sorting/merge_two_sorted_array.cpp diff --git a/sorting/merge_two_sorted_array.cpp b/sorting/merge_two_sorted_array.cpp new file mode 100644 index 00000000..447111bc --- /dev/null +++ b/sorting/merge_two_sorted_array.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int tar = m+n-1; // size of nums1 + + int i=m-1; // index of last element of nums1 + + int j = n-1; // index of last element of nums2 + + while(j>=0){ // iterate from last + + if(i>=0 && nums1[i] > nums2[j]) nums1[tar--] = nums1[i--]; + + else nums1[tar--] = nums2[j--]; + + } + // Time complexity of this code is O(m+n) + + // Space complexity is S(1) + } +}; \ No newline at end of file From 80875e6a4a933a2db0850450c8322639c3e3a947 Mon Sep 17 00:00:00 2001 From: Nyakinyua Date: Tue, 14 Feb 2023 22:12:04 +0300 Subject: [PATCH 0131/1894] Add solution for group anagram in python --- Strings/group_anagram.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Strings/group_anagram.py diff --git a/Strings/group_anagram.py b/Strings/group_anagram.py new file mode 100644 index 00000000..d451653f --- /dev/null +++ b/Strings/group_anagram.py @@ -0,0 +1,28 @@ +# Given an array of strings strs, group the anagrams together. You can return the answer in any order. + +# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +# Example 1: +# Input: strs = ["eat","tea","tan","ate","nat","bat"] +# Output: [["bat"],["nat","tan"],["ate","eat","tea"]] + +# Example 2: +# Input: strs = [""] +# Output: [[""]] + +# Example 3: +# Input: strs = ["a"] +# Output: [["a"]] + + + +class Solution: + def groupAnagrams(self,strs): + result = {} + for i in strs: + x = "".join(sorted(i)) + if x in result: + result[x].append(i) + else: + result[x] = [i] + return list(result.values()) \ No newline at end of file From f05a784235fc9a1ac89d4389b8a4db2efb32c577 Mon Sep 17 00:00:00 2001 From: Nyakinyua Date: Wed, 15 Feb 2023 12:40:07 +0300 Subject: [PATCH 0132/1894] group anagram solution JS --- Strings/group_anagrams.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Strings/group_anagrams.js diff --git a/Strings/group_anagrams.js b/Strings/group_anagrams.js new file mode 100644 index 00000000..20f99963 --- /dev/null +++ b/Strings/group_anagrams.js @@ -0,0 +1,34 @@ +/* Given an array of strings strs, group the anagrams together. You can return the answer in any order. + + An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + + Example 1: + Input: strs = ["eat","tea","tan","ate","nat","bat"] + Output: [["bat"],["nat","tan"],["ate","eat","tea"]] + + Example 2: + Input: strs = [""] + Output: [[""]] + + Example 3: + Input: strs = ["a"] + Output: [["a"]] + + + * @param {string[]} strs + * @return {string[][]} +*/ +function groupAnagrams(strs) { + let result = {} + + for (let i of strs){ + let anagram = i.split("").sort().join(""); + if (result[anagram]) { + result[anagram].push(i); + } else { + result[anagram] = [i]; + } + } + return Object.values(result); + +}; \ No newline at end of file From 493b90a29dcb8ea6e000ace54a63ade4b791a145 Mon Sep 17 00:00:00 2001 From: Harsh <115858346+harshprajapati460@users.noreply.github.com> Date: Wed, 15 Feb 2023 15:54:40 +0530 Subject: [PATCH 0133/1894] Update merge_two_sorted_array.cpp --- sorting/merge_two_sorted_array.cpp | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/sorting/merge_two_sorted_array.cpp b/sorting/merge_two_sorted_array.cpp index 447111bc..efe18802 100644 --- a/sorting/merge_two_sorted_array.cpp +++ b/sorting/merge_two_sorted_array.cpp @@ -1,3 +1,30 @@ +// Description: +// You are given two integer arrays nums1 and nums2, +// sorted in non-decreasing order, and two integers +// m and n, representing the number of elements in +// nums1 and nums2 respectively. + +// Merge nums1 and nums2 into a single array sorted +// in non-decreasing order. + +// The final sorted array should not be returned by +// the function, but instead be stored inside the +// array nums1. To accommodate this, nums1 has a +// length of m + n, where the first m elements denote +// the elements that should be merged, and the last +// n elements are set to 0 and should be ignored. +// nums2 has a length of n. + +// Sample Input/Output: + +// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 + +// Output: [1,2,2,3,5,6] + +// Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. + +// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1 +// - - - class Solution { public: void merge(vector& nums1, int m, vector& nums2, int n) { @@ -18,4 +45,4 @@ class Solution { // Space complexity is S(1) } -}; \ No newline at end of file +}; From 90192fd1d6dc7f15feb5568a323b34f8ccfd4a72 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:06:13 +0530 Subject: [PATCH 0134/1894] add is_pallindrome in go --- Strings/is_pallindrome.go | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Strings/is_pallindrome.go diff --git a/Strings/is_pallindrome.go b/Strings/is_pallindrome.go new file mode 100644 index 00000000..0ceaacf5 --- /dev/null +++ b/Strings/is_pallindrome.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "strings" +) + +func isPalindrome(inputString string) { + fmt.Printf("String to check: \"%s\". Length of string: %d\n", inputString, len(inputString)) + left := 0 + right := len(inputString) - 1 + i := 1 + + // The terminating condition for the loop is when both the pointers reach the same element or when they cross each other + for left < right { + fmt.Printf("In iteration %d, left = %d, right = %d\n", i, left, right) + fmt.Printf("The current element being pointed to by the left pointer is %c\n", inputString[left]) + fmt.Printf("The current element being pointed to by the right pointer is %c\n", inputString[right]) + fmt.Printf("%s\n", strings.Repeat("-", 100)) + // Heading towards the right + left += 1 + + // Heading towards left + right -= 1 + i += 1 + } + fmt.Printf("Loop terminated with left = %d, right = %d\n", left, right) + fmt.Printf("The pointers have either reached the same index, or have crossed each other, hence we don't need to look further.\n") + fmt.Printf("%s\n", strings.Repeat("-", 100)) +} + +// Driver code +func main() { + inputList := []string {"RACECAR", "ABBA", "TART"} + + for i, value := range inputList { + fmt.Printf("Test Case # %d\n", i + 1) + isPalindrome(value) + + } +} \ No newline at end of file From 2b3400d9bb6f4ec191862f76edfe4c1cacb22ca0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:06:46 +0530 Subject: [PATCH 0135/1894] add description and comment --- Strings/is_pallindrome.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Strings/is_pallindrome.go b/Strings/is_pallindrome.go index 0ceaacf5..6a01c5a8 100644 --- a/Strings/is_pallindrome.go +++ b/Strings/is_pallindrome.go @@ -1,3 +1,4 @@ +// Valid Palindrome package main import ( @@ -5,6 +6,8 @@ import ( "strings" ) +// The two pointers approach would allow us to solve this problem in linear time and without any extra space complexity or built-in functions because we’ll be simply traverse the array from the start and the end at the same time to reach the middle of the string. + func isPalindrome(inputString string) { fmt.Printf("String to check: \"%s\". Length of string: %d\n", inputString, len(inputString)) left := 0 From 41fdc7464dd2687e982b084bc265793a65372284 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:09:25 +0530 Subject: [PATCH 0136/1894] modify program --- Strings/is_pallindrome.go | 51 +++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/Strings/is_pallindrome.go b/Strings/is_pallindrome.go index 6a01c5a8..be995d1a 100644 --- a/Strings/is_pallindrome.go +++ b/Strings/is_pallindrome.go @@ -8,37 +8,46 @@ import ( // The two pointers approach would allow us to solve this problem in linear time and without any extra space complexity or built-in functions because we’ll be simply traverse the array from the start and the end at the same time to reach the middle of the string. -func isPalindrome(inputString string) { - fmt.Printf("String to check: \"%s\". Length of string: %d\n", inputString, len(inputString)) +func isPalindrome(inputString string) bool { left := 0 right := len(inputString) - 1 - i := 1 - - // The terminating condition for the loop is when both the pointers reach the same element or when they cross each other + fmt.Printf("\tThe current element being pointed by the left index is %c\n", inputString[left]) + fmt.Printf("\tThe current element being pointed by the right index is %c\n", inputString[right]) for left < right { - fmt.Printf("In iteration %d, left = %d, right = %d\n", i, left, right) - fmt.Printf("The current element being pointed to by the left pointer is %c\n", inputString[left]) - fmt.Printf("The current element being pointed to by the right pointer is %c\n", inputString[right]) - fmt.Printf("%s\n", strings.Repeat("-", 100)) + fmt.Printf("\tWe check if the two elements are indeed the same, in this case...\n") + + // If the elements at index left and index right are not equal + if inputString[left] != inputString[right] { + fmt.Printf("\tThe elements are not the same, hence we return false\n") + + // then the symmetry is broken, the string is not a palindrome + return false + } + + fmt.Printf("\tThey are the same, thus we move the two pointers toward the middle to continue the\n\tverfification process\n\n") + // Heading towards the right - left += 1 + left++ + + // Heading towards the middle + right-- - // Heading towards left - right -= 1 - i += 1 + fmt.Printf("\tThe new element at the left pointer is %c\n", inputString[left]) + fmt.Printf("\tThe new element at the right pointer is %c\n", inputString[right]) } - fmt.Printf("Loop terminated with left = %d, right = %d\n", left, right) - fmt.Printf("The pointers have either reached the same index, or have crossed each other, hence we don't need to look further.\n") - fmt.Printf("%s\n", strings.Repeat("-", 100)) + + // We reached the middle of the string without finding a mismatch, so it is a palindrome + return true } // Driver code func main() { - inputList := []string {"RACECAR", "ABBA", "TART"} - - for i, value := range inputList { + str := []string {"RACEACAR", "A", "ABCDEFGFEDCBA", "ABC", "ABCBA", "ABBA", "RACEACAR"} + for i, s := range str { fmt.Printf("Test Case # %d\n", i + 1) - isPalindrome(value) - + fmt.Printf("%s\n", strings.Repeat("-", 100)) + fmt.Printf("\tThe input string is '%s' and the length of the string is %d.\n", s, len(s)) + fmt.Printf("\nIs it a palindrome?.....%v\n", isPalindrome(s)) + fmt.Printf("%s\n", strings.Repeat("-", 100)) } } \ No newline at end of file From f32e578f64a159506bd376bc00492d79e87cd927 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:12:34 +0530 Subject: [PATCH 0137/1894] add time and space complexity with sample io --- Strings/is_pallindrome.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Strings/is_pallindrome.go b/Strings/is_pallindrome.go index be995d1a..44379ab4 100644 --- a/Strings/is_pallindrome.go +++ b/Strings/is_pallindrome.go @@ -7,6 +7,11 @@ import ( ) // The two pointers approach would allow us to solve this problem in linear time and without any extra space complexity or built-in functions because we’ll be simply traverse the array from the start and the end at the same time to reach the middle of the string. +// Time complexity +// The time complexity is O(n) where n is the number of characters present in the string. +// Space complexity O(1) because we use constant space to store two indices. +// Sample Input : RACEACAR +// Output: False func isPalindrome(inputString string) bool { left := 0 From d2367e0b718c4541cb142513e5d5ff0896c5760e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:17:15 +0530 Subject: [PATCH 0138/1894] reformat code --- sorting/merge_two_sorted_array.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/sorting/merge_two_sorted_array.cpp b/sorting/merge_two_sorted_array.cpp index efe18802..bca55e94 100644 --- a/sorting/merge_two_sorted_array.cpp +++ b/sorting/merge_two_sorted_array.cpp @@ -24,25 +24,26 @@ // Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. // The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1 -// - - - + +// Time complexity of this code is O(m+n) +// Space complexity is O(1) + class Solution { public: void merge(vector& nums1, int m, vector& nums2, int n) { - int tar = m+n-1; // size of nums1 - - int i=m-1; // index of last element of nums1 + int tar = m + n - 1; // size of nums1 - int j = n-1; // index of last element of nums2 + int i = m - 1; // index of last element of nums1 - while(j>=0){ // iterate from last + int j = n - 1; // index of last element of nums2 - if(i>=0 && nums1[i] > nums2[j]) nums1[tar--] = nums1[i--]; + while(j >= 0) { // iterate from last - else nums1[tar--] = nums2[j--]; + if( i >= 0 && nums1[i] > nums2[j]) + nums1[tar--] = nums1[i--]; + else + nums1[tar--] = nums2[j--]; } - // Time complexity of this code is O(m+n) - - // Space complexity is S(1) } }; From c89d2fe755b160b275604c1e2308a8c47ddb933d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:22:30 +0530 Subject: [PATCH 0139/1894] add readability --- sorting/tim_sort.cpp | 85 ++++++++++++++++++++++++++++++++++++++++++ sorting/timsort.cpp | 89 -------------------------------------------- 2 files changed, 85 insertions(+), 89 deletions(-) create mode 100644 sorting/tim_sort.cpp delete mode 100644 sorting/timsort.cpp diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp new file mode 100644 index 00000000..a9796d84 --- /dev/null +++ b/sorting/tim_sort.cpp @@ -0,0 +1,85 @@ +//Implementation of Tim Sort +//Tim Sort makes use of insertionSort and Merge function of MergeSort +//The basic idea is to divide the input array into blocks called as runs +//The size of runs varies from 32 to 64, and perform insertion sort on the runs +//Then, The runs(blocks) are merged to form the final sorted array +// +//Time Complexity of this algorithm in Best case is O(n),Average case is O(n*log(n)) +//Time Complexity in Worst case is O(n*log(n)). +//This is a stable sorting algorithm +//This algorithm uses Space of O(n) +//This algorithm is used in languages like Java and Python for sorting. + +#include +using namespace std; +const int run=32; +void insertionSort(vector&array,int l,int r) +{ + for(int i = l + 1; i <= r; i++){ + int temp = array[i]; + int j = i - 1; + while(j >= l and array[j] > temp) { + array[j + 1] = array[j]; + j--; + } + array[j + 1] = temp; + } +} +void merge(vector&array,int l,int m,int r) { + int len1 = m - l + 1, len2 = r - m; + vectorleft(len1), right(len2); + + for(int i = 0; i < len1; i++){ + left[i] = array[l + i]; + } + for(int i = 0; i < len2; i++){ + right[i] = array[m + 1 + i]; + } + + int i = 0, j = 0, k = l; + + while(i < len1 and j < len2) { + if(left[i] <= right[j]) + array[k] = left[i++]; + else array[k] = right[j++]; + k++; + } + + while(i&array, int n) { + // calling insertion sort on blocks of size equal to run=32 + // if the size of array is less than defined run size, then the insertion sort would have sorted the array and there is no need of merging. + for(int i = 0; i < n; i += run) { + insertionSort(array, i, min((i + run - 1), n - 1)); + } + //we merge from size run,the array merges to form sizes 64,128,... + for(int size = run; size < n; size = 2 * size) { + //we merge from array[left,left+size-1] + //and array[left+size,left+2*size] + //after every merge,we increase left by 2*size + for(int left = 0; left < n; left += 2 * size) { + int mid = left + size - 1;//ending point of left subarray + int right = min((left + 2 * size - 1), n - 1);//ending point of right subarray + if(mid < right) + merge(array, left, mid, right); //calling the merge function + } + } + for(int i: array)//printing the sorted array + cout << i <<" "; + //sample output 1,2,3,4,5,6,7,8,9 +} +int main() +{ + vector array = {9,8,7,6,5,4,3,2,1}; + int n = array.size(); + timSort(array, n);//call to TimSort function + return 0; +} diff --git a/sorting/timsort.cpp b/sorting/timsort.cpp deleted file mode 100644 index b3d3cf99..00000000 --- a/sorting/timsort.cpp +++ /dev/null @@ -1,89 +0,0 @@ -//Implementation of Tim Sort -//Tim Sort makes use of insertionSort and Merge function of MergeSort -//The basic idea is to divide the input array into blocks called as runs -//The size of runs varies from 32 to 64, and perform insertion sort on the runs -//Then, The runs(blocks) are merged to form the final sorted array -// -//Time Complexity of this algorithm in Best case is O(n),Average case is O(n*log(n)) -//Time Complexity in Worst case is O(n*log(n)). -//This is a stable sorting algorithm -//This algorithm uses Space of O(n) -//This algorithm is used in languages like Java and Python for sorting. - -#include -using namespace std; -const int run=32; -void insertionSort(vector&array,int l,int r) -{ - for(int i=l+1;i<=r;i++) - { - int temp=array[i]; - int j=i-1; - while(j>=l and array[j]>temp) - { - array[j+1]=array[j]; - j--; - } - array[j+1]=temp; - } -} -void merge(vector&array,int l,int m,int r) -{ - int len1=m-l+1,len2=r-m; - vectorleft(len1),right(len2); - for(int i=0;i&array,int n) -{ - //calling insertion sort on blocks of size equal to run=32 - //if the size of array is less than defined run size, then the insertion sort would have sorted the array and there is no need of merging. - for(int i=0;iarray={9,8,7,6,5,4,3,2,1}; - int n=array.size(); - timSort(array,n);//call to TimSort function - return 0; -} From 2f2ed0749d9071cd93a1dba1bcba477c1e4a99c4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 22:23:49 +0530 Subject: [PATCH 0140/1894] rename files --- sorting/{bubblesort.cpp => bubble_sort.cpp} | 0 sorting/{bubblesort.go => bubble_sort.go} | 0 sorting/{bubblesort.js => bubble_sort.js} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename sorting/{bubblesort.cpp => bubble_sort.cpp} (100%) rename sorting/{bubblesort.go => bubble_sort.go} (100%) rename sorting/{bubblesort.js => bubble_sort.js} (100%) diff --git a/sorting/bubblesort.cpp b/sorting/bubble_sort.cpp similarity index 100% rename from sorting/bubblesort.cpp rename to sorting/bubble_sort.cpp diff --git a/sorting/bubblesort.go b/sorting/bubble_sort.go similarity index 100% rename from sorting/bubblesort.go rename to sorting/bubble_sort.go diff --git a/sorting/bubblesort.js b/sorting/bubble_sort.js similarity index 100% rename from sorting/bubblesort.js rename to sorting/bubble_sort.js From 9ef3f4d370522c7e2288d6e64ba05589d6383d18 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 23:10:47 +0530 Subject: [PATCH 0141/1894] rename file --- sorting/{bubblesort.py => bubble_sort.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sorting/{bubblesort.py => bubble_sort.py} (100%) diff --git a/sorting/bubblesort.py b/sorting/bubble_sort.py similarity index 100% rename from sorting/bubblesort.py rename to sorting/bubble_sort.py From f2c43233100463eb2f8c15884166602d276d9873 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 23:10:54 +0530 Subject: [PATCH 0142/1894] add sum of three values --- Arrays/sum_of_three_values.go | 78 +++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Arrays/sum_of_three_values.go diff --git a/Arrays/sum_of_three_values.go b/Arrays/sum_of_three_values.go new file mode 100644 index 00000000..1750cf91 --- /dev/null +++ b/Arrays/sum_of_three_values.go @@ -0,0 +1,78 @@ +/* +Given an array of integers, nums, and an integer value, target, +determine if there are any three integers in nums whose sum equals the target. +Return TRUE if three such integers are found in the array. Otherwise, return FALSE. +*/ +package main + +import ( + "fmt" + "sort" + "strings" +) + +// FindSumOfThree is our challenge function +func findSumOfThree(nums []int, target int) bool { + // Sorting the input vector + sort.Sort(sort.IntSlice(nums)) + + // We create two pointers to track our indices and, variable to store our triple sum + low, high, triple := 0, 0, 0 + + // Fix one element at a time and find the other two + for i := 0; i < len(nums) - 2; i++ { + // Set the indices of the two pointers + // Index of the first of the remaining elements + low = i + 1 + + // Last index + high = len(nums) - 1 + + for low < high { + // Check if the sum of the triple is equal to the sum + triple = nums[i] + nums[low] + nums[high] + + // Found a triple whose sum equals the target + if triple == target { + return true + + // Move low pointer forward if the triple sum is less than the required sum + } else if triple < target { + low += 1 + } else { + // Move the high pointer backwards if the triple sum is greater than the required sum + high -= 1 + } + } + } + return false +} + +// Driver code +func main() { + numsLists := [][]int { + {3, 7, 1, 2, 8, 4, 5}, + {-1, 2, 1, -4, 5, -3}, + {2, 3, 4, 1, 7, 9}, + {1, -1, 0}, + {2, 4, 2, 7, 6, 3, 1}, + } + testLists := [][]int { + {10, 20, 21}, + {-8, 0, 7}, + {8, 10, 20}, + {1, -1, 0}, + {8, 11, 15}, + } + for i, nList := range numsLists { + fmt.Printf("%d. Input array: %s\n", i + 1, strings.Replace(fmt.Sprint(nList), " ", ", ", -1)) + for _, tList := range testLists[i] { + if findSumOfThree(nList, tList) { + fmt.Printf(" Sum for %d exists\n", tList) + } else { + fmt.Printf(" Sum for %d does not exist\n", tList) + } + } + fmt.Printf("%s\n", strings.Repeat("-", 100)) + } +} \ No newline at end of file From f072d800e8eeb475afa129f3d19ae7967b3604c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Feb 2023 23:14:48 +0530 Subject: [PATCH 0143/1894] add time and space complexity --- Arrays/sum_of_three_values.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Arrays/sum_of_three_values.go b/Arrays/sum_of_three_values.go index 1750cf91..cf72184d 100644 --- a/Arrays/sum_of_three_values.go +++ b/Arrays/sum_of_three_values.go @@ -3,6 +3,7 @@ Given an array of integers, nums, and an integer value, target, determine if there are any three integers in nums whose sum equals the target. Return TRUE if three such integers are found in the array. Otherwise, return FALSE. */ + package main import ( @@ -11,6 +12,8 @@ import ( "strings" ) +// Time complexity : Sorting the array O(n log(n)) and Nested loop to find triplet O(n^{2}) which can be simplified to O(n^{2}) +// Space complexity is O(1) since we use a fixed amount of extra space in memory. // FindSumOfThree is our challenge function func findSumOfThree(nums []int, target int) bool { // Sorting the input vector From 26830c5a85389846ce77762d186f50bba5e04291 Mon Sep 17 00:00:00 2001 From: stefanoska <75374281+stefanoska@users.noreply.github.com> Date: Wed, 15 Feb 2023 22:36:42 +0200 Subject: [PATCH 0144/1894] Bubblesort.java --- sorting/Bubblesort.java | 60 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 sorting/Bubblesort.java diff --git a/sorting/Bubblesort.java b/sorting/Bubblesort.java new file mode 100644 index 00000000..9985c4ab --- /dev/null +++ b/sorting/Bubblesort.java @@ -0,0 +1,60 @@ +// Implementation of Bubble sort. +// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm +// that repeatedly steps through the input list element by element, +// comparing the current element with the one after it, swapping their values if needed. +// These passes through the list are repeated until no swaps had to be performed during a pass, +// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort + +// Time Complexity worst-case and average complexity O(n^{2}) +// Bubble sort is O(n) on a list that is already sorted i.e. Best case + +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] + + + +package sorting; + +public class Bubblesort { + void bubblesort(int[] array){ + int size=array.length; + int temp=0; + boolean flag=false; + + for(int i=0; iarray[j]){ + //swap elements + temp=array[j-1]; + array[j-1]=array[j]; + array[j]=temp; + flag=true; + } + + } + if(!flag){ + System.out.println("Already sorted so no further redundant passes best case 0(n)"); + break; + } + } + } + + public static void main(String[] args) { + int[] array ={5,1,2,3,4,5}; + + System.out.println("Array Before Bubble Sort"); + for (int j : array) { + System.out.print(j + " "); + } + System.out.println(); + Bubblesort is=new Bubblesort(); + is.bubblesort(array);//sorting array elements using bubble sort + + System.out.println("Array After Bubble Sort"); + for (int j : array) { + System.out.print(j + " "); + } + + } + +} From cd5de8e05e3e5b7f01039c340cee0c507acf92cb Mon Sep 17 00:00:00 2001 From: stefanoska <75374281+stefanoska@users.noreply.github.com> Date: Wed, 15 Feb 2023 22:51:21 +0200 Subject: [PATCH 0145/1894] merge_sorted_array.java --- Arrays/merge_sorted_array.java | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Arrays/merge_sorted_array.java diff --git a/Arrays/merge_sorted_array.java b/Arrays/merge_sorted_array.java new file mode 100644 index 00000000..77fb0cf6 --- /dev/null +++ b/Arrays/merge_sorted_array.java @@ -0,0 +1,38 @@ +//You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers +// m and n, representing the number of elements in nums1 and nums2 respectively. + +//Merge nums1 and nums2 into a single array sorted in non-decreasing order. + +//The final sorted array should not be returned by the function, but instead be stored inside the array nums1. +// To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that +// should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. + + +import java.util.Arrays; + +class merge_sorted_array{ + + public void merge(int[] nums1, int m, int[] nums2, int n){ + int[] merged=new int[m+n]; //new merged array + //copying the first m elements from nums1 to the merged array + if (m >= 0) System.arraycopy(nums1, 0, merged, 0, m); + //copying the first n elements from nums2 to the merged array + if (n >= 0) System.arraycopy(nums2, 0, merged, m + 0, n); + //sorting the merged array + Arrays.sort(merged); + //copying the merged array to the nums1 array + System.arraycopy(merged, 0, nums1, 0, nums1.length); + } + + public static void main(String[] args){ + int[] nums1 ={1,2,3,0,0,0}; + int m=3,n=3; + int[] nums2 ={2,5,6}; + + merge_sorted_array is=new merge_sorted_array(); + is.merge(nums1,m,nums2,n); + for (int j : nums1) { + System.out.print(j + " "); + } + } +} From b3cf82af684263979e7e3abcf6f55d01adb2e60d Mon Sep 17 00:00:00 2001 From: stefanoska <75374281+stefanoska@users.noreply.github.com> Date: Wed, 15 Feb 2023 22:53:08 +0200 Subject: [PATCH 0146/1894] merge_sorted_array.java --- Arrays/merge_sorted_array.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/merge_sorted_array.java b/Arrays/merge_sorted_array.java index 77fb0cf6..db20501f 100644 --- a/Arrays/merge_sorted_array.java +++ b/Arrays/merge_sorted_array.java @@ -31,7 +31,7 @@ public static void main(String[] args){ merge_sorted_array is=new merge_sorted_array(); is.merge(nums1,m,nums2,n); - for (int j : nums1) { + for (int j:nums1) { System.out.print(j + " "); } } From 0a024ded36a576b407284a550f618726e789ee10 Mon Sep 17 00:00:00 2001 From: LeoC Date: Wed, 15 Feb 2023 19:30:05 -0500 Subject: [PATCH 0147/1894] add javascript solution for sum of three values in array --- Arrays/sum_of_three_values.js | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Arrays/sum_of_three_values.js diff --git a/Arrays/sum_of_three_values.js b/Arrays/sum_of_three_values.js new file mode 100644 index 00000000..282f016b --- /dev/null +++ b/Arrays/sum_of_three_values.js @@ -0,0 +1,73 @@ +/* +Given an array of integers, nums, and an integer value, target, +determine if there are any three integers in nums whose sum equals the target. +Return TRUE if three such integers are found in the array. Otherwise, return FALSE. + +Sample Input : 3, 7, 1, 2, 8, 4, 5 Target : 18 +Output : True +Sample Input : 0 -1 1 Target : 2 +Output : False + +APPROACH: + +1) We need to sort the array for our strategy to work. +2) Iterating from index 0, we check three numbers: + - value at index i (starting at 0) + - low: value at index i + 1 + - high: value at index nums.length - 1 (the last value, also the highest) +3) Take the sum of these three values. + - If sum equals target, return true + - If sum is less than the target, increment "low" and run this step again + - If sum is higher than the target, decrement "high" and run this step again +4) If low meets high, we ran out of numbers to try. Back to step 2. +5) Return false at the end of everything because we found no matching sums + +For a similar problem: +https://leetcode.com/problems/3sum/ + +*/ + + +const sumOfThree = (nums, target) => { + // function only applies to arrays with at least 3 values + if (nums.length < 3) return false + + // Sort the array + nums.sort() + + let low, high + + // Iterate through each value (up to 3rd from last) + for (let i = 0; i < nums.length - 2; i++) { + + //Assign pointers and check the sum + low = i + 1 + high = nums.length - 1 + + while (low < high) { + + let sum = nums[i] + nums[low] + nums[high] + + // match found, return true + if (sum === target) { + return true + + // sum is too low, increase low pointer + } else if (sum < target) { + low++ + + // sum is too high, decrease high pointer + } else { + high-- + } + } + } + + return false +} + +console.log(sumOfThree([3, 7, 1, 2, 8, 4, 5], 18)) // true +console.log(sumOfThree([3, 7, 1, 2, 8, 4, 5], 50)) // false +console.log(sumOfThree([0, -1, 1], 2)) // false +console.log(sumOfThree([0, -1, 1], 0)) // true + From dab09e5158b7cb70539c840014a9d5c2d477c0a9 Mon Sep 17 00:00:00 2001 From: Prince-1110 <123498733+Prince-1110@users.noreply.github.com> Date: Thu, 16 Feb 2023 12:31:18 +0530 Subject: [PATCH 0148/1894] Group_Anagram solution in java --- Strings/groupAnagram.java | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Strings/groupAnagram.java diff --git a/Strings/groupAnagram.java b/Strings/groupAnagram.java new file mode 100644 index 00000000..c2802934 --- /dev/null +++ b/Strings/groupAnagram.java @@ -0,0 +1,54 @@ +/*Given an array of strings strs, group the anagrams together. You can return the answer in any order. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + + + +Example 1: + +Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +Example 2: + +Input: strs = [""] +Output: [[""]] +Example 3: + +Input: strs = ["a"] +Output: [["a"]] +*/ + +package Strings; + +import java.util.*; + +public class groupAnagram { + + public List> groupAnagrams(String[] strs) { + + HashMap> map = new HashMap<>(); + + for(int i=0 ; i()); + } + map.get(string).add(strs[i]); + } + + List> result = new ArrayList<>(); + + for(String st:map.keySet()) + { + List list = map.get(st); + result.add(list); + } + return result; + + } +} From d038b2c16370fd73dbe6864ee83779c2b5a0c5a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Feb 2023 22:48:44 +0530 Subject: [PATCH 0149/1894] rename file and reformat code --- sorting/{Bubblesort.java => bubble_sort.java} | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) rename sorting/{Bubblesort.java => bubble_sort.java} (72%) diff --git a/sorting/Bubblesort.java b/sorting/bubble_sort.java similarity index 72% rename from sorting/Bubblesort.java rename to sorting/bubble_sort.java index 9985c4ab..64892db3 100644 --- a/sorting/Bubblesort.java +++ b/sorting/bubble_sort.java @@ -16,23 +16,23 @@ package sorting; public class Bubblesort { - void bubblesort(int[] array){ - int size=array.length; - int temp=0; - boolean flag=false; - - for(int i=0; iarray[j]){ + void bubblesort(int[] array) { + int size = array.length; + int temp = 0; + boolean flag = false; + + for(int i = 0; i < size; i++) { + for(int j = 1; j < (size - i); j++) { + if(array[j - 1] > array[j]) { //swap elements - temp=array[j-1]; - array[j-1]=array[j]; - array[j]=temp; - flag=true; + temp = array[j-1]; + array[j - 1] = array[j]; + array[j] = temp; + flag = true; } } - if(!flag){ + if(!flag) { System.out.println("Already sorted so no further redundant passes best case 0(n)"); break; } @@ -40,21 +40,20 @@ void bubblesort(int[] array){ } public static void main(String[] args) { - int[] array ={5,1,2,3,4,5}; + int[] array = {5, 1, 2, 3, 4, 5}; System.out.println("Array Before Bubble Sort"); for (int j : array) { System.out.print(j + " "); } System.out.println(); - Bubblesort is=new Bubblesort(); + Bubblesort is = new Bubblesort(); is.bubblesort(array);//sorting array elements using bubble sort System.out.println("Array After Bubble Sort"); for (int j : array) { System.out.print(j + " "); } - } } From 6bf5fdbb0e4c59619b226afb6071381b354a3bf5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Feb 2023 22:50:06 +0530 Subject: [PATCH 0150/1894] renaem file and reformat code --- ...{groupAnagram.java => group_anagrams.java} | 104 +++++++++--------- 1 file changed, 50 insertions(+), 54 deletions(-) rename Strings/{groupAnagram.java => group_anagrams.java} (80%) diff --git a/Strings/groupAnagram.java b/Strings/group_anagrams.java similarity index 80% rename from Strings/groupAnagram.java rename to Strings/group_anagrams.java index c2802934..f3e240b9 100644 --- a/Strings/groupAnagram.java +++ b/Strings/group_anagrams.java @@ -1,54 +1,50 @@ -/*Given an array of strings strs, group the anagrams together. You can return the answer in any order. - -An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. - - - -Example 1: - -Input: strs = ["eat","tea","tan","ate","nat","bat"] -Output: [["bat"],["nat","tan"],["ate","eat","tea"]] -Example 2: - -Input: strs = [""] -Output: [[""]] -Example 3: - -Input: strs = ["a"] -Output: [["a"]] -*/ - -package Strings; - -import java.util.*; - -public class groupAnagram { - - public List> groupAnagrams(String[] strs) { - - HashMap> map = new HashMap<>(); - - for(int i=0 ; i()); - } - map.get(string).add(strs[i]); - } - - List> result = new ArrayList<>(); - - for(String st:map.keySet()) - { - List list = map.get(st); - result.add(list); - } - return result; - - } -} +/*Given an array of strings strs, group the anagrams together. You can return the answer in any order. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + + + +Example 1: + +Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +Example 2: + +Input: strs = [""] +Output: [[""]] +Example 3: + +Input: strs = ["a"] +Output: [["a"]] +*/ + +package Strings; + +import java.util.*; + +public class groupAnagram { + + public List> groupAnagrams(String[] strs) { + + HashMap> map = new HashMap<>(); + + for(int i = 0 ; i < strs.length ; i++) { + char[] charArr = strs[i].toCharArray(); + Arrays.sort(charArr); + String string = new String(charArr); + + if(!map.containsKey(string)){ + map.put(string, new ArrayList<>()); + } + map.get(string).add(strs[i]); + } + + List> result = new ArrayList<>(); + + for(String st : map.keySet()) { + List list = map.get(st); + result.add(list); + } + return result; + } +} From 5ecc16248efeb4ff794dc9108d1f103bb2c4e679 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Feb 2023 22:51:06 +0530 Subject: [PATCH 0151/1894] reformat code --- Arrays/merge_sorted_array.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Arrays/merge_sorted_array.java b/Arrays/merge_sorted_array.java index db20501f..02e75427 100644 --- a/Arrays/merge_sorted_array.java +++ b/Arrays/merge_sorted_array.java @@ -25,13 +25,13 @@ public void merge(int[] nums1, int m, int[] nums2, int n){ } public static void main(String[] args){ - int[] nums1 ={1,2,3,0,0,0}; - int m=3,n=3; - int[] nums2 ={2,5,6}; + int[] nums1 = {1, 2, 3, 0, 0, 0}; + int m = 3, n = 3; + int[] nums2 ={2, 5, 6}; - merge_sorted_array is=new merge_sorted_array(); - is.merge(nums1,m,nums2,n); - for (int j:nums1) { + merge_sorted_array is = new merge_sorted_array(); + is.merge(nums1, m, nums2, n); + for (int j : nums1) { System.out.print(j + " "); } } From d807d5222a53455e9fced260d281721e44af8031 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Feb 2023 23:23:19 +0530 Subject: [PATCH 0152/1894] add reverse word in a string --- Strings/reverse_word_in_a_string.go | 98 +++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Strings/reverse_word_in_a_string.go diff --git a/Strings/reverse_word_in_a_string.go b/Strings/reverse_word_in_a_string.go new file mode 100644 index 00000000..7fcd8891 --- /dev/null +++ b/Strings/reverse_word_in_a_string.go @@ -0,0 +1,98 @@ +package main + +import ( + "fmt" + "strings" +) + +// reverseWords is our challenge function +func reverseWords(sentence string) string { + // We need to convert the input strings to lists of characters as strings are immutable in Go + sentenceBytes := []byte(sentence) + + // To reverse all words in the string, we will first reverse the entire string. + strLen := len(sentenceBytes) + sentenceBytes = strRev(sentenceBytes, 0, strLen-1) + strLen = len(sentenceBytes) + // Now all the words are in the desired location, but + // in reverse order: "Hello World" -> "dlroW olleH". + + // Now, let's iterate the sentence and reverse each word in place. + // "dlroW olleH" -> "World Hello" + start, end := 0, 0 + + for { + // find the start index of each word by detecting spaces. + for start < len(sentenceBytes) && sentenceBytes[start] == ' ' { + start += 1 + } + if start == strLen { + break + } + + // Find the end index of the word. + end = start + 1 + for end < strLen && sentenceBytes[end] != ' ' { + end += 1 + } + + // Let's call our helper function to reverse the word in-place. + sentenceBytes = strRev(sentenceBytes, start, end-1) + start = end + } + return string(sentenceBytes) +} + +// strRev function that reverses a whole sentence character by character +func strRev(str []byte, startRev int, endRev int) []byte { + // Starting from the two ends of the list, and moving + // in towards the centre of the string, swap the characters + for startRev < endRev { + temp := str[startRev] // temp store for swapping + str[startRev] = str[endRev] // swap step 1 + str[endRev] = temp // swap step 2 + + startRev += 1 // move forwards towards the middle + endRev -= 1 // move backwards towards the middle + } + + // Removing multiple spaces + // Removing multiple spaces + i := 0 + j := len(str) - 1 + strRes := make([]byte, 0) + for { + if str[i] != ' ' { + break + } + i++ + } + for { + if str[j] != ' ' { + break + } + j-- + } + for i <= j { + if str[i] == ' ' && strRes[len(strRes)-1] != ' ' { + strRes = append(strRes, str[i]) + } else if str[i] != ' ' { + strRes = append(strRes, str[i]) + } + i++ + } + + // Returning the reversed sentence + return strRes +} + +// Driver code +func main() { + stringToReverse := []string{"Hello World!", "We love Python.", "The quick brown fox jumped over the lazy dog.", "Hey!", "To be, or not to be", "AAAAA", "Hello World"} + + for i, str := range stringToReverse { + fmt.Printf("%d.\tActual string: \"%s\"\n", i+1, str) + fmt.Printf("\tReversed string: \"%s\"\n", reverseWords(str)) + fmt.Printf("%s\n", strings.Repeat("-", 100)) + } +} \ No newline at end of file From d4445cc384c73dc74931d3ba2d1513033d80c198 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Feb 2023 23:25:54 +0530 Subject: [PATCH 0153/1894] add description and time and space complexity --- Strings/reverse_word_in_a_string.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Strings/reverse_word_in_a_string.go b/Strings/reverse_word_in_a_string.go index 7fcd8891..d9c79837 100644 --- a/Strings/reverse_word_in_a_string.go +++ b/Strings/reverse_word_in_a_string.go @@ -1,3 +1,8 @@ +/* + Given a sentence, reverse the order of its words without affecting the order of letters within a given word. +*/ +// Time Complexity : O(n) n is length of string +// Space complexity : O(n) as we used additional space to store the list of characters as strings are immutable in go package main import ( From 21b5bcf074e267d9c6438337986672545f3a5bd2 Mon Sep 17 00:00:00 2001 From: Enrique Clerici <115318468+TheClerici@users.noreply.github.com> Date: Thu, 16 Feb 2023 11:47:46 -0700 Subject: [PATCH 0154/1894] Create SortColors.java Two Pointers: Add Dutch national flag problem in Java #322 --- Leetcode/SortColors.java | 58 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Leetcode/SortColors.java diff --git a/Leetcode/SortColors.java b/Leetcode/SortColors.java new file mode 100644 index 00000000..b977ca04 --- /dev/null +++ b/Leetcode/SortColors.java @@ -0,0 +1,58 @@ +/* +----- Problem explanation ----- +Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + +We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + +You must solve this problem without using the library's sort function. + +Example 1: + +Input: nums = [2,0,2,1,1,0] +Output: [0,0,1,1,2,2] + +Example 2: + +Input: nums = [2,0,1] +Output: [0,1,2] + +Constraints: + +n == nums.length +1 <= n <= 300 +nums[i] is either 0, 1, or 2. + +----- Approach ----- + +Take 3 Pointers low = 0, mid = 0 and high = nums.length -1; +Use loop to iterate the array with condition mid <= high.(Since we only need to check middle elements of low and high). +if element is 0 swap with low and low++, mid++. +if element is 1 then mid++. +if element is 2 then swap with high and high--. +*/ +class Solution { + public void sortColors(int[] nums) { + int low = 0, mid = 0, high = nums.length-1; + + while(mid <= high){ + if(nums[mid] == 0 ){ + //swap with left + swap(nums,low, mid ); + low++; + mid++; + }else if(nums[mid] == 2){ + swap(nums, mid, high); + high--; + }else{ + mid++; + } + } + System.out.println(nums); + } + + public static void swap(int[] nums, int i, int j){ + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +} From ba3877407b15a0d508c18743e1ac86241866064d Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:32:59 -0700 Subject: [PATCH 0155/1894] Number of Steps to Reduce a Number to Zero in Java Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ Answer to issue #615. --- Math/num_steps_reduce_to_zero.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Math/num_steps_reduce_to_zero.cpp diff --git a/Math/num_steps_reduce_to_zero.cpp b/Math/num_steps_reduce_to_zero.cpp new file mode 100644 index 00000000..a03b70bc --- /dev/null +++ b/Math/num_steps_reduce_to_zero.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int numberOfSteps(int num) { + // We initialize the step counter. + int steps = 0; + // While the number is still not zero... + while (num != 0) { + // ...we check if it is odd or even. + // If it is even... + if (num % 2 == 0) { + // ...we divide it by 2 and increase the step counter. + num /= 2; + steps++; + // If it is odd... + } else { + // ...we substract 1 and increase the step counter. + num -= 1; + steps++; + } + } + // Finally, we return the step counter. + return steps; + } +}; From 144436fd8dc0a934975cc94d156de6f135c860cd Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:42:04 -0700 Subject: [PATCH 0156/1894] Number of Steps to Reduce a Number to Zero in Java Number of Steps to Reduce a Number to Zero in Java Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ Answer to issue #615. --- Math/num_steps_reduce_to_zero.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Math/num_steps_reduce_to_zero.java diff --git a/Math/num_steps_reduce_to_zero.java b/Math/num_steps_reduce_to_zero.java new file mode 100644 index 00000000..9b994762 --- /dev/null +++ b/Math/num_steps_reduce_to_zero.java @@ -0,0 +1,23 @@ +class Solution { + public int numberOfSteps(int num) { + // We initialize the step counter. + int steps = 0; + // While the number is still not zero... + while (num != 0) { + // ...we check if it is odd or even. + // If it is even... + if (num % 2 == 0) { + // ...we divide it by 2 and increase the step counter. + num /= 2; + steps++; + // If it is odd... + } else { + // ...we substract 1 and increase the step counter. + num -= 1; + steps++; + } + } + // Finally, we return the step counter. + return steps; + } +} From ea5a0ab0c4d75e2157f59262199b6c6ae85a4998 Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:45:27 -0700 Subject: [PATCH 0157/1894] Number of Steps to Reduce a Number to Zero in Java Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ Answer to issue #615. --- Math/Math/num_steps_reduce_to_zero.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Math/Math/num_steps_reduce_to_zero.js diff --git a/Math/Math/num_steps_reduce_to_zero.js b/Math/Math/num_steps_reduce_to_zero.js new file mode 100644 index 00000000..cb8371c8 --- /dev/null +++ b/Math/Math/num_steps_reduce_to_zero.js @@ -0,0 +1,25 @@ +/** + * @param {number} num + * @return {number} + */ +var numberOfSteps = function(num) { + // We initialize the step counter. + let steps = 0; + // While the number is still not zero... + while (num != 0) { + // ...we check if it is odd or even. + // If it is even... + if (num % 2 == 0) { + // ...we divide it by 2 and increase the step counter. + num /= 2; + steps++; + // If it is odd... + } else { + // ...we substract 1 and increase the step counter. + num -= 1; + steps++; + } + } + // Finally, we return the step counter. + return steps; +}; From 809d790dc6ec7f6a8e63eb96522f9657ef3b9830 Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:51:44 -0700 Subject: [PATCH 0158/1894] Number of Steps to Reduce a Number to Zero in Python Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ --- Math/num_steps_reduce_to_zero.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Math/num_steps_reduce_to_zero.py diff --git a/Math/num_steps_reduce_to_zero.py b/Math/num_steps_reduce_to_zero.py new file mode 100644 index 00000000..5180507c --- /dev/null +++ b/Math/num_steps_reduce_to_zero.py @@ -0,0 +1,15 @@ +class Solution(object): + def numberOfSteps(self, num): + """ + :type num: int + :rtype: int + """ + steps = 0 + while num != 0: + if num % 2 == 0: + num = num / 2 + steps = steps + 1 + else: + num = num - 1 + steps = steps + 1 + return steps From 683dadc3886317678982c5d1d91628a3bb7e6684 Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:52:47 -0700 Subject: [PATCH 0159/1894] Wrong location for file. I accidentally made the directory when trying to place the file inside the only Math directory. --- Math/Math/num_steps_reduce_to_zero.js | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 Math/Math/num_steps_reduce_to_zero.js diff --git a/Math/Math/num_steps_reduce_to_zero.js b/Math/Math/num_steps_reduce_to_zero.js deleted file mode 100644 index cb8371c8..00000000 --- a/Math/Math/num_steps_reduce_to_zero.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @param {number} num - * @return {number} - */ -var numberOfSteps = function(num) { - // We initialize the step counter. - let steps = 0; - // While the number is still not zero... - while (num != 0) { - // ...we check if it is odd or even. - // If it is even... - if (num % 2 == 0) { - // ...we divide it by 2 and increase the step counter. - num /= 2; - steps++; - // If it is odd... - } else { - // ...we substract 1 and increase the step counter. - num -= 1; - steps++; - } - } - // Finally, we return the step counter. - return steps; -}; From dd8ecb38d1dbee4efc0b258f7de606a269bf62a0 Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:53:20 -0700 Subject: [PATCH 0160/1894] Number of Steps to Reduce a Number to Zero in JavaScript Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ --- Math/num_steps_reduce_to_zero.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Math/num_steps_reduce_to_zero.js diff --git a/Math/num_steps_reduce_to_zero.js b/Math/num_steps_reduce_to_zero.js new file mode 100644 index 00000000..cb8371c8 --- /dev/null +++ b/Math/num_steps_reduce_to_zero.js @@ -0,0 +1,25 @@ +/** + * @param {number} num + * @return {number} + */ +var numberOfSteps = function(num) { + // We initialize the step counter. + let steps = 0; + // While the number is still not zero... + while (num != 0) { + // ...we check if it is odd or even. + // If it is even... + if (num % 2 == 0) { + // ...we divide it by 2 and increase the step counter. + num /= 2; + steps++; + // If it is odd... + } else { + // ...we substract 1 and increase the step counter. + num -= 1; + steps++; + } + } + // Finally, we return the step counter. + return steps; +}; From 9ea444210a520473cd97cd5aad3c0743e0bd2357 Mon Sep 17 00:00:00 2001 From: Manuel Cota <108767897+MaAnCoSa@users.noreply.github.com> Date: Thu, 16 Feb 2023 14:59:11 -0700 Subject: [PATCH 0161/1894] Number of Steps to Reduce a Number to Zero in Go Added a solution to the problem from leetcode: https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ --- Math/num_steps_reduce_to_zero.Go | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Math/num_steps_reduce_to_zero.Go diff --git a/Math/num_steps_reduce_to_zero.Go b/Math/num_steps_reduce_to_zero.Go new file mode 100644 index 00000000..f2fe1689 --- /dev/null +++ b/Math/num_steps_reduce_to_zero.Go @@ -0,0 +1,13 @@ +func numberOfSteps(num int) int { + var steps = 0 + for num != 0 { + if num % 2 == 0 { + num /= 2 + steps++ + } else { + num -= 1 + steps++ + } + } + return steps +} From 9884b2121ed35c3add2f00e1c17d0ff6afe208e9 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 17 Feb 2023 15:45:55 +0530 Subject: [PATCH 0162/1894] Added factorial recursive in js --- Recursion/factorial.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Recursion/factorial.js diff --git a/Recursion/factorial.js b/Recursion/factorial.js new file mode 100644 index 00000000..828bc36c --- /dev/null +++ b/Recursion/factorial.js @@ -0,0 +1,16 @@ +// Program to find factorial till a given number +function recursiveFactorial(number) { + //Base case + if (number == 1) { + return 1; + } + + //recursively calling function to get factorial result + return number * recursiveFactorial(number - 1); +} + +// Driver code +console.log(recursiveFactorial(2)); +console.log(recursiveFactorial(3)); +console.log(recursiveFactorial(4)); +console.log(recursiveFactorial(5)); From cf609814d26fb3d2328d3fbdbfb2720a3ddbfff4 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 17 Feb 2023 15:57:14 +0530 Subject: [PATCH 0163/1894] Added iterative recursive in js --- Math/factorial_iterative.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Math/factorial_iterative.js diff --git a/Math/factorial_iterative.js b/Math/factorial_iterative.js new file mode 100644 index 00000000..e98cdb5e --- /dev/null +++ b/Math/factorial_iterative.js @@ -0,0 +1,19 @@ +// Program to find factorial till a given number +function factorialIterative(number) { + var factorialResult = 1; + + if (number == 0) { + return 0; + } + + for (i = 2; i <= number; i++) { + factorialResult *= i; + } + return factorialResult; +} + +// Driver code +console.log(factorialIterative(2)); +console.log(factorialIterative(3)); +console.log(factorialIterative(4)); +console.log(factorialIterative(5)); From 676983398662000e079a15a864bd4c89617baa08 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 17 Feb 2023 15:57:50 +0530 Subject: [PATCH 0164/1894] Added iterative in js --- Math/factorial_iterative.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Math/factorial_iterative.js b/Math/factorial_iterative.js index e98cdb5e..4e5971d0 100644 --- a/Math/factorial_iterative.js +++ b/Math/factorial_iterative.js @@ -6,7 +6,7 @@ function factorialIterative(number) { return 0; } - for (i = 2; i <= number; i++) { + for (i = 1; i <= number; i++) { factorialResult *= i; } return factorialResult; From 4efaa46d6fedfb1fd90dc8239fd21e845a0881b7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:22:47 +0530 Subject: [PATCH 0165/1894] rename files and remove duplicate folder --- .../{CeilLetter.java => ceil_letter.java} | 0 ...{CeilOfTarget.java => ceil_of_target.java} | 0 ...tion.java => first_and_last_position.java} | 0 .../first_last_pos.java | 0 ...rstOccurence.java => first_occurence.java} | 0 ...loorOfTarget.java => floor_of_target.java} | 0 ...IndexPosition.java => index_position.java} | 0 ...PerfectSquare.java => perfect_square.java} | 0 ...rray.java => search_in_rotated_array.java} | 196 +++++++++--------- .../{SquareRoot.java => square_root.java} | 0 10 files changed, 98 insertions(+), 98 deletions(-) rename Binary Search/{CeilLetter.java => ceil_letter.java} (100%) rename Binary Search/{CeilOfTarget.java => ceil_of_target.java} (100%) rename Binary Search/{FirstandLastPosition.java => first_and_last_position.java} (100%) rename Binary_Search/FirstLastPos.java => Binary Search/first_last_pos.java (100%) rename Binary Search/{FirstOccurence.java => first_occurence.java} (100%) rename Binary Search/{FloorOfTarget.java => floor_of_target.java} (100%) rename Binary Search/{IndexPosition.java => index_position.java} (100%) rename Binary Search/{PerfectSquare.java => perfect_square.java} (100%) rename Binary Search/{searchInRotatedArray.java => search_in_rotated_array.java} (95%) rename Binary Search/{SquareRoot.java => square_root.java} (100%) diff --git a/Binary Search/CeilLetter.java b/Binary Search/ceil_letter.java similarity index 100% rename from Binary Search/CeilLetter.java rename to Binary Search/ceil_letter.java diff --git a/Binary Search/CeilOfTarget.java b/Binary Search/ceil_of_target.java similarity index 100% rename from Binary Search/CeilOfTarget.java rename to Binary Search/ceil_of_target.java diff --git a/Binary Search/FirstandLastPosition.java b/Binary Search/first_and_last_position.java similarity index 100% rename from Binary Search/FirstandLastPosition.java rename to Binary Search/first_and_last_position.java diff --git a/Binary_Search/FirstLastPos.java b/Binary Search/first_last_pos.java similarity index 100% rename from Binary_Search/FirstLastPos.java rename to Binary Search/first_last_pos.java diff --git a/Binary Search/FirstOccurence.java b/Binary Search/first_occurence.java similarity index 100% rename from Binary Search/FirstOccurence.java rename to Binary Search/first_occurence.java diff --git a/Binary Search/FloorOfTarget.java b/Binary Search/floor_of_target.java similarity index 100% rename from Binary Search/FloorOfTarget.java rename to Binary Search/floor_of_target.java diff --git a/Binary Search/IndexPosition.java b/Binary Search/index_position.java similarity index 100% rename from Binary Search/IndexPosition.java rename to Binary Search/index_position.java diff --git a/Binary Search/PerfectSquare.java b/Binary Search/perfect_square.java similarity index 100% rename from Binary Search/PerfectSquare.java rename to Binary Search/perfect_square.java diff --git a/Binary Search/searchInRotatedArray.java b/Binary Search/search_in_rotated_array.java similarity index 95% rename from Binary Search/searchInRotatedArray.java rename to Binary Search/search_in_rotated_array.java index 467582ca..d84fbe0b 100644 --- a/Binary Search/searchInRotatedArray.java +++ b/Binary Search/search_in_rotated_array.java @@ -1,98 +1,98 @@ -/*There is an integer array nums sorted in ascending order (with distinct values). - -Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. - -Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. - -You must write an algorithm with O(log n) runtime complexity. - - - -Example 1: - -Input: nums = [4,5,6,7,0,1,2], target = 0 -Output: 4 -Example 2: - -Input: nums = [4,5,6,7,0,1,2], target = 3 -Output: -1 -Example 3: - -Input: nums = [1], target = 0 -Output: -1 - */ - - -public class searchInRotatedArray { - - //Brute force solution - - public static int searchTarget(int nums[] , int target) - { - int result = -1; - for(int i=0 ; i=target) - { - end = mid-1; - } - - else - { - start =mid+1; - } - } - - - else - { - if(nums[mid]<=target && target=target) + { + end = mid-1; + } + + else + { + start =mid+1; + } + } + + + else + { + if(nums[mid]<=target && target Date: Fri, 17 Feb 2023 22:32:46 +0530 Subject: [PATCH 0166/1894] rename file --- Hash Table/two_sum.go | 98 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Hash Table/two_sum.go diff --git a/Hash Table/two_sum.go b/Hash Table/two_sum.go new file mode 100644 index 00000000..7a2a6da8 --- /dev/null +++ b/Hash Table/two_sum.go @@ -0,0 +1,98 @@ +/* + Write a function that takes in a non-empty array of distinct integers and an + integer representing a target sum. If any two numbers in the input array sum + up to the target sum, the function should return them in an array, in any + order. If no two numbers sum up to the target sum, the function should return + an empty array. + Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 + Output: [-1 11] +*/ +package main + +import ( + "fmt" + "sort" +) + +// Bruteforce method continuously scan the array +// for every i run j len(array) times, if target sum is found then return +func TwoNUmberSumBruteForce(array []int, target int) []int { + // nil array to hold result + var result []int + for i := 0; i < len(array) - 1; i++ { + for j := i + 1; j < len(array); j++ { + // look for target + if array[i] + array[j] == target { + // add found values in array + result = append(result, array[i]) + result = append(result, array[j]) + return result + } + } + } + return result +} +// Two Pointer approach +// sort the given array, set i as initial index and j as last +// add element at i and j and compate with target, if it matches then return +// if element is greater then target decrease index of j by 1 +// if element is lesser then target increase index of i by 1 +func TwoNumberSumTwoPointerMethod(array []int, target int) []int { + var result []int + // sort the given array in place + sort.Ints(array) + j := len(array) - 1 // set j as last + i := 0 // set i as initial index + // i and j should not overlap + for i < j { + // check if it matches sum + if array[i] + array[j] == target { + // add result in array + result = append(result, array[i]) + result = append(result, array[j]) + // result the result + return result + } else if array[i] + array[j] > target { + // elements is greater that means look to left side of j + j--; + } else if array[i] + array[j] < target { + // // elements is smaller that means look to right side of i + i++; + } + } + return result +} + +func TwoNumberSum(array []int, target int) []int { + // Create map to keep track of what we ahve seen so far + m := make(map[int]int) + // initialize empty array for result + var result []int + // traverse array + for i := 0; i < len(array); i++ { + // lets say first element in our array is 3, and target sum is 10 + // then we will look for 7 in our map, if its present then we simply return 7 and 3 + required := target - array[i] + // if the required value is found then store result + if _, ok := m[required]; ok { + result = append(result, required) + result = append(result, array[i]) + return result + } else { + // keep track of what value in array we have seen so far + m[array[i]] = i + } + } + return result +} + +func main() { + arr := []int{2, 1, 3, -1, 11, 5, 4, 0} + msg := TwoNumberSum(arr, 10) + fmt.Println(msg) + msg = TwoNUmberSumBruteForce(arr, 10) + fmt.Println(msg) + arr = []int{2, 1, 3, -1, 11, 5, 4, 0, 44} + msg = TwoNumberSumTwoPointerMethod(arr, 9) + fmt.Println(msg) +} \ No newline at end of file From 178fb0bbd7b32df7ba6a584b7ebea667f99843d9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:33:00 +0530 Subject: [PATCH 0167/1894] update readme.md --- Hash Table/twosum.go | 98 -------------------------------------------- README.md | 12 ++++++ 2 files changed, 12 insertions(+), 98 deletions(-) delete mode 100644 Hash Table/twosum.go diff --git a/Hash Table/twosum.go b/Hash Table/twosum.go deleted file mode 100644 index 7a2a6da8..00000000 --- a/Hash Table/twosum.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - Write a function that takes in a non-empty array of distinct integers and an - integer representing a target sum. If any two numbers in the input array sum - up to the target sum, the function should return them in an array, in any - order. If no two numbers sum up to the target sum, the function should return - an empty array. - Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 - Output: [-1 11] -*/ -package main - -import ( - "fmt" - "sort" -) - -// Bruteforce method continuously scan the array -// for every i run j len(array) times, if target sum is found then return -func TwoNUmberSumBruteForce(array []int, target int) []int { - // nil array to hold result - var result []int - for i := 0; i < len(array) - 1; i++ { - for j := i + 1; j < len(array); j++ { - // look for target - if array[i] + array[j] == target { - // add found values in array - result = append(result, array[i]) - result = append(result, array[j]) - return result - } - } - } - return result -} -// Two Pointer approach -// sort the given array, set i as initial index and j as last -// add element at i and j and compate with target, if it matches then return -// if element is greater then target decrease index of j by 1 -// if element is lesser then target increase index of i by 1 -func TwoNumberSumTwoPointerMethod(array []int, target int) []int { - var result []int - // sort the given array in place - sort.Ints(array) - j := len(array) - 1 // set j as last - i := 0 // set i as initial index - // i and j should not overlap - for i < j { - // check if it matches sum - if array[i] + array[j] == target { - // add result in array - result = append(result, array[i]) - result = append(result, array[j]) - // result the result - return result - } else if array[i] + array[j] > target { - // elements is greater that means look to left side of j - j--; - } else if array[i] + array[j] < target { - // // elements is smaller that means look to right side of i - i++; - } - } - return result -} - -func TwoNumberSum(array []int, target int) []int { - // Create map to keep track of what we ahve seen so far - m := make(map[int]int) - // initialize empty array for result - var result []int - // traverse array - for i := 0; i < len(array); i++ { - // lets say first element in our array is 3, and target sum is 10 - // then we will look for 7 in our map, if its present then we simply return 7 and 3 - required := target - array[i] - // if the required value is found then store result - if _, ok := m[required]; ok { - result = append(result, required) - result = append(result, array[i]) - return result - } else { - // keep track of what value in array we have seen so far - m[array[i]] = i - } - } - return result -} - -func main() { - arr := []int{2, 1, 3, -1, 11, 5, 4, 0} - msg := TwoNumberSum(arr, 10) - fmt.Println(msg) - msg = TwoNUmberSumBruteForce(arr, 10) - fmt.Println(msg) - arr = []int{2, 1, 3, -1, 11, 5, 4, 0, 44} - msg = TwoNumberSumTwoPointerMethod(arr, 9) - fmt.Println(msg) -} \ No newline at end of file diff --git a/README.md b/README.md index 50eb55d7..1c180681 100644 --- a/README.md +++ b/README.md @@ -25,3 +25,15 @@ Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/ Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. - [How to Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo) + +# Pattern 1: Two Pointers + +As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. + +The pointers can be used to iterate the data structure in one or both directions, depending on the problem statement. For example, to identify whether a string is a palindrome, we can use one pointer to iterate the string from the beginning and the other to iterate it from the end. At each step, we can compare the values of the two pointers and see if they meet the palindrome properties. + +## Practice problems for two pointers + +Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) + +Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) From 9fc9f681f557f11e4443ef25bbce35dad6626e42 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:37:00 +0530 Subject: [PATCH 0168/1894] update contributing.md --- CONTRIBUTING.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b65b3775..f4816a6d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,12 @@ ## Contributing +🌈 Everyone is welcome! +You can join the fun by following our contributing guide. + +Before you get started, we encourage you to read these documents which describe some of our community norms: + +Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CODE_OF_CONDUCT.md), which stipulates explicitly that everyone must be gracious, respectful, and professional. This also documents our conflict resolution policy and encourages people to ask questions. + Contributions are always welcome! - Pick any good first issue and add comment on it (Example: "I'll take this up"), or Add classic DSA problem which is currently not present in this repo @@ -12,9 +19,11 @@ Contributions are always welcome! - Send a PR against dev branch ## What if the problem you want to add is not present in the issue? + - You can suggest an idea for this project under issues tab (add list of questions you think it is important, it will be assigned to you) - You can directly make a PR against dev branch with the proposed problems with appropriate comments and description ## What if the changes are inconsistent? + - Keep pulling from origin/main see below, this way you will be up to date with the latest changes in main branch - git pull origin main From dcfa571c18587f84b2363c44efc55246ce08e7e3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:37:06 +0530 Subject: [PATCH 0169/1894] update readme.md --- README.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/README.md b/README.md index 1c180681..8c1cfb5c 100644 --- a/README.md +++ b/README.md @@ -9,17 +9,8 @@ # Implementation of well known Data Structures and Algorithms -## Contributing - -🌈 Everyone is welcome! -You can join the fun by following our contributing guide. - Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) -Before you get started, we encourage you to read these documents which describe some of our community norms: - -Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CODE_OF_CONDUCT.md), which stipulates explicitly that everyone must be gracious, respectful, and professional. This also documents our conflict resolution policy and encourages people to ask questions. - ## Fork this repository Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. From 52504e56a41136cac4ba17d230ea3ad1d8ae2777 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:40:23 +0530 Subject: [PATCH 0170/1894] update readme.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8c1cfb5c..15f84a6d 100644 --- a/README.md +++ b/README.md @@ -28,3 +28,5 @@ The pointers can be used to iterate the data structure in one or both directions Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) + +Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) From d29b63c80807c7ea56dc3c52ca7f2a9f1ef3b018 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:41:05 +0530 Subject: [PATCH 0171/1894] add valid pallindrome link to readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 15f84a6d..0d0a6547 100644 --- a/README.md +++ b/README.md @@ -29,4 +29,6 @@ Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) +Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) + Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) From 0f152e6b26a0c1604fe708fe9e894ad7fc9f862a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:42:26 +0530 Subject: [PATCH 0172/1894] rename file --- Strings/{reverse_strings.js => reverse_word_in_a_string.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Strings/{reverse_strings.js => reverse_word_in_a_string.js} (100%) diff --git a/Strings/reverse_strings.js b/Strings/reverse_word_in_a_string.js similarity index 100% rename from Strings/reverse_strings.js rename to Strings/reverse_word_in_a_string.js From 6a6b35e2f3c605ed97c9d1dd7de41294c2eb76af Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:43:48 +0530 Subject: [PATCH 0173/1894] update readme with link to js version of reverse word in a string --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0d0a6547..b9f3a095 100644 --- a/README.md +++ b/README.md @@ -31,4 +31,4 @@ Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/ Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) -Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) +Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) From e4fcdc69efcd7e2e793004c392cf9107a9bc6487 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:48:23 +0530 Subject: [PATCH 0174/1894] add java link for two number sum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b9f3a095..d66aada9 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) +Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_number_sum.java) Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) From 521f9d19e77e09d11c725c73519d7b425322ab68 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Feb 2023 22:49:56 +0530 Subject: [PATCH 0175/1894] move forking to contributing.md --- CONTRIBUTING.md | 6 ++++++ README.md | 6 ------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f4816a6d..1c0c1840 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,6 +3,12 @@ 🌈 Everyone is welcome! You can join the fun by following our contributing guide. +## Fork this repository + +Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. + +- [How to Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo) + Before you get started, we encourage you to read these documents which describe some of our community norms: Our [code of conduct](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CODE_OF_CONDUCT.md), which stipulates explicitly that everyone must be gracious, respectful, and professional. This also documents our conflict resolution policy and encourages people to ask questions. diff --git a/README.md b/README.md index d66aada9..a8c98857 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,6 @@ Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) -## Fork this repository - -Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. - -- [How to Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo) - # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From c269ed829f4f50c46935710b7b77a68bfb572420 Mon Sep 17 00:00:00 2001 From: bprado Date: Fri, 17 Feb 2023 10:06:37 -0800 Subject: [PATCH 0176/1894] - implemented quick sort in java --- sorting/quick_sort.java | 69 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 sorting/quick_sort.java diff --git a/sorting/quick_sort.java b/sorting/quick_sort.java new file mode 100644 index 00000000..dade98c8 --- /dev/null +++ b/sorting/quick_sort.java @@ -0,0 +1,69 @@ +/* +Quick sort: +Quicksort picks an element as pivot, and then it partitions the given array around the picked pivot element. +In quick sort, a large array is divided into two arrays in which one holds values that are smaller than the +specified value (Pivot), and another array holds the values that are greater than the pivot. + +After that, left and right sub-arrays are also partitioned using the same approach. +It will continue until the single element remains in the sub-array. + +For more information: +--> https://www.geeksforgeeks.org/java-program-for-quicksort/ +--> https://www.javatpoint.com/quick-sort + */ + +package sorting; + +public class quick_sort { + public static void main(String[] args) { + int[] a = {15,4,3,7,13,2,6,7,3,2,1,5,6,3,2}; + int n = a.length; + + sort(a, 0, n-1); + + System.out.println("sorted array"); + for (int j : a) System.out.print(j + " "); + System.out.println(); + } + + /** + * + * @param a to be sorted + * @param start starting index + * @param end ending index + */ + private static void sort(int[] a, int start, int end){ + if (start < end) { + int p = partition(a, start, end); + sort(a, start, p-1); + sort(a, p+1, end); + } + } + + /** + * smaller elements to the left of the pivot, greater elements to the right + * @param a to be sorted + * @param start starting index + * @param end ending index + * @return index + */ + private static int partition(int[] a, int start, int end) { + int pivot = a[end]; + int i = (start-1); // index of smaller element + for (int j=start; j Date: Sat, 18 Feb 2023 03:00:02 +0530 Subject: [PATCH 0177/1894] Is power of two added --- Math/is_power_of_two.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Math/is_power_of_two.js diff --git a/Math/is_power_of_two.js b/Math/is_power_of_two.js new file mode 100644 index 00000000..7a5a2cfd --- /dev/null +++ b/Math/is_power_of_two.js @@ -0,0 +1,24 @@ +// Whether the provided number is power of two +function isPowerOfTwo(inputNumber) { + if (inputNumber <= 1) { + return false; + } + + var dividedNumber = inputNumber; + + while (dividedNumber !== 1) { + if (dividedNumber % 2 !== 0) { + return false; + } + dividedNumber = dividedNumber / 2; + } + return true; +} + +//Driver code +console.log(isPowerOfTwo(8)); +console.log(isPowerOfTwo(1)); +console.log(isPowerOfTwo(7)); +console.log(isPowerOfTwo(6)); +console.log(isPowerOfTwo(16)); +console.log(isPowerOfTwo(32)); From 96e889abb7623f8539d886f8539dc483a04fd44d Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sat, 18 Feb 2023 03:08:37 +0530 Subject: [PATCH 0178/1894] Is given number a prime number --- Math/isPrime.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Math/isPrime.js diff --git a/Math/isPrime.js b/Math/isPrime.js new file mode 100644 index 00000000..22c092d6 --- /dev/null +++ b/Math/isPrime.js @@ -0,0 +1,16 @@ +// Whether the given number is a prime nujmber or not + +function isPrime(input) { + for (i = 2; i < input; i++) { + if (input % i == 0) { + return "The number is not a prime number"; + break; + } else { + continue; + } + } + return "Given number is a prime number"; +} + +// Driver code +console.log(isPrime(6)); From 2fd44cacb58b5607f0ccb17c2422d6befc501000 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sat, 18 Feb 2023 03:34:31 +0530 Subject: [PATCH 0179/1894] Two_sum added --- Arrays/two_sum.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Arrays/two_sum.js diff --git a/Arrays/two_sum.js b/Arrays/two_sum.js new file mode 100644 index 00000000..07459185 --- /dev/null +++ b/Arrays/two_sum.js @@ -0,0 +1,19 @@ +//Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. +// https://leetcode.com/problems/two-sum/ + +function twoSum(nums, target) { + for (i = 0; i < nums.length; i++) { + for (j = 0; j < nums.length; j++) { + if (i == j) { + continue; + } + if (nums[i] + nums[j] == target) { + return [i, j]; + break; + } + } + } +} + +// Driver code +console.log(twoSum([3, 2, 4], 6)); From fb6845c8d84cf10e4f7028fc14270be75badab9e Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sat, 18 Feb 2023 04:04:55 +0530 Subject: [PATCH 0180/1894] Is plaindrome javascript added --- Strings/is_ palindrome.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Strings/is_ palindrome.js diff --git a/Strings/is_ palindrome.js b/Strings/is_ palindrome.js new file mode 100644 index 00000000..e520a9bc --- /dev/null +++ b/Strings/is_ palindrome.js @@ -0,0 +1,21 @@ +// Check whether a given string is a Valid Palindrome in Javascript +function isPalindrome(inputString) { + var stringArray = inputString.trim().toLowerCase().split(""); + + var reverseString = ""; + + for (i = stringArray.length - 1; i >= 0; i--) { + reverseString += stringArray[i]; + } + + if ( + inputString.trim().toLowerCase() == reverseString.trim().toLowerCase() + ) { + return true; + } else { + return false; + } +} + +// Driver code +console.log(isPalindrome("Kayak")); From 972a9a6442c1335a19be5068bf7a333ab2bab719 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 13:31:20 +0530 Subject: [PATCH 0181/1894] update reverse word in a string using regexp and strings --- Strings/reverse_word_in_a_string.go | 54 +++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Strings/reverse_word_in_a_string.go b/Strings/reverse_word_in_a_string.go index d9c79837..1cc32189 100644 --- a/Strings/reverse_word_in_a_string.go +++ b/Strings/reverse_word_in_a_string.go @@ -7,6 +7,7 @@ package main import ( "fmt" + "regexp" "strings" ) @@ -100,4 +101,57 @@ func main() { fmt.Printf("\tReversed string: \"%s\"\n", reverseWords(str)) fmt.Printf("%s\n", strings.Repeat("-", 100)) } + fmt.Printf("%s\n", strings.Repeat("*", 100)) + for i, str := range stringToReverse { + fmt.Printf("%d.\tActual string: \"%s\"\n", i+1, str) + fmt.Printf("\tReversed string: \"%s\"\n", ReverseWordsNew(str)) + fmt.Printf("%s\n", strings.Repeat("-", 100)) + } +} + +// Using regexp and strings library + +func ReverseWordsNew(s string) string { + // trim leading and multiple spaces + trimmedString := trimHelper(s) + // convert string into array bytes since strings are immutable in go + sBytes := []byte(trimmedString) + // reverse the entire sBytes first + strlen := len(sBytes) + reversedString := revHelper(sBytes, 0, strlen - 1) + + // this way words will be in desired position + + start, end := 0, 0 + for { + for start < strlen && reversedString[start] == ' ' { + start += 1; + } + if start == strlen { + break + } + end = start + 1 + for end < strlen && reversedString[end] != ' ' { + end += 1 + } + reversedString = revHelper(reversedString, start, end - 1) + start = end + } + return string(reversedString) +} + +func trimHelper(s string) string { + result := strings.TrimSpace(s) + regex := regexp.MustCompile("\\s+") + result = regex.ReplaceAllString(result, " ") + return result +} + +func revHelper(s []byte, start int, end int) []byte { + for start < end { + s[start], s[end] = s[end], s[start] + start += 1 + end -= 1 + } + return s } \ No newline at end of file From 1ce281c26ad0dbfb9fdf048924eeb860519d424b Mon Sep 17 00:00:00 2001 From: "melinaz@live.com" Date: Sat, 18 Feb 2023 14:15:41 +0200 Subject: [PATCH 0182/1894] Implementation of TimSort in Python --- sorting/tim_sort.py | 128 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 sorting/tim_sort.py diff --git a/sorting/tim_sort.py b/sorting/tim_sort.py new file mode 100644 index 00000000..ba524c43 --- /dev/null +++ b/sorting/tim_sort.py @@ -0,0 +1,128 @@ +""" +Implementation of Tim Sort in Python + +Tim Sort is based on Insertion and Merge Sort. + +The steps of the algorithm are: + +1. Divide the input array into blocks called runs +2. The size of a run can either be 32 or 64 +3. Sort the elements of every run with insertion sort +4. Merge the sorted runs using with merge sort +5. After every iteration double the size of the merged array + +""" + +MINIMUM = 32 + +# Returns the minrun = the minimum length of a run +def find_minrun(n): + + r = 0 + while n >= MINIMUM: + r |= n & 1 + n >>= 1 + + return n + r + + +# Sorts an array from left to right index (Insertion Sort) +def insertion_sort(array, left, right): + for i in range(left + 1, right + 1): + j = i + while j > left and array[j] < array[j - 1]: + array[j], array[j - 1] = array[j - 1], array[j] + j -= 1 + + +# Merges the sorted runs +def merge(array, l, m, r): + + # original array is broken in two parts: left - right + + array_len1 = m - l + 1 + array_len2 = r - m + + left = [] + right = [] + + for i in range(0, array_len1): + left.append(array[l + i]) + + for i in range(0, array_len2): + right.append(array[m + 1 + i]) + + i = 0 + j = 0 + k = l + + # merge the two arrays in a larger sub array + while i < array_len1 and j < array_len2: + if left[i] <= right[j]: + arr[k] = left[i] + i += 1 + + else: + arr[k] = right[j] + j += 1 + + k += 1 + + # Copy remaining elements of the left part, if any + while i < array_len1: + arr[k] = left[i] + k += 1 + i += 1 + + # Copy remaining element of the right part, if any + while j Date: Sat, 18 Feb 2023 19:51:39 +0530 Subject: [PATCH 0183/1894] remove test folder --- Test/hello.js | 1 - Test/hello.py | 1 - 2 files changed, 2 deletions(-) delete mode 100644 Test/hello.js delete mode 100644 Test/hello.py diff --git a/Test/hello.js b/Test/hello.js deleted file mode 100644 index ad86b2ec..00000000 --- a/Test/hello.js +++ /dev/null @@ -1 +0,0 @@ -console.log("hello"); \ No newline at end of file diff --git a/Test/hello.py b/Test/hello.py deleted file mode 100644 index 8405850b..00000000 --- a/Test/hello.py +++ /dev/null @@ -1 +0,0 @@ -print("Testing!") From f55d956d65592d832df851c865e0c0ae44050e44 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 19:54:46 +0530 Subject: [PATCH 0184/1894] fix typo --- Hash Table/two_sum.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash Table/two_sum.go b/Hash Table/two_sum.go index 7a2a6da8..ba8f04b2 100644 --- a/Hash Table/two_sum.go +++ b/Hash Table/two_sum.go @@ -50,7 +50,7 @@ func TwoNumberSumTwoPointerMethod(array []int, target int) []int { // add result in array result = append(result, array[i]) result = append(result, array[j]) - // result the result + // return the result return result } else if array[i] + array[j] > target { // elements is greater that means look to left side of j From 8cb1eefd983da5a4c2078fef790292d3cc4249d2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 19:54:55 +0530 Subject: [PATCH 0185/1894] rename file --- Hash Table/{two_number_sum.java => two_sum.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash Table/{two_number_sum.java => two_sum.java} (100%) diff --git a/Hash Table/two_number_sum.java b/Hash Table/two_sum.java similarity index 100% rename from Hash Table/two_number_sum.java rename to Hash Table/two_sum.java From aa7429e095ed4a3abcd820aa0aa00aaf9aa7896d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 19:56:21 +0530 Subject: [PATCH 0186/1894] add two sum in cpp --- Hash Table/two_sum.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hash Table/two_sum.cpp diff --git a/Hash Table/two_sum.cpp b/Hash Table/two_sum.cpp new file mode 100644 index 00000000..9f068cc2 --- /dev/null +++ b/Hash Table/two_sum.cpp @@ -0,0 +1,35 @@ +/* + Write a function that takes in a non-empty array of distinct integers and an + integer representing a target sum. If any two numbers in the input array sum + up to the target sum, the function should return them in an array, in any + order. If no two numbers sum up to the target sum, the function should return + an empty array. + Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 + Output: [-1 11] +*/ +// Two Pointer approach +// sort the given array, set i as initial index and j as last +// add element at i and j and compate with target, if it matches then return +// if element is greater then target decrease index of j by 1 +// if element is lesser then target increase index of i by 1 +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map mp; + vector result; // result vector + for(int i = 0; i < nums.size(); i++){ + // lets say first element in our array is 3, and target sum is 10 + // then we will look for 7 in our map, if its present then we simply return 7 and 3 + int to_find = target - nums[i]; + // if the required value is found then store result + if(mp.find(to_find) != mp.end()){ + result.push_back(mp[to_find]); + result.push_back(i); + return result; + } + // keep track of what value in array we have seen so far + mp[nums[i]] = i; + } + return result; + } +}; \ No newline at end of file From 5be84ffeed4f5995d2b896836efad346c028debf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 19:58:07 +0530 Subject: [PATCH 0187/1894] add link to cpp version of 2sum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8c98857..344b240f 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_number_sum.java) +Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) From 0663b3ddf0072c4a8e7a3b39f938f3005e8f7944 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 20:02:32 +0530 Subject: [PATCH 0188/1894] add brute force approach of two sum in py --- Hash Table/two_sum.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Hash Table/two_sum.py diff --git a/Hash Table/two_sum.py b/Hash Table/two_sum.py new file mode 100644 index 00000000..4cba5352 --- /dev/null +++ b/Hash Table/two_sum.py @@ -0,0 +1,18 @@ +''' + Write a function that takes in a non-empty array of distinct integers and an + integer representing a target sum. If any two numbers in the input array sum + up to the target sum, the function should return them in an array, in any + order. If no two numbers sum up to the target sum, the function should return + an empty array. + Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 + Output: [-1 11] +''' +# Brute Force Approach +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i in range(len(nums)): + for j in range(i + 1, len(nums)): + if nums[i] + nums[j] == target: + return [i, j] + return [] + From ca82e8d4ea35d405237fb20acddc2d8433b02436 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 20:02:46 +0530 Subject: [PATCH 0189/1894] add two pointers approach of 2 sum in py --- Hash Table/two_sum.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Hash Table/two_sum.py b/Hash Table/two_sum.py index 4cba5352..49ebc056 100644 --- a/Hash Table/two_sum.py +++ b/Hash Table/two_sum.py @@ -16,3 +16,17 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: return [i, j] return [] +# Two Pointer approach +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + # Create map to keep track of what we ahve seen so far + numToIndex = {} + for i in range(len(nums)): + # lets say first element in our array is 3, and target sum is 10 + # then we will look for 7 in our map, if its present then we simply return 7 and 3 + # if the required value is found then store result + if target - nums[i] in numToIndex: + return [numToIndex[target - nums[i]], i] + # keep track of what value in array we have seen so far + numToIndex[nums[i]] = i + return [] \ No newline at end of file From 1e2fec2d4a518c422e33c4cfe6a87650be9b969d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 20:05:41 +0530 Subject: [PATCH 0190/1894] add time and space complexity --- Hash Table/two_sum.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Hash Table/two_sum.py b/Hash Table/two_sum.py index 49ebc056..2d97f679 100644 --- a/Hash Table/two_sum.py +++ b/Hash Table/two_sum.py @@ -8,6 +8,8 @@ Output: [-1 11] ''' # Brute Force Approach +# Time complexity: O(N^2); +# Space Complexity: O(1); class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): @@ -17,6 +19,8 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: return [] # Two Pointer approach +# Time complexity: O(N); +# Space Complexity: O(N); class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # Create map to keep track of what we ahve seen so far From 7bae117ebc651d19dc82653f773ce98cc315fd59 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 20:05:51 +0530 Subject: [PATCH 0191/1894] update py link to 2 sum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 344b240f..e455d284 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) +Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) From 67929f6f20d9792d016a9c0a8bfb61a50bb68a3d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 20:11:19 +0530 Subject: [PATCH 0192/1894] reformat code --- Hash Table/two_sum.java | 69 +++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/Hash Table/two_sum.java b/Hash Table/two_sum.java index 61620494..bcbccb18 100644 --- a/Hash Table/two_sum.java +++ b/Hash Table/two_sum.java @@ -1,31 +1,40 @@ +/* + Write a function that takes in a non-empty array of distinct integers and an + integer representing a target sum. If any two numbers in the input array sum + up to the target sum, the function should return them in an array, in any + order. If no two numbers sum up to the target sum, the function should return + an empty array. + Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 + Output: [-1 11] +*/ import java.util.*; -/** - * - - Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the function should return an empty array. - - Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum. - - You can assume that there will be at most one pair of numbers summing up to the target sum. - Sample Input - - array = [3, 5, -4, 8, 11, 1, -1, 6] - targetSum = 10 - - Sample Output - - [-1, 11] // the numbers could be in reverse order - - - */ public class TwoNumberSum { + public static void main(String[] args) { int[] array = {3, 5, -4, 8, 11, 1, -1, 6}; int targetSum = 10; } - public static int[] twoNumberSumOptimal(int[] array, int targetSum) { -// O(nlog(n)) time | O(1) space + + // Brute Force Solution + // Time complexity: O(N^2); + // Space Complexity: O(1); + public static int[] TwoSumBruteForce(int[] array, int targetSum) { + for(int i = 0; i < array.length - 1; i++) { + int firstNum = array[i]; + for(int j = i + 1; j < array.length; j++) { + int secondNum = array[j]; + if(firstNum + secondNum == targetSum) + return new int[] {firstNum, secondNum}; + } + } return new int[0]; + } + + // Sorting Solution + // Time complexity: O(N log N); + // Space Complexity: O(1); + public static int[] TwoSumBySorting(int[] array, int targetSum) { + // O(nlog(n)) time | O(1) space Arrays.sort(array); int left = 0; int right = array.length - 1; @@ -38,8 +47,11 @@ public static int[] twoNumberSumOptimal(int[] array, int targetSum) { else right -= 1; } return new int[0]; } - public static int[] twoNumberSumUsingSet(int[] array, int targetSum) { -// O(n) time | O(n) space + + // Optimal Solution + // Time complexity: O(N); + // Space Complexity: O(N); + public static int[] TwoSumOptimal(int[] array, int targetSum) { Set nums = new HashSet<>(); for(int num: array) { int potentialMatch = targetSum - num; @@ -47,15 +59,4 @@ public static int[] twoNumberSumUsingSet(int[] array, int targetSum) { nums.add(num); } return new int[0]; } - public static int[] twoNumberSumBruteForce(int[] array, int targetSum) { -// O(n^2) time | O(1) space - for(int i = 0; i < array.length - 1; i++) { - int firstNum = array[i]; - for(int j = i + 1; j < array.length; j++) { - int secondNum = array[j]; - if(firstNum + secondNum == targetSum) - return new int[] {firstNum, secondNum}; - } - } return new int[0]; - } } From 80a1deac364722c35b02dfe311155a903161aea2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 22:58:06 +0530 Subject: [PATCH 0193/1894] rename file --- Math/isPrime.js | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 Math/isPrime.js diff --git a/Math/isPrime.js b/Math/isPrime.js deleted file mode 100644 index 22c092d6..00000000 --- a/Math/isPrime.js +++ /dev/null @@ -1,16 +0,0 @@ -// Whether the given number is a prime nujmber or not - -function isPrime(input) { - for (i = 2; i < input; i++) { - if (input % i == 0) { - return "The number is not a prime number"; - break; - } else { - continue; - } - } - return "Given number is a prime number"; -} - -// Driver code -console.log(isPrime(6)); From 12068de6b705fb99a4fb6ee214d31e63749a9097 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 22:58:15 +0530 Subject: [PATCH 0194/1894] add optimal solution for is prime --- Math/is_prime.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Math/is_prime.js diff --git a/Math/is_prime.js b/Math/is_prime.js new file mode 100644 index 00000000..018fb1c6 --- /dev/null +++ b/Math/is_prime.js @@ -0,0 +1,27 @@ +// Whether the given number is a prime nujmber or not +// Time complexity O(n) +function isPrime(input) { + for (i = 2; i < input; i++) { + if (input % i == 0) { + return "The number is not a prime number"; + break; + } else { + continue; + } + } + return "Given number is a prime number"; +} + +// Driver code +console.log(isPrime(6)); + +// Time complexity: O(sqrt(n)) +// Space complexity: O(1) +const isPrime = (num) => { + for (let i = 2, s = Math.sqrt(num); i <= s; i++) { + if (num % i === 0) return false; + } + return num > 1; +}; + +console.log(isPrime(10)); From 90ece32c47235d7512addc6a7477b38ceba628cf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 23:00:02 +0530 Subject: [PATCH 0195/1894] update contributing.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c0c1840..e2065e20 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,7 +22,7 @@ Contributions are always welcome! - Explain approach with comments - Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) -- Send a PR against dev branch +- Send a Pull Request (PR) against main branch ## What if the problem you want to add is not present in the issue? From 732e3afd8f129fb90f4a61bfef773580d35e4393 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 23:02:02 +0530 Subject: [PATCH 0196/1894] rename file --- Math/{pow.js => powXn.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Math/{pow.js => powXn.js} (100%) diff --git a/Math/pow.js b/Math/powXn.js similarity index 100% rename from Math/pow.js rename to Math/powXn.js From ae3df5979f192757c70b9601d511052f14ff5042 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Feb 2023 23:02:32 +0530 Subject: [PATCH 0197/1894] rename file --- Strings/length_of_longest_substring.java | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Strings/length_of_longest_substring.java diff --git a/Strings/length_of_longest_substring.java b/Strings/length_of_longest_substring.java new file mode 100644 index 00000000..446cef52 --- /dev/null +++ b/Strings/length_of_longest_substring.java @@ -0,0 +1,49 @@ +/* Implement lengthOfLongestSubstring(s), which calculates the length of the longest possible substring that does not contain repeating characters. + +Example 1: +Input: "abcabcbaba" +Output: 3 + +Example 2: +Input: "dddddddd" +Output: 1 + +Example 3: +Input: "pwwkewo" +Output: 4 + +Constraints: +0 <= s.length <= 5 * 10^4 + +Time complexity: O(n^2) +Space complexity: O(1) + +*/ + +class Solution { + public int lengthOfLongestSubstring(String s) { + int length = s.length(); + if (length==0) { + return 0; + } + + int max = 1; + // Aiming to find substring of s that starts at index i and ends at j-1. + int i = 0; + int j = i+1; + + while (j max) { + max = j-i; + } + + i++; + } + + return max; + } +} From 30af3e8f2a8ca8f57f835f09cca1575e8a22d55b Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 19 Feb 2023 02:02:21 +0530 Subject: [PATCH 0198/1894] Two pointer approach added for palindrome --- Strings/is_ palindrome.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Strings/is_ palindrome.js b/Strings/is_ palindrome.js index e520a9bc..4cbf225c 100644 --- a/Strings/is_ palindrome.js +++ b/Strings/is_ palindrome.js @@ -1,4 +1,27 @@ // Check whether a given string is a Valid Palindrome in Javascript + +// Two pointer approach +function isPalindromeTwoPointer(inputString) { + var string = inputString.trim().toLowerCase(); + + if (string == "") { + return false; + } + + var leftIndex = 0; + var rightIndex = string.length - 1; + + while (leftIndex < rightIndex) { + if (string[leftIndex] !== string[rightIndex]) { + return false; + } + leftIndex++; + rightIndex--; + } + return true; +} + +// Reverse String approach function isPalindrome(inputString) { var stringArray = inputString.trim().toLowerCase().split(""); @@ -18,4 +41,5 @@ function isPalindrome(inputString) { } // Driver code -console.log(isPalindrome("Kayak")); +console.log(isPalindrome("Kaayak")); +console.log(isPalindromeTwoPointer("Kayak")); From aff9b697fc4bab91c9d4f5076f452a03cf7c42d9 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 19 Feb 2023 02:29:24 +0530 Subject: [PATCH 0199/1894] Is prime optimized --- Math/isPrime.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Math/isPrime.js b/Math/isPrime.js index 22c092d6..952d7b62 100644 --- a/Math/isPrime.js +++ b/Math/isPrime.js @@ -1,5 +1,6 @@ // Whether the given number is a prime nujmber or not +// Time complexity - O(n) function isPrime(input) { for (i = 2; i < input; i++) { if (input % i == 0) { @@ -12,5 +13,19 @@ function isPrime(input) { return "Given number is a prime number"; } +// Time complexity - (O logn) +function isPrimeLogn(input) { + for (i = 2; i < Math.sqrt(input); i++) { + if (input % i == 0) { + return "The number is not a prime number"; + break; + } else { + continue; + } + } + return "Given number is a prime number"; +} + // Driver code console.log(isPrime(6)); +console.log(isPrimeLogn(7)); From a41a9310476e21958ac3bc6348e26410e003db78 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 19 Feb 2023 02:33:06 +0530 Subject: [PATCH 0200/1894] Typo fixed --- Math/isPrime.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Math/isPrime.js b/Math/isPrime.js index 952d7b62..e0da274d 100644 --- a/Math/isPrime.js +++ b/Math/isPrime.js @@ -1,4 +1,4 @@ -// Whether the given number is a prime nujmber or not +// Whether the given number is a prime number or not // Time complexity - O(n) function isPrime(input) { @@ -13,7 +13,7 @@ function isPrime(input) { return "Given number is a prime number"; } -// Time complexity - (O logn) +// Time complexity - O(logn) function isPrimeLogn(input) { for (i = 2; i < Math.sqrt(input); i++) { if (input % i == 0) { From 3d368ebea9025d2194abf5d7dea22c663ec877b2 Mon Sep 17 00:00:00 2001 From: WesleyHanauer Date: Sat, 18 Feb 2023 18:16:52 -0300 Subject: [PATCH 0201/1894] Check if the given number is a palindrome --- Math/Check_if_X_is_palindrome.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Math/Check_if_X_is_palindrome.cpp diff --git a/Math/Check_if_X_is_palindrome.cpp b/Math/Check_if_X_is_palindrome.cpp new file mode 100644 index 00000000..5915490e --- /dev/null +++ b/Math/Check_if_X_is_palindrome.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isPalindrome(int x) { + + if (x < 0 || (x % 10 == 0 && x != 0)) { + return false; + } + + int reversed = 0; + while (x > reversed) { + reversed = reversed * 10 + x % 10; + x /= 10; + } + + return x == reversed || x == reversed / 10; + } +}; \ No newline at end of file From a4a07316355e2d5e79af894a2b38a9e898d4a6f3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 12:56:40 +0530 Subject: [PATCH 0202/1894] rename file --- Strings/lengthOfLongestSubstring.java | 49 --------------------------- 1 file changed, 49 deletions(-) delete mode 100644 Strings/lengthOfLongestSubstring.java diff --git a/Strings/lengthOfLongestSubstring.java b/Strings/lengthOfLongestSubstring.java deleted file mode 100644 index 446cef52..00000000 --- a/Strings/lengthOfLongestSubstring.java +++ /dev/null @@ -1,49 +0,0 @@ -/* Implement lengthOfLongestSubstring(s), which calculates the length of the longest possible substring that does not contain repeating characters. - -Example 1: -Input: "abcabcbaba" -Output: 3 - -Example 2: -Input: "dddddddd" -Output: 1 - -Example 3: -Input: "pwwkewo" -Output: 4 - -Constraints: -0 <= s.length <= 5 * 10^4 - -Time complexity: O(n^2) -Space complexity: O(1) - -*/ - -class Solution { - public int lengthOfLongestSubstring(String s) { - int length = s.length(); - if (length==0) { - return 0; - } - - int max = 1; - // Aiming to find substring of s that starts at index i and ends at j-1. - int i = 0; - int j = i+1; - - while (j max) { - max = j-i; - } - - i++; - } - - return max; - } -} From b1eed3505a4019b043f8742ce355cd0d8afd684e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 12:58:05 +0530 Subject: [PATCH 0203/1894] rename file --- ...lerNumberThanCurrent.java => smaller_number_than_current.java} | 0 .../{SumOfUniqueElements.java => sum_of_unique_elements.java} | 0 Leetcode/{SortColors.java => sort_colors.java} | 0 ...chars.cpp => len_of_concatenated_string_with_unique_chars.cpp} | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename Hash Table/{SmallerNumberThanCurrent.java => smaller_number_than_current.java} (100%) rename Hash Table/{SumOfUniqueElements.java => sum_of_unique_elements.java} (100%) rename Leetcode/{SortColors.java => sort_colors.java} (100%) rename Strings/{_len_of_concatenated_string_with_unique_chars.cpp => len_of_concatenated_string_with_unique_chars.cpp} (100%) diff --git a/Hash Table/SmallerNumberThanCurrent.java b/Hash Table/smaller_number_than_current.java similarity index 100% rename from Hash Table/SmallerNumberThanCurrent.java rename to Hash Table/smaller_number_than_current.java diff --git a/Hash Table/SumOfUniqueElements.java b/Hash Table/sum_of_unique_elements.java similarity index 100% rename from Hash Table/SumOfUniqueElements.java rename to Hash Table/sum_of_unique_elements.java diff --git a/Leetcode/SortColors.java b/Leetcode/sort_colors.java similarity index 100% rename from Leetcode/SortColors.java rename to Leetcode/sort_colors.java diff --git a/Strings/_len_of_concatenated_string_with_unique_chars.cpp b/Strings/len_of_concatenated_string_with_unique_chars.cpp similarity index 100% rename from Strings/_len_of_concatenated_string_with_unique_chars.cpp rename to Strings/len_of_concatenated_string_with_unique_chars.cpp From 81df52f14cbdf716c68a9d0576c59af561483783 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:01:59 +0530 Subject: [PATCH 0204/1894] remove duplicate file --- Math/isPrime.js | 31 ------------------------------- Math/is_prime.js | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 31 deletions(-) delete mode 100644 Math/isPrime.js diff --git a/Math/isPrime.js b/Math/isPrime.js deleted file mode 100644 index e0da274d..00000000 --- a/Math/isPrime.js +++ /dev/null @@ -1,31 +0,0 @@ -// Whether the given number is a prime number or not - -// Time complexity - O(n) -function isPrime(input) { - for (i = 2; i < input; i++) { - if (input % i == 0) { - return "The number is not a prime number"; - break; - } else { - continue; - } - } - return "Given number is a prime number"; -} - -// Time complexity - O(logn) -function isPrimeLogn(input) { - for (i = 2; i < Math.sqrt(input); i++) { - if (input % i == 0) { - return "The number is not a prime number"; - break; - } else { - continue; - } - } - return "Given number is a prime number"; -} - -// Driver code -console.log(isPrime(6)); -console.log(isPrimeLogn(7)); diff --git a/Math/is_prime.js b/Math/is_prime.js index 018fb1c6..a0954483 100644 --- a/Math/is_prime.js +++ b/Math/is_prime.js @@ -25,3 +25,20 @@ const isPrime = (num) => { }; console.log(isPrime(10)); + +// Time complexity - O(logn) +function isPrimeLogn(input) { + for (i = 2; i < Math.sqrt(input); i++) { + if (input % i == 0) { + return "The number is not a prime number"; + break; + } else { + continue; + } + } + return "Given number is a prime number"; +} + +// Driver code +console.log(isPrime(6)); +console.log(isPrimeLogn(7)); From f507941c9edf0a61e8e3f6b64febd94d64d2540d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:02:39 +0530 Subject: [PATCH 0205/1894] add better naming --- Math/Check_if_X_is_palindrome.cpp | 17 ----------------- Math/check_if_num_is_palindrome.cpp | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 17 deletions(-) delete mode 100644 Math/Check_if_X_is_palindrome.cpp create mode 100644 Math/check_if_num_is_palindrome.cpp diff --git a/Math/Check_if_X_is_palindrome.cpp b/Math/Check_if_X_is_palindrome.cpp deleted file mode 100644 index 5915490e..00000000 --- a/Math/Check_if_X_is_palindrome.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - bool isPalindrome(int x) { - - if (x < 0 || (x % 10 == 0 && x != 0)) { - return false; - } - - int reversed = 0; - while (x > reversed) { - reversed = reversed * 10 + x % 10; - x /= 10; - } - - return x == reversed || x == reversed / 10; - } -}; \ No newline at end of file diff --git a/Math/check_if_num_is_palindrome.cpp b/Math/check_if_num_is_palindrome.cpp new file mode 100644 index 00000000..621974c9 --- /dev/null +++ b/Math/check_if_num_is_palindrome.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isPalindrome(int num) { + + if (num < 0 || (num % 10 == 0 && num != 0)) { + return false; + } + + int reversed = 0; + while (num > reversed) { + reversed = reversed * 10 + num % 10; + num /= 10; + } + + return num == reversed || num == reversed / 10; + } +}; \ No newline at end of file From 83d324115e5b89796cf96d73f8249cd5c7e6471b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:10:18 +0530 Subject: [PATCH 0206/1894] updaet readme.md --- README.md | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e455d284..dc84b4de 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,26 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) +- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) -Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) +- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) -Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) -Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) +- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) + +# Pattern 2: Fast and Slow Pointers + +Similar to the two pointers pattern, the fast and slow pointers pattern uses two pointers to traverse an iterable data structure at different speeds. It’s usually used to identify distinguishable features of directional data structures, such as a linked list or an array. + +The pointers can be used to traverse the array or list in either direction, however, one moves faster than the other. Generally, the slow pointer moves forward by a factor of one, and the fast pointer moves by a factor of two in each step. However, the speed can be adjusted according to the problem statement. + +Unlike the two pointers approach, which is concerned with data values, the fast and slow pointers approach is used to determine data structure traits using indices in arrays or node pointers in linked lists. The approach is commonly used to detect cycles in the given data structure, so it’s also known as Floyd’s cycle detection algorithm. + +The key idea is that the pointers start at the same location, but they move forward at different speeds. If there is a cycle, the two are bound to meet at some point in the traversal. To understand the concept, think of two runners on a track. While they start from the same point, they have different running speeds. If the race track is a circle, the faster runner will overtake the slower one after completing a lap. On the other hand, if the track is straight, the faster runner will end the race before the slower one, hence never meeting on the track again. The fast and slow pointers pattern uses the same intuition. + +## Practice problems for fast and slow pointers + +- Linked List cycle detection +- Find middle of Linked List +- Pallindrome Linked List From 9df2c42aa231f38aa8cbefe8c095a8d5d8a8ca98 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:11:27 +0530 Subject: [PATCH 0207/1894] update readme.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index dc84b4de..10e5f5af 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ The pointers can be used to iterate the data structure in one or both directions # Pattern 2: Fast and Slow Pointers +The fast and slow pointer technique (also known as the tortoise and hare algorithm) uses two pointers to determine traits about directional data structures. This can be an array, singly-linked list, or a graph. + Similar to the two pointers pattern, the fast and slow pointers pattern uses two pointers to traverse an iterable data structure at different speeds. It’s usually used to identify distinguishable features of directional data structures, such as a linked list or an array. The pointers can be used to traverse the array or list in either direction, however, one moves faster than the other. Generally, the slow pointer moves forward by a factor of one, and the fast pointer moves by a factor of two in each step. However, the speed can be adjusted according to the problem statement. From c99cdd7e404ef3a30cd9aa95b19f7252695129fa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:16:21 +0530 Subject: [PATCH 0208/1894] update program links --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 10e5f5af..0d71d594 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ The key idea is that the pointers start at the same location, but they move forw ## Practice problems for fast and slow pointers -- Linked List cycle detection -- Find middle of Linked List +- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) +- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) - Pallindrome Linked List +- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) From 973479e6b5082d2b25f31db69934696e76395a06 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:22:49 +0530 Subject: [PATCH 0209/1894] update link to problem --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0d71d594..e9bc8f98 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) From a825a3ee50fdae4290979ba2d9d6eb16a8fd7d53 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:28:35 +0530 Subject: [PATCH 0210/1894] add linked list sort --- Linked List/liniked_list_sort_list.cpp | 75 ++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Linked List/liniked_list_sort_list.cpp diff --git a/Linked List/liniked_list_sort_list.cpp b/Linked List/liniked_list_sort_list.cpp new file mode 100644 index 00000000..03298627 --- /dev/null +++ b/Linked List/liniked_list_sort_list.cpp @@ -0,0 +1,75 @@ +/* + Given the head of a linked list, return the list after sorting it in ascending order. + + Input: head = [4,2,1,3] + Output: [1,2,3,4] + + Input: head = [-1,5,3,4,0] + Output: [-1,0,3,4,5] + + Input: head = [] + Output: [] + + + Constraints: + + The number of nodes in the list is in the range [0, 5 * 104]. + -105 <= Node.val <= 105 + + Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)? +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* compute_midpoint(ListNode* head){ + if(head == NULL || head->next == NULL){ + return head; + } + ListNode* slow = head; + ListNode* fast = head->next; + while(fast != NULL && fast->next != NULL){ + slow = slow->next; + fast = fast->next->next; + } + return slow; + } + ListNode* merge_two_lists(ListNode* A, ListNode* B){ + if(A == NULL) + return B; + else if(B == NULL) + return A; + ListNode* C = NULL; + if(A->val < B->val){ + C = A; + C->next = merge_two_lists(A->next, B); + } + else{ + C = B; + C->next = merge_two_lists(A, B->next); + } + return C; + } + ListNode* sortList(ListNode* head) { + if(head == NULL || head->next == NULL) + return head; + ListNode* mid = compute_midpoint(head); + ListNode* A = head; + ListNode* B = mid->next; + mid->next = NULL; + A = sortList(A); + B = sortList(B); + + ListNode* C = merge_two_lists(A, B); + return C; + } +}; \ No newline at end of file From 3cb0e065eb37d0cebf69192f7bd6283e3f6b5f4c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Feb 2023 13:31:08 +0530 Subject: [PATCH 0211/1894] update link to problem --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e9bc8f98..8bd3f3e2 100644 --- a/README.md +++ b/README.md @@ -45,3 +45,4 @@ The key idea is that the pointers start at the same location, but they move forw - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) - Pallindrome Linked List - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) +- Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) From b3803e4d10c211133b9c480f550d3c1770279086 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 19 Feb 2023 15:16:22 +0530 Subject: [PATCH 0212/1894] is prime constant time function added --- Math/is_power_of_two.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Math/is_power_of_two.js b/Math/is_power_of_two.js index 7a5a2cfd..47b63566 100644 --- a/Math/is_power_of_two.js +++ b/Math/is_power_of_two.js @@ -1,4 +1,6 @@ // Whether the provided number is power of two + +// Time complexity - O(log n) function isPowerOfTwo(inputNumber) { if (inputNumber <= 1) { return false; @@ -15,6 +17,30 @@ function isPowerOfTwo(inputNumber) { return true; } +// Time complexity - O(1) +function isPowerOfTwoConst(inputNumber) { + if (inputNumber <= 1) { + return false; + } + + return ( + parseInt(Math.ceil(Math.log(n) / Math.log(2))) == + parseInt(Math.floor(Math.log(n) / Math.log(2))) + ); +} + +// Time complexity - O(log n) +function isPowerOfTwoConst(inputNumber) { + if (inputNumber <= 1) { + return false; + } + + return ( + parseInt(Math.ceil(Math.log(n) / Math.log(2))) == + parseInt(Math.floor(Math.log(n) / Math.log(2))) + ); +} + //Driver code console.log(isPowerOfTwo(8)); console.log(isPowerOfTwo(1)); From 147e8bb5e765624c611ee4040c9445215a476850 Mon Sep 17 00:00:00 2001 From: Tarun Samanta Date: Sun, 19 Feb 2023 21:55:05 +0530 Subject: [PATCH 0213/1894] added 2P --- Two Pointers/tripletSum.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Two Pointers/tripletSum.py diff --git a/Two Pointers/tripletSum.py b/Two Pointers/tripletSum.py new file mode 100644 index 00000000..24c92796 --- /dev/null +++ b/Two Pointers/tripletSum.py @@ -0,0 +1,36 @@ +# Python3 program to find a triplet sum in array +def find3Numbers(A, arr_size, sum): + + # Sort the elements + A.sort() + + # Now fix the first element + # one by one and find the + # other two elements + for i in range(0, arr_size-2): + + # index of the first element + # in the remaining elements + l = i + 1 + + # index of the last element + r = arr_size-1 + while (l < r): + + if( A[i] + A[l] + A[r] == sum): + return True + elif (A[i] + A[l] + A[r] < sum): + l += 1 + else: # A[i] + A[l] + A[r] > sum + r -= 1 + + # If we reach here, then + # no triplet was found + return False + +# Driver program to test above function +A = [1, 2, 3, 4, 5, 6] +sum = 9 +arr_size = len(A) + +print(find3Numbers(A, arr_size, sum)) \ No newline at end of file From df8f88ffd723b49f1a7039f58548c48713cac2e0 Mon Sep 17 00:00:00 2001 From: Tarun Samanta Date: Sun, 19 Feb 2023 22:06:13 +0530 Subject: [PATCH 0214/1894] added 2P-C++ --- Two Pointers/tripletSum.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Two Pointers/tripletSum.cpp diff --git a/Two Pointers/tripletSum.cpp b/Two Pointers/tripletSum.cpp new file mode 100644 index 00000000..bad2d895 --- /dev/null +++ b/Two Pointers/tripletSum.cpp @@ -0,0 +1,35 @@ +// C++ program to find a triplet sum in array +#include +using namespace std; +bool findTriplet(int arr[], int n, int target) +{ + int l, r; + /* Sort the elements */ + sort(arr, arr + n); + /* start with the first element */ + for (int i = 0; i < n - 2; i++) { + l = i + 1; // index of the first element + r = n - 1; // last element + while (l < r) { + if (arr[i] + arr[l] + arr[r] == target) { + return true; + } + else if (arr[i] + arr[l] + arr[r] < target) + l++; + else + // A[i] + A[l] + A[r] is greater than target + r--; + } + } + // If no triplet was found + return false; +} + +int main() +{ + int arr[] = { 1, 2, 3, 4, 5, 6}; + int target = 9; + int n = sizeof(arr) / sizeof(arr[0]); + cout< Date: Sun, 19 Feb 2023 22:14:50 +0530 Subject: [PATCH 0215/1894] Commit-cpp --- Two Pointers/tripletSum | Bin 0 -> 63400 bytes Two Pointers/tripletSum.cpp | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100755 Two Pointers/tripletSum diff --git a/Two Pointers/tripletSum b/Two Pointers/tripletSum new file mode 100755 index 0000000000000000000000000000000000000000..44218ae8bd940db5fb69adcad96343bad5422991 GIT binary patch literal 63400 zcmeGFd3;pW`3H{QJ2N*k$<0RgK!60 zLe2}Nl@(X_x54ej<;p&a>gqEEV& zakbUn@y6i>i=Q^Mn%9b3Lk$(>#jQ^SMSA16H-gbh~zPmYuS zjpL+~4~6)Pf0iO)u=>f5!uZUHPd-li4x|rO&+m{v3V-p>Q%D%14b>{iKs@PekdNQL zv8|)s-yIHgh5dfbUtM40Zwht=H-@^y!LIt6#jPFf!TLZ$Yf#|^$DF>RuA{Zv+o1VR zuM3w4+nZXe8|%WQrHw6tE`PWy5DIr!H+sFRkv6R%&>d>@cXWrlf`PW`dVhV1-&h@50NvU_Uq_gtcrK{^Y>ipipGA>pb(RO1;PZ*tQ><##vL+ydq z(0M_vE!fu9u^AokLn|7szP1HI?N-J>IM^FvDR7~2lfSWLlfO9-YSoatJKWSbX%h9O zg3(45s#;#XXz{vr{%KRoH3|F6VnWlRiDgr#lgUolHV57Y{v42ZC;s?mntB)?jxn+2 zCOqM5FmX<;!Wt*$o^0V+A}bVv${5-rEA1z{zYcYBY0Is6&(KgJwQa3c-nQSi-8^K? zkDWEDeLFp!N{**DF8x+3zsHgvJHH)&Vx=laod#i%=Ri!lMT+1K#-zvEheI*xb{i~k zI3_(QQoE)diAgtO(vQZZCQ@=v>$8k2s5m7mk0Jtjoo8k0`@WDNwn03W=)+m55PDbm^!P1-~Jz4>fC8h;}${>QlZOL6h1 z@&UqiATgS5RL(Y$yr>2d(6hwkSJLkQO z6yHwcd4gF-!`Wcn*BJ)u5|1598+j4)J!(PZ|DNQZejCAr|N8ol_#S?Lf$!m?PM`j3 z-*f*BXQ6_iRe|T&p=Rl)U7q~CXx?|g4y|X>8sGML8OW*m`rZg9`*zG*ipb&L{P)C7aZ>EdA)DVp&j1WeK+`aW?e>_eLK8| zeflE;`hMr@+kbc!MsmORQzGAf2Cp67Pq**W`@A2a-1fr=9DVyPl^kEofgR~PydN<& zIi~I>c4+z|JG@5+OFuBnd#K0#0A=Z&t!U`~KQ&&Mu-*HS{*G&V+ff|^&G8;hySfJK z*zWxladg5l%lm2C)u$lo0ko|B=Fu2Nl{EQwxW?>$Vx z-tT>v^1R=Bgkrqk`w`vN{oaH0M)!MPWo*ZqgF9+o_3iW?>U)N4?Zk+s{cK;~uOUVc z&1LQT4>x{x?3iyy_FRby^M@csX!7k?bF|4fDN85`8;3nW^rJJq?}AVJdX8?t;8VS4 z&czoTJ$4MzQijSqu#3dX-~1Gn?=*6y@<$LlO%T6^4H5Tm2Mv|sG=Z9lT0?~w;6!4nSnZip$q{oQoQ*w=I9@Xcrh z{X8P2l<<+cF%(&Xd(?;Ql539lNO(R%M|_je(!)m`?CE)|XJ-~IzGYjM?jK2eN|X zgH|CBEF_SPs&`)2bqG`+_H92}x$PTKuE+IJ^$d9~ERm8sYb#X^($+tvPiRXeAMrt+ z`hI`-J`CDBnQ@){&4A7p+N?)s4Eo97uluL5XtB?vxD0Bff|K zw!o(!@I40tW9`cU#UC(Wr|(mA=df>Qrwas7V8F)xhex9cmF{CY2t!`>?b*YnkcocW zszfgiV#p4}X)4Mb^v&@eNV{~W;?hCi_I)n2eB_;O)XA|q0)2ee8k?)o*-Q6@7oix~ zxc~5JXlIAk=Y3ZacGiLpVGf#-vGf6t;_ou=MCMIrgMI1m3_1KhRn4lVli9X=kDxf} z1vx$2-_ds=LUmS#1?oKOKXK|D%TaK|d-R>0!{1QVLYVd+&R5kQWwl39?V+ASyN)*| zkYtSF??Hd80AIiwgsrH2rZxH)C-3jA4sHe4z>qxO&Ki{E*gz|+@$taip;wXS4|e@B zuK9kl_0Di83RzG?F@sWC>Why2QjuYcxog`?tVnzcnW|_-sO=)5-Xp^0!#lKDkEHF{ z*UyfSW6`XA?5icvJH3Clx^yS>4_!JRD4;=16tzR4@>D7CR4Ma=An)ymM1G_QCC098 zU9<=pV;8xcMQB-6S0m}|NEgXt)3NoWt9sx>kTsF~^O=9~Afz6`)PY_we{8#{%ul7K zw%Ek{XMnEu9~i?LMPU_3|1FDE=Sw3PaSq%&$R^`Q0)=gMwt73862l{132gkGp>cib zqCQhz-nlMDcdZ#BI*fHNe&b^;Fe-!I?>~Gd%lAEssF;Tui9U?zL0{h^zP>-vFf3!@ zj`>Fqo)AmZ+gh9-o7)b2_%oAw&sO!S5s7l4ez=9^y z1rLU7h#K2Iut}_H#ONNR8AhKj!g#UIuY=Innb5%mj~cEXmI5dCAHI&3fBOZ8wQv%8 zd{}?yN4o~GTH8O0>j$}w0fN-f=JeGJYLZd?$M9ZA#YaLV65eKl&FY;TTnMF9tJ`0WqlC`$)rN5zozS27A#tlbwmF#m9a9@ zSM%6lVndmxz(5|}zCtV#1Owi?Pv6Hh;r_#i9Pl1E3qwYf;~(|ck@PTVe$+Aw%^!>9 zp*1)Rw+A&ur*&JxM#wC+<^a6@>t&2M)#|^+a66<#AL!ZPeF8$O_ZQk(-ot5EpANkt zdixaO#D{Gv5BWq8M)b@Fu5rMzv6IOV9a)bfEvkefF)7>M zt+abb)$gl$ad{ucn3^$QoaxNeNt03G!J1P>>oxd6pbCCrM0kL*g$G2U!sAsch&kSa z7nTjEd}lIbe9enUf5Pf#Cx#4jsI}HKWQ}#{zO>7@h6b-+B>(G=PfV=IP}Tvo*JC2c@!ja)e8~vM0b9Wc=9>Pfs-6K$$^s`ILU#N95~5=lN>n7fs-6K$$^s``2P$C zblh>YA3KC?07=E3vfL@>xh9V>dGF4HKb~yz4k7Og+IIu7be2aS=A6U3+q`#s;Lpd7 z-HLGKp<~CM0IUV%0qTzcuLS%iZV>dM(MSGr>=<{%&iU)HWBbt1KEOkOF9RM$zSjZs zfd3G1Cg6Vo*8!gLIu1wyR|6gdych5&V8t8A58`hDCc40~Y=buUVH zj4_paq~6r@%N>hT5*C3Vq!WKP{vHE94N$Z3OQZOwkbK|glz$iaTYw)ETmH;wdEPzG zM}H>(M(TGK>de9RdH;75WbeDNL#; z0)JUQ{8u9QyMfPvthe;T`y=?LfIl1f>VEjj2>xB*uK@mne)w<%pA6Z59r%~};h&1& zCj*>0{pnx@@GfuzZ>{dfgg{4 zM8{`jWPF|iz7D#|BijhxacQLecY)sryxiNj<)>QJUx*^f(A^&cFIR$Xym!0Pu`o(Q z3G)0AdG74j#?6s7YJqQrop_=j{#Ow^k91AgiyQmlcSrEMfWHiQZu>?05Qw(_BjB$A z{&;;j0Q|+kx5t*Ry4tzjJlg~*GoaDes4xHq`Ne3>_e@%{XH7zFFy3i`TX<0$2thLEAG`e# zDjMk@j_##@$Sy^3<3-|6SRKQnRpM|h<-t-*;&)hh90N-nF30~XPvpDqxY|ps0j#uO ztpzt&u+xGUSun2nmyX)sAyzG3JiBoGnuebCa8F@r>C|acOQw|eNVN3Ava+cqC*xGYzYHbeYTO_Svl;y zkQJBZ4dQ>bbW@fyh<94LXn%Hmi4|W79G~Z`xGYT&-(u9jeN$&LL`mNB_oXoAZ3Z;hMr5b!+87@ zB>fE?PaI!Bx{doLAv_`LdW4fM#jD6z;pK9vntWCj_&0|X|{$m(Ud78EAV%w)U9 zMAA7c>)Qv_v9# zuAgEYlDrZrbUn!mmP%y2>qo4hN+Kn$t*pQ&k(sVh%vLRtN|zfSD<>_Jh|g6EGLlY} zj?}v98CfooRj#v`ZG}WuyIuyHl4>PV=lYw0$ZCnyyL=qZdWo!YEyqYFogtCaT#KMo zNoPuAt!q7N^Gjr%>m}9}kjQ%1o2;!-BB#5Su(qH?&T#oyTdPFQbj@dNZ4x<4I}P8` zYpFT9c~L$LuQ}b^3l2KW3M)Rtyb0;q$rD`W2q;8$@#S zKpUMPA?370wwyBxRHx?YL#bM&S*HMTc~VO0-QZ`+t4S$q{|*t>)6PoDdJT9ztug6z zP*^q}FD>g?HTMeKYCb3M zLi0}ox0^=WbP7p zxp|MI_nD6iyxKe@aHsh%fnPO~p{S0WYs^sscbhc=uQNjeziwV6@SElyfj62D2)xPs zlfauz?g2Y;ZZ!*G)f_puo6`h-$E*~1r@30-U1poW@0vRWe$V`Y!2dHJ6L`1zH-SfT z9u>O(nbQSncjWvlCjnC9$T^xbO5lHTdIf%*GgIIvIqL*|nsY5-ZjE`51)mpKZ~jZ* zT5|{tpCk7ybG*Q_%_Rc;W|IZC3*2DdX2C}U2F$-$P@ll^4Q8PQD+%-Fn$MEnym{s; z0_U3>B)!tqF+(`=7Mdvn7n$P)E;bhnTw=Iz@6r60S7lB=8pVeu1}|&j`HDJR|Ct;>dr-tPuFDxyFKFfd|ZM zE%;-B&za9z@QA?Y&9pL>f8Lx1n4NFxIcp`5tmkw~AVtr)P6EU9RQ4r1e}tY&W@qOY z>8a#$cK&ERmF&&VAFrpX;uG{#ReYkJ%HocptIdZ6)|o#QSg#~&=$Yp85)Yd132ZSv z)0jVGjsPsY9pW-23EyeeXxwBX+tzKT@dEg}LBGApRUdzJ{)-8pHXh_8&le8bK~* z$thbsAm-vfy71iq;+ZHg0)MJ|Qn$)+Sr!Z|b4&-eGLl2;7-hn^UA=X%IDH#l!)iS*W68wM>rB*g?t&+hTA&ZV3mjU=6W65o zft>m^G+D4t{}aYK|8yvRL6h!Y3Bz3oYW3A@a4o6K*@;Q4;B>u+PH7U6i-PBBE&9!< zja08>cIH&s7qy19R{g3Bg>3DQOnxdAb%k~JXtge?#1?tf#5nW-|8iFD~?hL(I4`SZB${%5x0-5Jc(jNDpI6H#aAMeJ%4 z)062z6g;WBFPMUZYb0FB%);m7MwBmjR(C%QrjoJWC5rW^%FYOOG;0Mf=+X9etArQr0-AG98e|gVr8$Ndo9}Wq8(v}_6wrDm&Y@q+ z@_t&F5$8Kn-T<99AVt@E`sdJ+{spSFC5w^qBcL|yLY*V4ibYXmMfe<*N?`66J0 z+r`zpYk}Ky9$1{R2|Z5NmYy>SHzx{=lpi9^2!OCLCFwGbS0JJBmi9ZWIZgfF>62I^n)OVL>8||p9`j^EQB;`DPIHU^_1=8SqgWeoGG+M zu9SHQ8(Lu-#%kiylrvDEnIbmvELYCPiLWG&Y(a|FawlG={l}5jh1lY6Au_QiISU4M zB0?1@yO0{9gibD5Fpa#J;sp=RxeY0X>w4r~yD;@3r7zol|QtBCtc*+5UwUi?{EIJ*Gaim->^#2lVxKjR@g+@}UPfGN|XyMD5EN zbmaD-iIogGb00=Ks~L3V9ztVl7&LO1p_+9JCgjdUvu7~q&bF0Qo0y4bAJnZdKpaCvW|>L`)SW7zlNx+iql@2M8+9Da4hY2lV}gLO`UCB z+Pe8E3s=D2O+6pPrc@;i$%O5wL#`BGLN<%YV)&0_;MBiDq>!aNHp^2eCRx_cVU}-U z+#SDjT!k#jzd(ZH6^El88=Ehnf_5ZIR#vP32>nqn;)PD>6#De-0jHtB|4To9Kz<9r5m|0?JU2)UqejMPB|Y# zlJMA#V{pOCCRKXFG1X;YPx&gw!ua#2kfj;fU(6p4`JntELQ6h_vuA*n%n} zeH!Agu9nmx{*@{a9VZDvY@o015{ChHNzR){QiOS`Pd{hBZ}=$&Yd^80(M2Mh6;>cx zsdma3=$r8we@No9ex2h`N4vt}s+0_2KKFf%I^7rp4JtuvQK1>6oGMZUy>+?W#vHKu z>;Xk~N2H1&E%_%!=t9_O>;~7_`1LIDg`%ACf8a5s??V`dS1L8_0hAKyi;iaUpCFm8 z)7-`(w7{A_8bHfn-Il>SMNdK5m4ARZ6+>GhY!|&4tdy`#istvirWm*B#%JJn0}Dsg z?6@4;%GSY!;nz5871q)771 zurjVzw{a~D5*wd!LdEj0g~@XDx{XgkWXBg3iRn}toAbJjMi`IVzNnn)R5n=dy3B3d zG#bZ0{fe9e;eHT39cHtq*kav)hJz?GFCbL8C)<3+T6b2+9x7PH-I zr|n7UL}~etPelEPGK}Y;8ZFFtW1-?@jDogKIR%>VH^b=z5kebZnCH?Vze(q%a^s#` z&HD97)PIVYR`Dv{Nf+eYg=7!6rPFlB69_N83GJko=;mvHg-w%?e~dXB;jHx-3|$|W zlnULO@l`0#%e>l%ug1gfQ$}bXpIcZ%H--spPs~tsEU!9 zt(Zc}5SxiV^S>~CTDfFeU{qsJmLqkojZr+GLH~OR56{^8`9MasYy~8Zy)@sNWw$N{ zT1(=bl=T8cUDsD9C80-EjI6n@5J%}i{fupR=$MsDrZbIeFthv?sV~_WtM#8@*aH8A ziDm2m0n%wV8X?2%oriYBpjdsU#meYL?Ru-z0J|BV03uYKZI8g<>1ECe2ot%4oy;dp zwZnPPR6Co0HPz1M>!#Y#e8W^bns1rCFjkJ7!zOn&+nYk0wVaon4p^*#boy}S zaqxt0Ia~}Jmpu;)nU?N)4}+5CaeYAGa=kDXpwRga@&dOFCdz2yVBenh8Ip|0QEk~B z>HlIFeup;gx!eT+qdnzwogwg-Thy+53Na${5;>;Y%&uUYHebRn%{T{H$`=?F$Td2> ze2Mc4@Q}ONs)#rB!AOy%6831umB>pP1~7ichC(P&QbrrXN!-&lD$$!6dFp6zFWQ-ruZ{zM3LTm;R2>06iy@jZ zOpg6VUoA4m9<>7HqTDtpUke`-r%)|htxs3T}FzH!jN^_*=gEMKa^nakQg(L7vpDEf~ojyB{ zM=+X)8kaEw-1Gp|rXrk#5moRzs1DZ7!R%S!~v!)(U8 zg_<_clXnL=WN^D`zAybAqm0t7}(#*2Rz#XU>G+PsAt&!39# z&BK7BKCSr46cut6Ka9R}SJPAcD>TJWx@K%)&5e0%Yja`xv~TI@#TYxDT`k*+*R6UA zMcSh+dmE*{t*8ARvGjCp3xAet+V^#58#1N$o&wnz?OBwnzYj6|2uWLAi-tH~M&Q&E zjATY8X*rd`nVCen(_DS1XHlA4_~hDzlto#_gUAoHJc2qFWjpUiEGrGmo%F>?>EjE5 zdK7IgPByDSx#n63VO^Y(#>SvzKLY`a@ry{vX1s#e5+lD7AnPcs`9W`~hlg;kKcEZV zX;z!RfLMAfUDrSqz3O~A&(#j{y|W}+p{tu^W=mwe>l_Gg*!qu1pop*0z$;LSy@bFk9zu1H&r$R)0! zY;>jPZvfj}4@0cItI|G3$aO(aZ*ZMXhMbw7ipZ_5=OL5c zvxJ=Qx~>Gny=NyOuXUV+^eYL7qg^CK-8_Dj731BLgB* zRi8l#Nn*N;^%!1WtIBZlkX0|oOG`|G-c_FAk%Xfv`JkPwGo*P)XaWXStEzQ~cg0g( zoyI{K10gx#JtS5+^i;-p+$)}!a=#MJ#@JQe?noo=c?2vc9y(*{rE2&AY(iC{sv*#? z28+lPaJcF>ib$RuOLBC*ttD{bRrQ(5z|(M*fgu~R*iP@BwF<IUH?&!w%@7f9rdl3HY^D%6-Vl&yNf z!9#1+!kF0*&?=wK<7-7LxvC`$WgW|Psf0(`QJms9Ij2>;2|cd*xiCEOI^?Q)T1Mw< zETHQ7J!aslJ*opd@{S#^c@U5C(-n@#;5rShmb@G^mirwUgfw_O8CR&pkPE2hG^SE|CUAyu#ovCz- zcdrhp>)IhlLELDap%U|t@GqEyX^ z=fKjG|5PrU@KQlMJ|P_|t@2#e9o{yO3|c~FHmg;K%P)*3HGvNS4#&^3eTFDz0YG@J~pfSECmCOqlihEKd z@jdY0cc+LV?_fkx7DYa`_Iefp3-Er1YLOIa8G`;xDgg(M*EUoYf=-?SKKM%YEJ7CN zb&eQ<6~0(cC7$JZ%_B;JmXU`=qVHH10gLnYM{MhY{w$S%r3;A``BAOE2@C97u4fUl zcx9wGV_LG{m+7g5EVdz1Uho%$+q9Y0ZqKJkcAbVrLUp3$9<79Fu1=DO%TMe?9K1Z&TW&^!qWFU2!3sB{p=I}pEQN{UOA}@!_7Zi!pspc`FU|87ORYsW zmtC64CU}QNp%N#;I4rwTQhAd`r6w!{-9g;km$$V*^@~OI9|B*Lid?Qc`=u2av#;L5%eOQy_!0O z1_DxLwyGl;D0R?Nyby4C8 zm}QlUh_}P2<`I77u&D_u7q1n?%_q8KP53?dTQf$D$tLFFOY{7P9CzSVvs%^g^+*j8 zifN1jns5`D^>0NV?<&PI^2bo6n$HxD_m>2xB`k)F)SRXG#Oq9oKB?GZ*46Cv4UXjP zfMgagJE>7n84}(~LWV4-j6H8a>68t{v4j^m3_(@>3gSdKWDFVAJX|d%yI|UD_B)b4 zfoQS`-kXZgnXrhIcB!g()hCWpUFu8zeGzg!<4Ar6kX7-@Rg_wlDWM7KUel(k;$+Rqh9lK5kcM!iz$_0!gs5wS5rLi zi^a1`3`?Syod2^_z{_M(ftGm3c%%lUMP4n7wy373#PufdZ9*)soJE_p@SngY)to8i zc@-_be8NJC`#QzL5Hra1A)y$NCeIR6NZ>vpkhj>PO=$@mVd!hl)5Z9HCxT;0^U&5L zOdz|r>Ebf{x_^emmBjr)NPLqhaRx;$rGkVmj^Yn=@w|9FPBkpeP^`3s4=E=utr!t5LE7D$~)>?}O-t7|_U^lBcuGc$~=L3=p zyzgh>GTw6lciV6RvXNH+73tzHD)gst@LO+&E zG)wayVYF9T#wBpIYVICRz|y>47~8g>zn@FM(!6yT+qN?srJoy4z|y>o7~8g>pUov; zY2HzcZF@)}N`E|@fTekLG1|7}&Pkr5xdg0&yVX$wtYLkc9Jp8)CziX|suCrP9}%}# z7vGs1+fke~+pVT7J*;CeMJut0v_=2l9*>V?tUrC0~cNG?szvRa5ix8D53gs?z*FGS8jh z(5kYb|73VF{7Nn6N0s>IcFZi zo>$--dH%u|uj?f7)>YocpfQipJYMff^EjVGfwXj|8x|606>lK7u?ziPy+l4A8eO=0 zx$`+l!DZ9oWB&`(t**&~)FYC?Tq`8vaGe1bu3jk-muoaJwGv5i9Ux|vL_DqvVpdBe z$+a3ou(~c|CMrvIeQyFH^@2%XeiT+`4b#nC%byv7i#`k+H@SX037OVPi7eM4jO^-l zQXhlTxD0q!gI$% zt`0!gBZb$wv(PCa`>g*$ z>>`C5)?m>XDZKGqsH-CTRTQr2#y#Km0`^$fYB~d5TE{THfylWd z*aAip733q7IhL3c5MbD>Ln zadyDxGzE};2}-Blkb?v0Q$*1myIWIT$Q6mUXz7)R$A6}&@8RKiY#8s8 zId-pezlo7WyjaC+-C>w!#OJctj@`b3@r=Lj$a)fj;@I7S?+YQ5Nvv}&PwGd_#<@q4 zq7pj-^5}bNkQzB3kDQp#BVXP{Nz{{im=zKQpr){@^Mz3sWTb9BIQ9;|U#Rc)cZwl+NYlmHQBg|CC(c^C#&DjI^|A556em1wc_DMFRsv6@xY? z{R~X9H6@)l9pgV)*Y|km$B4tg%Zf@N3!H^kHA*21oKsZXvNi?ISr+58BHn(C|59Gx za~_)MFAliz7!?Ozd5r(uUf=U;78-EXQRKpLLy>B+MdZS9!%P+30MSBS@t^YRdrrq3 z6BPvef}R@o&&I04>r!b;jnBL)TANB!YW#Pkiu%+j|96_w&dQw6m|4d~ENFAi_Ze~O zju#Or5F26W8O3N+gp(IB<9}{I-;-837)`=*+{Co(kxy8T_)vHLXsW_0R7y+*+jxrU!lWOuxM`3(;kr2dRSE+Mm`6D zN)oG#NX%yR5LvtS$eKsOQK3D!_GWa+L{ByPHP-3sSG=(S=4BAJ_a|6u16E`KN6wu$y#U` z9V!l_Ni48ZA{Z*(H;ww zlwGwWRl_TBeF(#p#CGPs3|cA{XciJGk+`DFRPs@o{U% zO$q zpBKa2lT~qLa9joM5h|_>4&udXdi&M3@ozv(`Rr6cHD72ozhQi;MO~$ZR?0ud?WBQ% z@*_E&SCZp@Fh<|=htDCf)jgvhd)nNQ!JnXLb7) zcdBaNujTE+Ld?TWpd^0s=D8OyAM4(SKb-+>)y=>@jnM1(lO^0;2wbV33N0DgI$A!G z>(g^!-_oi;(|{}7SLt_SL5Hi}6Xh=VDt=#AfSl9t7pZQC?)SHABk#$*8};C}9NzK2 zqXe&$_1{>iZdNPSAIh*?C~H$1TiIMzh$$9+$BMy`!daj` zN_$b13FiqDMp^U}4P(ph_Ec%NNh&!dLaQQ55j#3lx4F@t%C^QtvKh0AQdFj~AWR!) zks29|@utoJfUrf1L^!URoal&S_9Tv|8vMzq&NI8nNl~oMWY?#}R72V=uBob~%D5Hj z=sf63CZ)w9vqcZ%vNqU5p)Hvq0#-VU!zN6{b^ih)i_n2-Rx%odHpMgsDVdw!n6Da| z?gGv8i`-_Bt2#5v>I!R6MRh0&nEI_Migb(FOl|^UGeH=-R<626!e(WHB9@sQsYXVe zNplw2(lnRD*Ze3$Thh`^mO=w z^_J=Ja9bT#2)m-_I(6CV`dSXLtxC8=XK_O0MP%8G%GmnBkd&O$`y;N<^VKMvA!1{- zrfeGao-k^bF_BR_E23>6sZ7S>>_~k`f;9jQJ9JZVz~3JSZL_hs^%ZOV%h1_?nkYtq zyA3XVzG;H5(Y`kd!y~FufD?kIXcFmNfR5l(_GqF~p=PTKpia85Q6vK~8snCzYyrsu z3PsJIWIu)&O+VU$Pp$NDZM?>Nr%YIw7HOU#Xx0tx5Umoz~P$B9F)f9es07-v+Q}% zk--Js2*qF-Im#SgiO_|_2wfL|1dlDA%yyw=_>oCbuuW9Vnu@4|7vZ~7Tf&uny;zS9 z0CqYUixt4_I_Fp_)ujlr>kIPBW#BKREq9y?8J{H zDDqax9CnqBk^bUyBgQQf$mpw))ACcqaM%SM8dlX7=G4X|*Y{P-JQs zV#<1`Qp!B#U{{gc!b0?g$+PC{TL99i{j1GoWycjNC_ z{Jo051Y|12-%R`k@W+30-l30lq^<7+R==ImpYX+~_9#Qo@bxlZhxqycFXvn?zdk|8 za3SPO<|~7*5qKp`#LKY+FZXh$)$?^GUrl`R2V0%pe4WqNcE0-f+Qrumcsahy*UuRJ zB|{&w$=@(~fUn>2b%?LG@N)c%FMiVE$i>S!imwTb&S8kRaGWa{UB_1gUtzv3;cFLO zo?GxT`1xhxJq+ECSJK0L{T445zuHK8gRg%xivLu|$Yp3OUPdurGx17Xh?lk;FZo%& zq##55TqkKGUtht?z!yQ9aVev_82tuAEBLyL(OdCy{g9yt7~0Ped+s{G&?|iX6)%(j z_<$2~pgF%nMi@@WgYA(!%XFjQ5@Tec!vTRX44`b!-Z@`4#_e@Dna(2i;=%bYocCdu z7$Z~}mqW1jI>h-mQ#TgwHA;VHc*BNos?_V^C!dK9d!dwLWP8pqGS?Z2ml&y@(+wkR znCo{NiMx&L^+wJ*V}vKe7`e{K0~j~e7{AUaLMUabk+6vKQ^nJ!!h(_AD@RzHOvlV&p$)jP!(%xg<8Tz4hR{R5JG(t`cL|X2avz$k5o+ zjeLYm{AD|PFjSWqhBKvE@l}yz?~FJfOVy1GwB|-rE#T5dG_}ddof1!;y>a9GHwxr? zwi>yTbz>}5_EwVf9pssTN*C=lraWN`zr+~z17p1BP1O0VSR(AbG3Sk`I(XuK%NTXg zaPKuzOAME%*)Vadcdy}DZ)AGDWenMCjJ?emz1DDZtel(o8neiHjQj)WTw0+cC(3Vo z$Itm=&@oDNZY**;OAL;eQ&r-8(3q~OFuv_@MN8Yem(I77@e>!GUevIW>`5**9H1)m zR7HZP%c$sI+>pVxw^p6sc5)oIa6mHGLwwJbao8kHp^8L@y}9e0#CGNxL-!g*>tgw1 zZ$dktf%**b{1DYO8>!2MIa#No+sU4(My9g|S^-uQWNconL0WtFwOEYAFGs)7~1mS?a zyYGApWG{Qjs9B~uEJ#=hk(GW1^AZOqy#LrzmMs)!D~b&QEpSbGK3Ou92~qBMON$ zE;I5UFoqTz`F{n2&rn3DZrTTF&TqgLn$8iB?}!e&g%S4oob!h+-AH}N$m+)?`;gFi z6WBD;b1Rs%EXR?EUW)A4XOqrD;BgLwCx0*OpW?G3+dhVM{t0B?V&uMM4A~AA8sknk zGA=PPHyi28jMR&b{4jn6h=#`HS!X0HH%6{E(vdxNnKArz%FP((Rxs}pqu>c6!`Rz&gU5&%K)gfXs#)sF0mExp|E{DNbb^m8NkL3ID;ia|D+ z?ln@@%X>TD_Mj?$+K1cD2OQwm&*QjdpRhZR8M-me(__?nEOVzyXB1-M#N&L1r9U*X zEnX{9> zQKHy1j=*yZ-p+(&c)P-QC9E?>C0uD_?lp!iGYVffj8m04RYcntH=OUGQ)8ehVel{{ zV=OXYUl?&dYRN!eR0bS|0~W@<#p3(}Y8d5AL=9OO>Fq{k4@do!ON=5+cbEus-T*_5 zoLdY>kJR71F&J*t{HNE2OUwNJwoo|OPr0H`ci*=iNCH)D#A}I2U>fA znn09n>-4iZtu5Hr(Y4jz(ba^u1C8hQgt~%STSHfCuw83x>FQ|j@V7E!ptT!i&q1+< zo@ReIuo1DC_UGb<%jawUI)AXMtD_5;*498cs5N(V30YD@7zn#yd$_Bk)xQPJqBkpM z`TZN)d;E>Pz0>{vj?V5<0FWCc)4Kv4LTWWR)EeyW7UI2H51REi2fD)*<=~RvFY(qO z5@s@9z0%(u0DFS%P1=^m?r=v>TcB49bT@`WZ9%QImESF*`MQqQZf^sM2b#|5=??o_ zf`LwUXyW9;){gd#g$PbouLzy9XA7YK{Yje7b{e}o+qKq?#z1SZv7;SL)S%|3u3$4m z7|AG~x;q1nL2V0r5!SlHUEz*aG6eEa;`euUbP6euhQT=0zhSR;GbE;*|F6cVTa~p+ z_rfzn9o-^W<<;$>@Zxgs>Qli_bhtg(8`f~iEzsH;Z1wlFbXvbC*ipM#>+I@i z3v~xkdsi^fv=wp_4s|z&f=yaSC!`;;JAQ&C6X@T3(a6pY>V&)-TLPhW=^`XwYlH}P zK@&*8si0s6iUc=;%aG`H@-bZ9Kt1&~Zf@{GKEN%iOix=oWHut=&;SjUhr%I_u?G_bG&=+>#|UG*zT60l zWU_0hZF8V21SwWy9A{lhL06~kF?xqV|R1dUd%yuY}8SxZMl=dbRr z3$=B!MlmQ~imhm0v2}A0V$nri1X*P>V)-TdplnBIb4U0DX|#WeG!(0C219BQ=1b}ntg>^9wmQiDd{! zY}!1Ij54y_mXW2a0plxg)P@YvNwu^Bc2_cVYnG;H5#eKln!mX#7{rLfX@D-bYKLX&FZ(ArlxkuXS@TDGBBpV^HbcA!Ivc1w4By1^J-TTYkl4@@Y7K|l zp)rajGPyODRshw}+-$imUs4eVahPC8gvU|eh`i|DiixuorkvBb&7CLPUNo9>Xf79TPd3$@K zUfr}ZA=-9?PJA}PwAS88x1}x&H?+E`o(&CVY|CbRj`u_J6lWeFMon4zl7HTMN*FFEI1y$5FhZ>rrCC3VH=|UUPr?@u=JpoK0e$9c<5iEIXXFEEWx@l zh}|gNseDzq!&-AE^|>1Z(HsuK#KX^|rz_(;KrSL)Pg?`mS?$4%@HV4P9>%S!L&T!B zqhsJohNgSbW!p*wM%vYaGX{(cUztc)hkhu_f#&Z~L791E`2 z>PCn{oR^AG50_5sH)mDXbCv3?tH4xV@&Ybi_u=YD$(3Twl?{S&S*7UfbMl zyLaeve;0dhLq|ue^3>+rQ*VTJHAjAKnc1^pyn3+urdw?H`SZ&)W0f47->;yWrlBm& zm=>{qn)`*LH&&<>ubifXB6S=kE}b4H>zFbJDsI1ZdSsuV)N*9O0xWa+h9?|rjIEV; zIlZdrk{gSq<1EDoF@MO+S*Qt1uNKUH*x%5aw}hG?BUt1&b}%q#i=4exlNf=;Wyfui zGp?-j?QMq!7~&w^Evy4HE}>y?!9NkG#@;}T9Z>$gT@G{g#^@NwF7(Ki zmSA*r>in3*+Cq(5Q%4W9SlZaw8fs{y!yD|{9K^}CEj4rJD$j;968uY9t5vTKc~`-2G7d1IJ(2f*NR^ z^3UVkPHl6uZIC0Ift(iFwQx(QTl{)OeouQ(cd)698xUA>Yc%cMozPmuxjvW8&W&x@ zwrJLxd%`_k(VZE1tzDrY^b2Ib=YTgQdrHc@+6(t^M`v|=6BZW1bHy(geaG?#o#On0 z)doE_e{*X`0DG@9m6A>C=N1gg!U0>5(QP;3WHUsXoUB8uFkYc1Kel_Y;{x9Z-IT4W zK~=4^49*V?i*x{57Xo!^vBAw65gKed!I-H{Crsl()j^B|b{F7__#3cmCHsl~df63X z|L9IpX^+1PRT9~SBBS88h$Z7<9h*SheeTrSv1YXq6hj$7S#H?7D3K{7>V+a72xtm~ z1D2b`jRV`@s=X#z?O`sb>(CnPEmW42_8X2?#O_6w9~h9c~bRH_o}Tq@IR58nlfOFSlRowk_o58TbFy*v%NQzT|ZG1*X@F_LM8>Z{{v9 z_7q#GyyGn)oDdbFAQrdWvE+=}*wGUf!NGo;SSRijQvhSvZ<_dL%0$FZy3{auUP=W; zeblar24|N&;yT631GQ3Ksy)3I($gHAIk-NQv2>0T{>Tlo53G@qXfIEoKX6Ucf?sNJKm`h zn9>Csy2X!a4}ZY`wx!wwI9q{b#eAqWbYn{5mNmQ=d*@!QKX5G5gv4(2xQ(9Rh0!${ zObrT%iIyS6`2$%2u5~taA%9d{o0P*Bt6u$P!Q;=h{hV6(c;E>Bm1;oigbN|-L`t(( zmK@*Dx1z0d3@D6TT)|k$)BrVW7RL!DU{ia?mUcfqIx0e(XHgO8=Dq?PvNjxjV2n6L z#fWgsrm%J{TL6jH)}6I;=U**5(F-I?x>X(^YiVh}rpTBo< z90!oboqM6M$?dX^16QLvK#@g9za>CpE4T?$+fc90w&WP3!P-|R(|88cZu<$A1&X!P z5kVe&(KA@*N(buHz}=wF6$u{iP$cZxO{PX`iW3Ql+biO}Iph#_4C@v+4cOL=%)*Gl zf5h-&F$F#7!2u@XCH?0BSm8h~-J-$7YlgKxr}c*oYGbZ}jE{G3g!7o(g!goCFl?fP zocN*Z8`b%$Xuiy{P;MAf>^<~%NHB$H*y-39Zc&r5obSN5Q*!ymvjQCQCGDDwtTNxQ zkF*JBQ}%!4gu&i^wH#COu%}y{F;7=8`2y=%=nA)#9+p@XuqEO@TH zB%=4pg=&m{h7W3K_29nBVTV0GjK`!U{=03&2Qog+H3#2AFd*KB)v`OHnAS|z4!Xyo z_8n9%P9Zo*FNH<-)82~-q1VQhvdm%;({{W=Y|MlH)eEVDF*?<#o!irKJTubIoLb9% zIpDxzNG+GS6t`B)pabJ3t0tH^IvqW5Ub&XSsLDnU<_|g9;&4>0SW~!o(xlQEg{7ra zr%f#>oYEHVX%EiZ7;F!Ag&Gm%3^T8HX2q0>^1>+_3#Z^dz}9wkccG_yN>4kE*PEt< z16ZVY0|^0W+%yHpynF4j<&Z&)P#94KVjfRo|(byal7ZwW9yx3q(FyJmX3T%6f zO(}I?EpsZC?osbAvKWL#i`n_M>|VV3d3g&&&h+u7`oSdQxR5Pj{e@+Vy=;5v&Y2J0HUAnriqs~uX%bG$qTNL+m>v&k*!^vFDd|%+X ziDx}vlLbZ%9LE2+3(|>Ypje3>>4G|U!h%sT3mD#;fboNE>Ev+1*o6ZjUOZXR1B2yn z-3XJz(UkcS!eL+R;3jGy?8oI5Oqs!67#lPg?r74mr~;=flffkHU~qq?2mfBDEU0;R zgo+Wn`cj2SqP_N(g*)bP@dSCb0XunEY^m!F>I@dmXbqtz+@2BJ%(EuwPwY9zAXC0F zi8RUNi*+qRtoIl28XL$f)&99<&rWD^KhDlwc(Wfz!gAjNzt|UU>x2h~F$cYv7}2ko zy=X{n>xqbMneo5{~j8xSpSr=0V&gv!cms9H|s>Lf0^l;f3p|>+t=ns z{>HA3o=%)aW9+Ss0gSNR6QRizKMsP3B_5o$S@3EpkfG-4b=_TcVK9c1arH6@a&xR& zO=2PJF7#kAi|x)$L2l%6MOlheIp>huA2NHRvTEowu%$C?ta1R^j-b5W>DWQ&33@kM zyMe1|3cNG|6kTh9LkkK;5c4_cjAi?ks~fSEr__(4jbTPaCQqK2z(nzfuVmDx39a^( zG7LE+%?s-TTV&lOvpsOjwc*~K?d6EO$z~em><~SmL^X%7OCy_@4I;1>hq;`NxpPJ7 zIw7kF@d7<+h0g^(M;|Un#1oX!V=t;#pNO=6@iy#qay@F7wuG>uZ5t=}3+HvT!%9*J zMf_myX7lc-kM zV3^FCP2C-SbucOtc)Vq3>G77KGTxjYAlVVS6?@C&1ZUfb*}`!iH~QfiLU7wVFt)h9 zqfQI0-3?d(YngW<5*Al67+Kw2!|NMhGjx!AW=lA)595~(Pl(Gn-iT~M%gUjXa~m~5 z?4az?olr$`NR6C>u7U=fFb!M;kqsi%5ZU9@GH@+*{MF%B>=>LF2OwwGB-sD3TEo6E z?{~tf4{-Ym7fSI~>MBC6F2Sj71~3ecROAX3*EGRitR2-gJr<1Lm_P}|Tw7gKMY7Xr z9RbIBQ76`ySr|-pN0ehp8OEKJ=>9L{*SZkQi)YH8!L~9z9rmm_0Eb3x7+Ci<)m$Pz zj=ghBC+Tu^YRt(%)$aa}~Zz$?l!mBbzIe<@{D z?yt4u+U$TgE;zb*d7EA3VAI}F4=Gu)<1?#BWz`Bovk<@(#gn-U)dQ>wK1|w#7II`OGjZXuT+xi|FK*#&P;esq^_rJYGY@oR@~Fw zRUB$>Z0%_Z7B^0sR9sqG+`ucdgCP2+VWH)(D4&9Tww~T8*drTQ>n4sp+M&x3v zk%^N{OTDB=IK_IfZssNJMtVSSxNs2Agbi7N=z+jchX8Pn5I16h7Ax7P&a(kX0B&x^ z+>~bBawa9ywX_s&f*`Ul;&LL1Ctk!5YK=fDt~U0_x<8h9Z_f}&2#HVh9p znIa<%2>WHR>+Yn}V0Mw@l42U>P5#fkL5kULwEmt7yu8JanxC}gkGV*|tOTe6=l>Sie z{F_6;E!M`8c0Ip7#&^(sjF<3(G<;mz3Rhjd=C;2|-RE-KU&Wek`y<#ixBc0x>9#*{ z9pkpY0WEghAA0)T_E(&j>2CXb%oex(p=Gt({+#jxxBa2yOS;?swsDc${!Ve5+y3OR z+HHSQIL>WTdf}wux^0 zleG-D{drou+x`-5oZJ55>|Uqa{TdhH zr&725h0{2<{Uy_8H4w*nW6Ur{|2P(pPDFwZ%+>ffnops;@$9@wES0i25hHAB|5RkBfYb2bb_137k{r(C9tp8A4Jy%NpY^^0O z|6NEQjQ*cV{tV4if`Eh-d{M#~T4G%K2UdDgTzU=|s^fQZ&A9XmNgt}&KOjxM^YL2w zldb&tid-K46glfjk4wMKO3#W*=RdB@{CRQduUY8@aq0471;}3*mtKsI*ICc#|EIaD z3yrIY!q-A;#Ue=&TBAbHpn=*;le9IWXnva7z@`oT!CI7U+HAA2O`0aDSPPN|5kbK| z_=6x+p`cjMioO(u_QhHRMJ$LQzA3)=P<<#u)%txi-*5c?nu0G155th~ zPjM(nGfxSR;^7B-8c{Ea?hE41O#x>ucOTg>h*X11iW*o}0 zatTgeK@wTl2%Py0PYMbw0cZWj{pE=Gu~WQ?gt0siH}EC=K%&_s1v1 zAD2TJxW#F4kiM*V!b6J!-^=0uO#I=2PyBxf4^MT%`*5xl^BJC*gdYRmEPs}~CjRi; zrNEDX*USGG;tvmR;$MMdn3!&OcohC5@Mih5cFVAs9Kl-!H=~Tv+-BTu)Ehnwg$rJB4;6>8BW|iV zbo3c5?oXG7({+fe4hIc)M_~XoIdlvQbYPV#KlFj1;>hRO;8Y+C-!Wb2#8RquEM`?}g?4Cj@ir5$x4BrU z0g9Fn3)pL%-4LJ8*Csx`MCEg}doFMJmd~a{WzUz-r$lK*b#PWL6k%z6RxW3emCv=_ z-vG9k&BCax!4`AmU&=#V&g?Zm(G4L{zo#vqbE9g(8>B+7mCtHP)0{wDXf%G6xq$t; zwHCnSTF(t%b2ILNUSwMc|fA+p%;1@vYqh{kw?w$gbiSsf8Vjs!V(&QQo7E4^{bp7l4cR;vJWB*5GEVKY_5u`|ac6W1& zrPV~$%w`$ao4+}xN{3Ky>n*H=hWv&LERA_wHgxy58MF{vv&qzOjxOTx3#SV}HooFcdL=Ds1-fod2R}26!XSgha>JXtfby|?gfNMJ3hfrN7%x#WYeZD<|_RX*ZX6MV=`JmQfaBjvd zZezzB=9jko&6oS8U=pDmqS~vinR{W)TvHBtI&G-SsWl7D)pzQ8Hwz8#98QID&3w_$ ze5m(;G>f@zv47_P9tG|F3LS)RS37CikKh7J43(D-(=C zm0q*JjYzP|qZOT>B=8)`Th6)R+M48G$QRG5<0{wU!+i?KHv!|+)Q#6Eyy*z6uAPTA4=JWU zT=I1r+=tx*by_OJfSs?~VQ*iRd z3%I{@XGvMmzI~IWr!9p0ZOo4nG%sPajc`4QGk>twFqK{Yn75zHxLgXu^1pMd-Fi8` zw;+0la3fkav&-ae_^?D8qW3VkKaw|nnbBrr z6t#77gCB$E%C&2U?f%aweWR^n#Im$=asG#ZV(Bm3|M!wNT2_Ja9_clC9Cq#8DE=v8 z>33m0p3dn0sKBGk{8c1xdOD-j!)9Ha{tuD-`8LmO^i}mI zi^JNFUH=RZmV8|wBxd^RGCqz;7nhgG8~qJD_}){HH~lz2%SmT^{;G0q_+JQM+tsiU z^pP`?w~nQ572>meorWxnD9B51Ir9iWxEc3f`LlG5^7#9#e9&ujc^ON`VlX+oUIAfZ zmVVH$ba{@|j6CDIGJbj+mHxU2Z|L&Cnh3Y(j5bL=VoM&B{6uJ&p2OsfpZcB{W7ug8 zNVju>$+(zzLyr7~m%LEvri?JWv3zfi{2G1$3vL(ZCl``9tzZjAbm$r*i0@}9f$-|?;YziEsLiY{GwL{;QCzq#ZE&a3=daM_BVwLhCb k7;J6NOZfj2KYH54&Y5v>`WznX$-n=r7kV}lh%S?V0Qi@5hyVZp literal 0 HcmV?d00001 diff --git a/Two Pointers/tripletSum.cpp b/Two Pointers/tripletSum.cpp index bad2d895..221ba382 100644 --- a/Two Pointers/tripletSum.cpp +++ b/Two Pointers/tripletSum.cpp @@ -1,7 +1,7 @@ // C++ program to find a triplet sum in array #include using namespace std; -bool findTriplet(int arr[], int n, int target) +string findTriplet(int arr[], int n, int target) { int l, r; /* Sort the elements */ @@ -12,7 +12,7 @@ bool findTriplet(int arr[], int n, int target) r = n - 1; // last element while (l < r) { if (arr[i] + arr[l] + arr[r] == target) { - return true; + return "TRUE"; } else if (arr[i] + arr[l] + arr[r] < target) l++; @@ -22,7 +22,7 @@ bool findTriplet(int arr[], int n, int target) } } // If no triplet was found - return false; + return "FALSE"; } int main() From 0f921a15093373f204ce661b6710b5df46661603 Mon Sep 17 00:00:00 2001 From: Tarun Samanta Date: Sun, 19 Feb 2023 22:21:50 +0530 Subject: [PATCH 0216/1894] added 2p-Java --- Two Pointers/tripleSum.java | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Two Pointers/tripleSum.java diff --git a/Two Pointers/tripleSum.java b/Two Pointers/tripleSum.java new file mode 100644 index 00000000..2b41074f --- /dev/null +++ b/Two Pointers/tripleSum.java @@ -0,0 +1,45 @@ +import java.util.*; +// Java program to find a triplet sum in array +class FindTriplet { + boolean findTriplet(int arr[], int n, int sum) + { + int l, r; + + /* Sort the elements */ + Arrays.sort(arr); + + /* Now fix the first element one by one and find the + other two elements */ + for (int i = 0; i < n - 2; i++) { + + l = i + 1; // index of the first element + r = n - 1; // index of the last element + while (l < r) { + if (arr[i] + arr[l] + arr[r] == sum) { + return true; + } + else if (arr[i] + arr[l] + arr[r] < sum) + l++; + + else + // arr[i] + arr[l] + arr[r] is greater than sum + r--; + } + } + + // If no triplet was found + return false; + } + + public static void main(String[] args) + { + + FindTriplet triplet = new FindTriplet(); + int[] arr = { 1, 2, 3, 4, 5, 6 }; + int sum = 9; + int n = arr.length; + + System.out.println(triplet.findTriplet(arr, n, sum)); + } +} + From de210f62d3c25e292d414a8b6188d6d461c9fdfa Mon Sep 17 00:00:00 2001 From: Munyao Kelvin Date: Mon, 20 Feb 2023 15:47:20 +0300 Subject: [PATCH 0217/1894] create an array arguement --- sorting/tim_sort.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorting/tim_sort.py b/sorting/tim_sort.py index ba524c43..84574ed6 100644 --- a/sorting/tim_sort.py +++ b/sorting/tim_sort.py @@ -59,24 +59,24 @@ def merge(array, l, m, r): # merge the two arrays in a larger sub array while i < array_len1 and j < array_len2: if left[i] <= right[j]: - arr[k] = left[i] + array[k] = left[i] i += 1 else: - arr[k] = right[j] + array[k] = right[j] j += 1 k += 1 # Copy remaining elements of the left part, if any while i < array_len1: - arr[k] = left[i] + array[k] = left[i] k += 1 i += 1 # Copy remaining element of the right part, if any while j Date: Mon, 20 Feb 2023 22:24:09 +0530 Subject: [PATCH 0218/1894] rename files --- Two Pointers/tripletSum | Bin 63400 -> 0 bytes .../{tripletSum.cpp => triplet_sum.cpp} | 0 .../{tripleSum.java => triplet_sum.java} | 0 Two Pointers/{tripletSum.py => triplet_sum.py} | 0 4 files changed, 0 insertions(+), 0 deletions(-) delete mode 100755 Two Pointers/tripletSum rename Two Pointers/{tripletSum.cpp => triplet_sum.cpp} (100%) rename Two Pointers/{tripleSum.java => triplet_sum.java} (100%) rename Two Pointers/{tripletSum.py => triplet_sum.py} (100%) diff --git a/Two Pointers/tripletSum b/Two Pointers/tripletSum deleted file mode 100755 index 44218ae8bd940db5fb69adcad96343bad5422991..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 63400 zcmeGFd3;pW`3H{QJ2N*k$<0RgK!60 zLe2}Nl@(X_x54ej<;p&a>gqEEV& zakbUn@y6i>i=Q^Mn%9b3Lk$(>#jQ^SMSA16H-gbh~zPmYuS zjpL+~4~6)Pf0iO)u=>f5!uZUHPd-li4x|rO&+m{v3V-p>Q%D%14b>{iKs@PekdNQL zv8|)s-yIHgh5dfbUtM40Zwht=H-@^y!LIt6#jPFf!TLZ$Yf#|^$DF>RuA{Zv+o1VR zuM3w4+nZXe8|%WQrHw6tE`PWy5DIr!H+sFRkv6R%&>d>@cXWrlf`PW`dVhV1-&h@50NvU_Uq_gtcrK{^Y>ipipGA>pb(RO1;PZ*tQ><##vL+ydq z(0M_vE!fu9u^AokLn|7szP1HI?N-J>IM^FvDR7~2lfSWLlfO9-YSoatJKWSbX%h9O zg3(45s#;#XXz{vr{%KRoH3|F6VnWlRiDgr#lgUolHV57Y{v42ZC;s?mntB)?jxn+2 zCOqM5FmX<;!Wt*$o^0V+A}bVv${5-rEA1z{zYcYBY0Is6&(KgJwQa3c-nQSi-8^K? zkDWEDeLFp!N{**DF8x+3zsHgvJHH)&Vx=laod#i%=Ri!lMT+1K#-zvEheI*xb{i~k zI3_(QQoE)diAgtO(vQZZCQ@=v>$8k2s5m7mk0Jtjoo8k0`@WDNwn03W=)+m55PDbm^!P1-~Jz4>fC8h;}${>QlZOL6h1 z@&UqiATgS5RL(Y$yr>2d(6hwkSJLkQO z6yHwcd4gF-!`Wcn*BJ)u5|1598+j4)J!(PZ|DNQZejCAr|N8ol_#S?Lf$!m?PM`j3 z-*f*BXQ6_iRe|T&p=Rl)U7q~CXx?|g4y|X>8sGML8OW*m`rZg9`*zG*ipb&L{P)C7aZ>EdA)DVp&j1WeK+`aW?e>_eLK8| zeflE;`hMr@+kbc!MsmORQzGAf2Cp67Pq**W`@A2a-1fr=9DVyPl^kEofgR~PydN<& zIi~I>c4+z|JG@5+OFuBnd#K0#0A=Z&t!U`~KQ&&Mu-*HS{*G&V+ff|^&G8;hySfJK z*zWxladg5l%lm2C)u$lo0ko|B=Fu2Nl{EQwxW?>$Vx z-tT>v^1R=Bgkrqk`w`vN{oaH0M)!MPWo*ZqgF9+o_3iW?>U)N4?Zk+s{cK;~uOUVc z&1LQT4>x{x?3iyy_FRby^M@csX!7k?bF|4fDN85`8;3nW^rJJq?}AVJdX8?t;8VS4 z&czoTJ$4MzQijSqu#3dX-~1Gn?=*6y@<$LlO%T6^4H5Tm2Mv|sG=Z9lT0?~w;6!4nSnZip$q{oQoQ*w=I9@Xcrh z{X8P2l<<+cF%(&Xd(?;Ql539lNO(R%M|_je(!)m`?CE)|XJ-~IzGYjM?jK2eN|X zgH|CBEF_SPs&`)2bqG`+_H92}x$PTKuE+IJ^$d9~ERm8sYb#X^($+tvPiRXeAMrt+ z`hI`-J`CDBnQ@){&4A7p+N?)s4Eo97uluL5XtB?vxD0Bff|K zw!o(!@I40tW9`cU#UC(Wr|(mA=df>Qrwas7V8F)xhex9cmF{CY2t!`>?b*YnkcocW zszfgiV#p4}X)4Mb^v&@eNV{~W;?hCi_I)n2eB_;O)XA|q0)2ee8k?)o*-Q6@7oix~ zxc~5JXlIAk=Y3ZacGiLpVGf#-vGf6t;_ou=MCMIrgMI1m3_1KhRn4lVli9X=kDxf} z1vx$2-_ds=LUmS#1?oKOKXK|D%TaK|d-R>0!{1QVLYVd+&R5kQWwl39?V+ASyN)*| zkYtSF??Hd80AIiwgsrH2rZxH)C-3jA4sHe4z>qxO&Ki{E*gz|+@$taip;wXS4|e@B zuK9kl_0Di83RzG?F@sWC>Why2QjuYcxog`?tVnzcnW|_-sO=)5-Xp^0!#lKDkEHF{ z*UyfSW6`XA?5icvJH3Clx^yS>4_!JRD4;=16tzR4@>D7CR4Ma=An)ymM1G_QCC098 zU9<=pV;8xcMQB-6S0m}|NEgXt)3NoWt9sx>kTsF~^O=9~Afz6`)PY_we{8#{%ul7K zw%Ek{XMnEu9~i?LMPU_3|1FDE=Sw3PaSq%&$R^`Q0)=gMwt73862l{132gkGp>cib zqCQhz-nlMDcdZ#BI*fHNe&b^;Fe-!I?>~Gd%lAEssF;Tui9U?zL0{h^zP>-vFf3!@ zj`>Fqo)AmZ+gh9-o7)b2_%oAw&sO!S5s7l4ez=9^y z1rLU7h#K2Iut}_H#ONNR8AhKj!g#UIuY=Innb5%mj~cEXmI5dCAHI&3fBOZ8wQv%8 zd{}?yN4o~GTH8O0>j$}w0fN-f=JeGJYLZd?$M9ZA#YaLV65eKl&FY;TTnMF9tJ`0WqlC`$)rN5zozS27A#tlbwmF#m9a9@ zSM%6lVndmxz(5|}zCtV#1Owi?Pv6Hh;r_#i9Pl1E3qwYf;~(|ck@PTVe$+Aw%^!>9 zp*1)Rw+A&ur*&JxM#wC+<^a6@>t&2M)#|^+a66<#AL!ZPeF8$O_ZQk(-ot5EpANkt zdixaO#D{Gv5BWq8M)b@Fu5rMzv6IOV9a)bfEvkefF)7>M zt+abb)$gl$ad{ucn3^$QoaxNeNt03G!J1P>>oxd6pbCCrM0kL*g$G2U!sAsch&kSa z7nTjEd}lIbe9enUf5Pf#Cx#4jsI}HKWQ}#{zO>7@h6b-+B>(G=PfV=IP}Tvo*JC2c@!ja)e8~vM0b9Wc=9>Pfs-6K$$^s`ILU#N95~5=lN>n7fs-6K$$^s``2P$C zblh>YA3KC?07=E3vfL@>xh9V>dGF4HKb~yz4k7Og+IIu7be2aS=A6U3+q`#s;Lpd7 z-HLGKp<~CM0IUV%0qTzcuLS%iZV>dM(MSGr>=<{%&iU)HWBbt1KEOkOF9RM$zSjZs zfd3G1Cg6Vo*8!gLIu1wyR|6gdych5&V8t8A58`hDCc40~Y=buUVH zj4_paq~6r@%N>hT5*C3Vq!WKP{vHE94N$Z3OQZOwkbK|glz$iaTYw)ETmH;wdEPzG zM}H>(M(TGK>de9RdH;75WbeDNL#; z0)JUQ{8u9QyMfPvthe;T`y=?LfIl1f>VEjj2>xB*uK@mne)w<%pA6Z59r%~};h&1& zCj*>0{pnx@@GfuzZ>{dfgg{4 zM8{`jWPF|iz7D#|BijhxacQLecY)sryxiNj<)>QJUx*^f(A^&cFIR$Xym!0Pu`o(Q z3G)0AdG74j#?6s7YJqQrop_=j{#Ow^k91AgiyQmlcSrEMfWHiQZu>?05Qw(_BjB$A z{&;;j0Q|+kx5t*Ry4tzjJlg~*GoaDes4xHq`Ne3>_e@%{XH7zFFy3i`TX<0$2thLEAG`e# zDjMk@j_##@$Sy^3<3-|6SRKQnRpM|h<-t-*;&)hh90N-nF30~XPvpDqxY|ps0j#uO ztpzt&u+xGUSun2nmyX)sAyzG3JiBoGnuebCa8F@r>C|acOQw|eNVN3Ava+cqC*xGYzYHbeYTO_Svl;y zkQJBZ4dQ>bbW@fyh<94LXn%Hmi4|W79G~Z`xGYT&-(u9jeN$&LL`mNB_oXoAZ3Z;hMr5b!+87@ zB>fE?PaI!Bx{doLAv_`LdW4fM#jD6z;pK9vntWCj_&0|X|{$m(Ud78EAV%w)U9 zMAA7c>)Qv_v9# zuAgEYlDrZrbUn!mmP%y2>qo4hN+Kn$t*pQ&k(sVh%vLRtN|zfSD<>_Jh|g6EGLlY} zj?}v98CfooRj#v`ZG}WuyIuyHl4>PV=lYw0$ZCnyyL=qZdWo!YEyqYFogtCaT#KMo zNoPuAt!q7N^Gjr%>m}9}kjQ%1o2;!-BB#5Su(qH?&T#oyTdPFQbj@dNZ4x<4I}P8` zYpFT9c~L$LuQ}b^3l2KW3M)Rtyb0;q$rD`W2q;8$@#S zKpUMPA?370wwyBxRHx?YL#bM&S*HMTc~VO0-QZ`+t4S$q{|*t>)6PoDdJT9ztug6z zP*^q}FD>g?HTMeKYCb3M zLi0}ox0^=WbP7p zxp|MI_nD6iyxKe@aHsh%fnPO~p{S0WYs^sscbhc=uQNjeziwV6@SElyfj62D2)xPs zlfauz?g2Y;ZZ!*G)f_puo6`h-$E*~1r@30-U1poW@0vRWe$V`Y!2dHJ6L`1zH-SfT z9u>O(nbQSncjWvlCjnC9$T^xbO5lHTdIf%*GgIIvIqL*|nsY5-ZjE`51)mpKZ~jZ* zT5|{tpCk7ybG*Q_%_Rc;W|IZC3*2DdX2C}U2F$-$P@ll^4Q8PQD+%-Fn$MEnym{s; z0_U3>B)!tqF+(`=7Mdvn7n$P)E;bhnTw=Iz@6r60S7lB=8pVeu1}|&j`HDJR|Ct;>dr-tPuFDxyFKFfd|ZM zE%;-B&za9z@QA?Y&9pL>f8Lx1n4NFxIcp`5tmkw~AVtr)P6EU9RQ4r1e}tY&W@qOY z>8a#$cK&ERmF&&VAFrpX;uG{#ReYkJ%HocptIdZ6)|o#QSg#~&=$Yp85)Yd132ZSv z)0jVGjsPsY9pW-23EyeeXxwBX+tzKT@dEg}LBGApRUdzJ{)-8pHXh_8&le8bK~* z$thbsAm-vfy71iq;+ZHg0)MJ|Qn$)+Sr!Z|b4&-eGLl2;7-hn^UA=X%IDH#l!)iS*W68wM>rB*g?t&+hTA&ZV3mjU=6W65o zft>m^G+D4t{}aYK|8yvRL6h!Y3Bz3oYW3A@a4o6K*@;Q4;B>u+PH7U6i-PBBE&9!< zja08>cIH&s7qy19R{g3Bg>3DQOnxdAb%k~JXtge?#1?tf#5nW-|8iFD~?hL(I4`SZB${%5x0-5Jc(jNDpI6H#aAMeJ%4 z)062z6g;WBFPMUZYb0FB%);m7MwBmjR(C%QrjoJWC5rW^%FYOOG;0Mf=+X9etArQr0-AG98e|gVr8$Ndo9}Wq8(v}_6wrDm&Y@q+ z@_t&F5$8Kn-T<99AVt@E`sdJ+{spSFC5w^qBcL|yLY*V4ibYXmMfe<*N?`66J0 z+r`zpYk}Ky9$1{R2|Z5NmYy>SHzx{=lpi9^2!OCLCFwGbS0JJBmi9ZWIZgfF>62I^n)OVL>8||p9`j^EQB;`DPIHU^_1=8SqgWeoGG+M zu9SHQ8(Lu-#%kiylrvDEnIbmvELYCPiLWG&Y(a|FawlG={l}5jh1lY6Au_QiISU4M zB0?1@yO0{9gibD5Fpa#J;sp=RxeY0X>w4r~yD;@3r7zol|QtBCtc*+5UwUi?{EIJ*Gaim->^#2lVxKjR@g+@}UPfGN|XyMD5EN zbmaD-iIogGb00=Ks~L3V9ztVl7&LO1p_+9JCgjdUvu7~q&bF0Qo0y4bAJnZdKpaCvW|>L`)SW7zlNx+iql@2M8+9Da4hY2lV}gLO`UCB z+Pe8E3s=D2O+6pPrc@;i$%O5wL#`BGLN<%YV)&0_;MBiDq>!aNHp^2eCRx_cVU}-U z+#SDjT!k#jzd(ZH6^El88=Ehnf_5ZIR#vP32>nqn;)PD>6#De-0jHtB|4To9Kz<9r5m|0?JU2)UqejMPB|Y# zlJMA#V{pOCCRKXFG1X;YPx&gw!ua#2kfj;fU(6p4`JntELQ6h_vuA*n%n} zeH!Agu9nmx{*@{a9VZDvY@o015{ChHNzR){QiOS`Pd{hBZ}=$&Yd^80(M2Mh6;>cx zsdma3=$r8we@No9ex2h`N4vt}s+0_2KKFf%I^7rp4JtuvQK1>6oGMZUy>+?W#vHKu z>;Xk~N2H1&E%_%!=t9_O>;~7_`1LIDg`%ACf8a5s??V`dS1L8_0hAKyi;iaUpCFm8 z)7-`(w7{A_8bHfn-Il>SMNdK5m4ARZ6+>GhY!|&4tdy`#istvirWm*B#%JJn0}Dsg z?6@4;%GSY!;nz5871q)771 zurjVzw{a~D5*wd!LdEj0g~@XDx{XgkWXBg3iRn}toAbJjMi`IVzNnn)R5n=dy3B3d zG#bZ0{fe9e;eHT39cHtq*kav)hJz?GFCbL8C)<3+T6b2+9x7PH-I zr|n7UL}~etPelEPGK}Y;8ZFFtW1-?@jDogKIR%>VH^b=z5kebZnCH?Vze(q%a^s#` z&HD97)PIVYR`Dv{Nf+eYg=7!6rPFlB69_N83GJko=;mvHg-w%?e~dXB;jHx-3|$|W zlnULO@l`0#%e>l%ug1gfQ$}bXpIcZ%H--spPs~tsEU!9 zt(Zc}5SxiV^S>~CTDfFeU{qsJmLqkojZr+GLH~OR56{^8`9MasYy~8Zy)@sNWw$N{ zT1(=bl=T8cUDsD9C80-EjI6n@5J%}i{fupR=$MsDrZbIeFthv?sV~_WtM#8@*aH8A ziDm2m0n%wV8X?2%oriYBpjdsU#meYL?Ru-z0J|BV03uYKZI8g<>1ECe2ot%4oy;dp zwZnPPR6Co0HPz1M>!#Y#e8W^bns1rCFjkJ7!zOn&+nYk0wVaon4p^*#boy}S zaqxt0Ia~}Jmpu;)nU?N)4}+5CaeYAGa=kDXpwRga@&dOFCdz2yVBenh8Ip|0QEk~B z>HlIFeup;gx!eT+qdnzwogwg-Thy+53Na${5;>;Y%&uUYHebRn%{T{H$`=?F$Td2> ze2Mc4@Q}ONs)#rB!AOy%6831umB>pP1~7ichC(P&QbrrXN!-&lD$$!6dFp6zFWQ-ruZ{zM3LTm;R2>06iy@jZ zOpg6VUoA4m9<>7HqTDtpUke`-r%)|htxs3T}FzH!jN^_*=gEMKa^nakQg(L7vpDEf~ojyB{ zM=+X)8kaEw-1Gp|rXrk#5moRzs1DZ7!R%S!~v!)(U8 zg_<_clXnL=WN^D`zAybAqm0t7}(#*2Rz#XU>G+PsAt&!39# z&BK7BKCSr46cut6Ka9R}SJPAcD>TJWx@K%)&5e0%Yja`xv~TI@#TYxDT`k*+*R6UA zMcSh+dmE*{t*8ARvGjCp3xAet+V^#58#1N$o&wnz?OBwnzYj6|2uWLAi-tH~M&Q&E zjATY8X*rd`nVCen(_DS1XHlA4_~hDzlto#_gUAoHJc2qFWjpUiEGrGmo%F>?>EjE5 zdK7IgPByDSx#n63VO^Y(#>SvzKLY`a@ry{vX1s#e5+lD7AnPcs`9W`~hlg;kKcEZV zX;z!RfLMAfUDrSqz3O~A&(#j{y|W}+p{tu^W=mwe>l_Gg*!qu1pop*0z$;LSy@bFk9zu1H&r$R)0! zY;>jPZvfj}4@0cItI|G3$aO(aZ*ZMXhMbw7ipZ_5=OL5c zvxJ=Qx~>Gny=NyOuXUV+^eYL7qg^CK-8_Dj731BLgB* zRi8l#Nn*N;^%!1WtIBZlkX0|oOG`|G-c_FAk%Xfv`JkPwGo*P)XaWXStEzQ~cg0g( zoyI{K10gx#JtS5+^i;-p+$)}!a=#MJ#@JQe?noo=c?2vc9y(*{rE2&AY(iC{sv*#? z28+lPaJcF>ib$RuOLBC*ttD{bRrQ(5z|(M*fgu~R*iP@BwF<IUH?&!w%@7f9rdl3HY^D%6-Vl&yNf z!9#1+!kF0*&?=wK<7-7LxvC`$WgW|Psf0(`QJms9Ij2>;2|cd*xiCEOI^?Q)T1Mw< zETHQ7J!aslJ*opd@{S#^c@U5C(-n@#;5rShmb@G^mirwUgfw_O8CR&pkPE2hG^SE|CUAyu#ovCz- zcdrhp>)IhlLELDap%U|t@GqEyX^ z=fKjG|5PrU@KQlMJ|P_|t@2#e9o{yO3|c~FHmg;K%P)*3HGvNS4#&^3eTFDz0YG@J~pfSECmCOqlihEKd z@jdY0cc+LV?_fkx7DYa`_Iefp3-Er1YLOIa8G`;xDgg(M*EUoYf=-?SKKM%YEJ7CN zb&eQ<6~0(cC7$JZ%_B;JmXU`=qVHH10gLnYM{MhY{w$S%r3;A``BAOE2@C97u4fUl zcx9wGV_LG{m+7g5EVdz1Uho%$+q9Y0ZqKJkcAbVrLUp3$9<79Fu1=DO%TMe?9K1Z&TW&^!qWFU2!3sB{p=I}pEQN{UOA}@!_7Zi!pspc`FU|87ORYsW zmtC64CU}QNp%N#;I4rwTQhAd`r6w!{-9g;km$$V*^@~OI9|B*Lid?Qc`=u2av#;L5%eOQy_!0O z1_DxLwyGl;D0R?Nyby4C8 zm}QlUh_}P2<`I77u&D_u7q1n?%_q8KP53?dTQf$D$tLFFOY{7P9CzSVvs%^g^+*j8 zifN1jns5`D^>0NV?<&PI^2bo6n$HxD_m>2xB`k)F)SRXG#Oq9oKB?GZ*46Cv4UXjP zfMgagJE>7n84}(~LWV4-j6H8a>68t{v4j^m3_(@>3gSdKWDFVAJX|d%yI|UD_B)b4 zfoQS`-kXZgnXrhIcB!g()hCWpUFu8zeGzg!<4Ar6kX7-@Rg_wlDWM7KUel(k;$+Rqh9lK5kcM!iz$_0!gs5wS5rLi zi^a1`3`?Syod2^_z{_M(ftGm3c%%lUMP4n7wy373#PufdZ9*)soJE_p@SngY)to8i zc@-_be8NJC`#QzL5Hra1A)y$NCeIR6NZ>vpkhj>PO=$@mVd!hl)5Z9HCxT;0^U&5L zOdz|r>Ebf{x_^emmBjr)NPLqhaRx;$rGkVmj^Yn=@w|9FPBkpeP^`3s4=E=utr!t5LE7D$~)>?}O-t7|_U^lBcuGc$~=L3=p zyzgh>GTw6lciV6RvXNH+73tzHD)gst@LO+&E zG)wayVYF9T#wBpIYVICRz|y>47~8g>zn@FM(!6yT+qN?srJoy4z|y>o7~8g>pUov; zY2HzcZF@)}N`E|@fTekLG1|7}&Pkr5xdg0&yVX$wtYLkc9Jp8)CziX|suCrP9}%}# z7vGs1+fke~+pVT7J*;CeMJut0v_=2l9*>V?tUrC0~cNG?szvRa5ix8D53gs?z*FGS8jh z(5kYb|73VF{7Nn6N0s>IcFZi zo>$--dH%u|uj?f7)>YocpfQipJYMff^EjVGfwXj|8x|606>lK7u?ziPy+l4A8eO=0 zx$`+l!DZ9oWB&`(t**&~)FYC?Tq`8vaGe1bu3jk-muoaJwGv5i9Ux|vL_DqvVpdBe z$+a3ou(~c|CMrvIeQyFH^@2%XeiT+`4b#nC%byv7i#`k+H@SX037OVPi7eM4jO^-l zQXhlTxD0q!gI$% zt`0!gBZb$wv(PCa`>g*$ z>>`C5)?m>XDZKGqsH-CTRTQr2#y#Km0`^$fYB~d5TE{THfylWd z*aAip733q7IhL3c5MbD>Ln zadyDxGzE};2}-Blkb?v0Q$*1myIWIT$Q6mUXz7)R$A6}&@8RKiY#8s8 zId-pezlo7WyjaC+-C>w!#OJctj@`b3@r=Lj$a)fj;@I7S?+YQ5Nvv}&PwGd_#<@q4 zq7pj-^5}bNkQzB3kDQp#BVXP{Nz{{im=zKQpr){@^Mz3sWTb9BIQ9;|U#Rc)cZwl+NYlmHQBg|CC(c^C#&DjI^|A556em1wc_DMFRsv6@xY? z{R~X9H6@)l9pgV)*Y|km$B4tg%Zf@N3!H^kHA*21oKsZXvNi?ISr+58BHn(C|59Gx za~_)MFAliz7!?Ozd5r(uUf=U;78-EXQRKpLLy>B+MdZS9!%P+30MSBS@t^YRdrrq3 z6BPvef}R@o&&I04>r!b;jnBL)TANB!YW#Pkiu%+j|96_w&dQw6m|4d~ENFAi_Ze~O zju#Or5F26W8O3N+gp(IB<9}{I-;-837)`=*+{Co(kxy8T_)vHLXsW_0R7y+*+jxrU!lWOuxM`3(;kr2dRSE+Mm`6D zN)oG#NX%yR5LvtS$eKsOQK3D!_GWa+L{ByPHP-3sSG=(S=4BAJ_a|6u16E`KN6wu$y#U` z9V!l_Ni48ZA{Z*(H;ww zlwGwWRl_TBeF(#p#CGPs3|cA{XciJGk+`DFRPs@o{U% zO$q zpBKa2lT~qLa9joM5h|_>4&udXdi&M3@ozv(`Rr6cHD72ozhQi;MO~$ZR?0ud?WBQ% z@*_E&SCZp@Fh<|=htDCf)jgvhd)nNQ!JnXLb7) zcdBaNujTE+Ld?TWpd^0s=D8OyAM4(SKb-+>)y=>@jnM1(lO^0;2wbV33N0DgI$A!G z>(g^!-_oi;(|{}7SLt_SL5Hi}6Xh=VDt=#AfSl9t7pZQC?)SHABk#$*8};C}9NzK2 zqXe&$_1{>iZdNPSAIh*?C~H$1TiIMzh$$9+$BMy`!daj` zN_$b13FiqDMp^U}4P(ph_Ec%NNh&!dLaQQ55j#3lx4F@t%C^QtvKh0AQdFj~AWR!) zks29|@utoJfUrf1L^!URoal&S_9Tv|8vMzq&NI8nNl~oMWY?#}R72V=uBob~%D5Hj z=sf63CZ)w9vqcZ%vNqU5p)Hvq0#-VU!zN6{b^ih)i_n2-Rx%odHpMgsDVdw!n6Da| z?gGv8i`-_Bt2#5v>I!R6MRh0&nEI_Migb(FOl|^UGeH=-R<626!e(WHB9@sQsYXVe zNplw2(lnRD*Ze3$Thh`^mO=w z^_J=Ja9bT#2)m-_I(6CV`dSXLtxC8=XK_O0MP%8G%GmnBkd&O$`y;N<^VKMvA!1{- zrfeGao-k^bF_BR_E23>6sZ7S>>_~k`f;9jQJ9JZVz~3JSZL_hs^%ZOV%h1_?nkYtq zyA3XVzG;H5(Y`kd!y~FufD?kIXcFmNfR5l(_GqF~p=PTKpia85Q6vK~8snCzYyrsu z3PsJIWIu)&O+VU$Pp$NDZM?>Nr%YIw7HOU#Xx0tx5Umoz~P$B9F)f9es07-v+Q}% zk--Js2*qF-Im#SgiO_|_2wfL|1dlDA%yyw=_>oCbuuW9Vnu@4|7vZ~7Tf&uny;zS9 z0CqYUixt4_I_Fp_)ujlr>kIPBW#BKREq9y?8J{H zDDqax9CnqBk^bUyBgQQf$mpw))ACcqaM%SM8dlX7=G4X|*Y{P-JQs zV#<1`Qp!B#U{{gc!b0?g$+PC{TL99i{j1GoWycjNC_ z{Jo051Y|12-%R`k@W+30-l30lq^<7+R==ImpYX+~_9#Qo@bxlZhxqycFXvn?zdk|8 za3SPO<|~7*5qKp`#LKY+FZXh$)$?^GUrl`R2V0%pe4WqNcE0-f+Qrumcsahy*UuRJ zB|{&w$=@(~fUn>2b%?LG@N)c%FMiVE$i>S!imwTb&S8kRaGWa{UB_1gUtzv3;cFLO zo?GxT`1xhxJq+ECSJK0L{T445zuHK8gRg%xivLu|$Yp3OUPdurGx17Xh?lk;FZo%& zq##55TqkKGUtht?z!yQ9aVev_82tuAEBLyL(OdCy{g9yt7~0Ped+s{G&?|iX6)%(j z_<$2~pgF%nMi@@WgYA(!%XFjQ5@Tec!vTRX44`b!-Z@`4#_e@Dna(2i;=%bYocCdu z7$Z~}mqW1jI>h-mQ#TgwHA;VHc*BNos?_V^C!dK9d!dwLWP8pqGS?Z2ml&y@(+wkR znCo{NiMx&L^+wJ*V}vKe7`e{K0~j~e7{AUaLMUabk+6vKQ^nJ!!h(_AD@RzHOvlV&p$)jP!(%xg<8Tz4hR{R5JG(t`cL|X2avz$k5o+ zjeLYm{AD|PFjSWqhBKvE@l}yz?~FJfOVy1GwB|-rE#T5dG_}ddof1!;y>a9GHwxr? zwi>yTbz>}5_EwVf9pssTN*C=lraWN`zr+~z17p1BP1O0VSR(AbG3Sk`I(XuK%NTXg zaPKuzOAME%*)Vadcdy}DZ)AGDWenMCjJ?emz1DDZtel(o8neiHjQj)WTw0+cC(3Vo z$Itm=&@oDNZY**;OAL;eQ&r-8(3q~OFuv_@MN8Yem(I77@e>!GUevIW>`5**9H1)m zR7HZP%c$sI+>pVxw^p6sc5)oIa6mHGLwwJbao8kHp^8L@y}9e0#CGNxL-!g*>tgw1 zZ$dktf%**b{1DYO8>!2MIa#No+sU4(My9g|S^-uQWNconL0WtFwOEYAFGs)7~1mS?a zyYGApWG{Qjs9B~uEJ#=hk(GW1^AZOqy#LrzmMs)!D~b&QEpSbGK3Ou92~qBMON$ zE;I5UFoqTz`F{n2&rn3DZrTTF&TqgLn$8iB?}!e&g%S4oob!h+-AH}N$m+)?`;gFi z6WBD;b1Rs%EXR?EUW)A4XOqrD;BgLwCx0*OpW?G3+dhVM{t0B?V&uMM4A~AA8sknk zGA=PPHyi28jMR&b{4jn6h=#`HS!X0HH%6{E(vdxNnKArz%FP((Rxs}pqu>c6!`Rz&gU5&%K)gfXs#)sF0mExp|E{DNbb^m8NkL3ID;ia|D+ z?ln@@%X>TD_Mj?$+K1cD2OQwm&*QjdpRhZR8M-me(__?nEOVzyXB1-M#N&L1r9U*X zEnX{9> zQKHy1j=*yZ-p+(&c)P-QC9E?>C0uD_?lp!iGYVffj8m04RYcntH=OUGQ)8ehVel{{ zV=OXYUl?&dYRN!eR0bS|0~W@<#p3(}Y8d5AL=9OO>Fq{k4@do!ON=5+cbEus-T*_5 zoLdY>kJR71F&J*t{HNE2OUwNJwoo|OPr0H`ci*=iNCH)D#A}I2U>fA znn09n>-4iZtu5Hr(Y4jz(ba^u1C8hQgt~%STSHfCuw83x>FQ|j@V7E!ptT!i&q1+< zo@ReIuo1DC_UGb<%jawUI)AXMtD_5;*498cs5N(V30YD@7zn#yd$_Bk)xQPJqBkpM z`TZN)d;E>Pz0>{vj?V5<0FWCc)4Kv4LTWWR)EeyW7UI2H51REi2fD)*<=~RvFY(qO z5@s@9z0%(u0DFS%P1=^m?r=v>TcB49bT@`WZ9%QImESF*`MQqQZf^sM2b#|5=??o_ zf`LwUXyW9;){gd#g$PbouLzy9XA7YK{Yje7b{e}o+qKq?#z1SZv7;SL)S%|3u3$4m z7|AG~x;q1nL2V0r5!SlHUEz*aG6eEa;`euUbP6euhQT=0zhSR;GbE;*|F6cVTa~p+ z_rfzn9o-^W<<;$>@Zxgs>Qli_bhtg(8`f~iEzsH;Z1wlFbXvbC*ipM#>+I@i z3v~xkdsi^fv=wp_4s|z&f=yaSC!`;;JAQ&C6X@T3(a6pY>V&)-TLPhW=^`XwYlH}P zK@&*8si0s6iUc=;%aG`H@-bZ9Kt1&~Zf@{GKEN%iOix=oWHut=&;SjUhr%I_u?G_bG&=+>#|UG*zT60l zWU_0hZF8V21SwWy9A{lhL06~kF?xqV|R1dUd%yuY}8SxZMl=dbRr z3$=B!MlmQ~imhm0v2}A0V$nri1X*P>V)-TdplnBIb4U0DX|#WeG!(0C219BQ=1b}ntg>^9wmQiDd{! zY}!1Ij54y_mXW2a0plxg)P@YvNwu^Bc2_cVYnG;H5#eKln!mX#7{rLfX@D-bYKLX&FZ(ArlxkuXS@TDGBBpV^HbcA!Ivc1w4By1^J-TTYkl4@@Y7K|l zp)rajGPyODRshw}+-$imUs4eVahPC8gvU|eh`i|DiixuorkvBb&7CLPUNo9>Xf79TPd3$@K zUfr}ZA=-9?PJA}PwAS88x1}x&H?+E`o(&CVY|CbRj`u_J6lWeFMon4zl7HTMN*FFEI1y$5FhZ>rrCC3VH=|UUPr?@u=JpoK0e$9c<5iEIXXFEEWx@l zh}|gNseDzq!&-AE^|>1Z(HsuK#KX^|rz_(;KrSL)Pg?`mS?$4%@HV4P9>%S!L&T!B zqhsJohNgSbW!p*wM%vYaGX{(cUztc)hkhu_f#&Z~L791E`2 z>PCn{oR^AG50_5sH)mDXbCv3?tH4xV@&Ybi_u=YD$(3Twl?{S&S*7UfbMl zyLaeve;0dhLq|ue^3>+rQ*VTJHAjAKnc1^pyn3+urdw?H`SZ&)W0f47->;yWrlBm& zm=>{qn)`*LH&&<>ubifXB6S=kE}b4H>zFbJDsI1ZdSsuV)N*9O0xWa+h9?|rjIEV; zIlZdrk{gSq<1EDoF@MO+S*Qt1uNKUH*x%5aw}hG?BUt1&b}%q#i=4exlNf=;Wyfui zGp?-j?QMq!7~&w^Evy4HE}>y?!9NkG#@;}T9Z>$gT@G{g#^@NwF7(Ki zmSA*r>in3*+Cq(5Q%4W9SlZaw8fs{y!yD|{9K^}CEj4rJD$j;968uY9t5vTKc~`-2G7d1IJ(2f*NR^ z^3UVkPHl6uZIC0Ift(iFwQx(QTl{)OeouQ(cd)698xUA>Yc%cMozPmuxjvW8&W&x@ zwrJLxd%`_k(VZE1tzDrY^b2Ib=YTgQdrHc@+6(t^M`v|=6BZW1bHy(geaG?#o#On0 z)doE_e{*X`0DG@9m6A>C=N1gg!U0>5(QP;3WHUsXoUB8uFkYc1Kel_Y;{x9Z-IT4W zK~=4^49*V?i*x{57Xo!^vBAw65gKed!I-H{Crsl()j^B|b{F7__#3cmCHsl~df63X z|L9IpX^+1PRT9~SBBS88h$Z7<9h*SheeTrSv1YXq6hj$7S#H?7D3K{7>V+a72xtm~ z1D2b`jRV`@s=X#z?O`sb>(CnPEmW42_8X2?#O_6w9~h9c~bRH_o}Tq@IR58nlfOFSlRowk_o58TbFy*v%NQzT|ZG1*X@F_LM8>Z{{v9 z_7q#GyyGn)oDdbFAQrdWvE+=}*wGUf!NGo;SSRijQvhSvZ<_dL%0$FZy3{auUP=W; zeblar24|N&;yT631GQ3Ksy)3I($gHAIk-NQv2>0T{>Tlo53G@qXfIEoKX6Ucf?sNJKm`h zn9>Csy2X!a4}ZY`wx!wwI9q{b#eAqWbYn{5mNmQ=d*@!QKX5G5gv4(2xQ(9Rh0!${ zObrT%iIyS6`2$%2u5~taA%9d{o0P*Bt6u$P!Q;=h{hV6(c;E>Bm1;oigbN|-L`t(( zmK@*Dx1z0d3@D6TT)|k$)BrVW7RL!DU{ia?mUcfqIx0e(XHgO8=Dq?PvNjxjV2n6L z#fWgsrm%J{TL6jH)}6I;=U**5(F-I?x>X(^YiVh}rpTBo< z90!oboqM6M$?dX^16QLvK#@g9za>CpE4T?$+fc90w&WP3!P-|R(|88cZu<$A1&X!P z5kVe&(KA@*N(buHz}=wF6$u{iP$cZxO{PX`iW3Ql+biO}Iph#_4C@v+4cOL=%)*Gl zf5h-&F$F#7!2u@XCH?0BSm8h~-J-$7YlgKxr}c*oYGbZ}jE{G3g!7o(g!goCFl?fP zocN*Z8`b%$Xuiy{P;MAf>^<~%NHB$H*y-39Zc&r5obSN5Q*!ymvjQCQCGDDwtTNxQ zkF*JBQ}%!4gu&i^wH#COu%}y{F;7=8`2y=%=nA)#9+p@XuqEO@TH zB%=4pg=&m{h7W3K_29nBVTV0GjK`!U{=03&2Qog+H3#2AFd*KB)v`OHnAS|z4!Xyo z_8n9%P9Zo*FNH<-)82~-q1VQhvdm%;({{W=Y|MlH)eEVDF*?<#o!irKJTubIoLb9% zIpDxzNG+GS6t`B)pabJ3t0tH^IvqW5Ub&XSsLDnU<_|g9;&4>0SW~!o(xlQEg{7ra zr%f#>oYEHVX%EiZ7;F!Ag&Gm%3^T8HX2q0>^1>+_3#Z^dz}9wkccG_yN>4kE*PEt< z16ZVY0|^0W+%yHpynF4j<&Z&)P#94KVjfRo|(byal7ZwW9yx3q(FyJmX3T%6f zO(}I?EpsZC?osbAvKWL#i`n_M>|VV3d3g&&&h+u7`oSdQxR5Pj{e@+Vy=;5v&Y2J0HUAnriqs~uX%bG$qTNL+m>v&k*!^vFDd|%+X ziDx}vlLbZ%9LE2+3(|>Ypje3>>4G|U!h%sT3mD#;fboNE>Ev+1*o6ZjUOZXR1B2yn z-3XJz(UkcS!eL+R;3jGy?8oI5Oqs!67#lPg?r74mr~;=flffkHU~qq?2mfBDEU0;R zgo+Wn`cj2SqP_N(g*)bP@dSCb0XunEY^m!F>I@dmXbqtz+@2BJ%(EuwPwY9zAXC0F zi8RUNi*+qRtoIl28XL$f)&99<&rWD^KhDlwc(Wfz!gAjNzt|UU>x2h~F$cYv7}2ko zy=X{n>xqbMneo5{~j8xSpSr=0V&gv!cms9H|s>Lf0^l;f3p|>+t=ns z{>HA3o=%)aW9+Ss0gSNR6QRizKMsP3B_5o$S@3EpkfG-4b=_TcVK9c1arH6@a&xR& zO=2PJF7#kAi|x)$L2l%6MOlheIp>huA2NHRvTEowu%$C?ta1R^j-b5W>DWQ&33@kM zyMe1|3cNG|6kTh9LkkK;5c4_cjAi?ks~fSEr__(4jbTPaCQqK2z(nzfuVmDx39a^( zG7LE+%?s-TTV&lOvpsOjwc*~K?d6EO$z~em><~SmL^X%7OCy_@4I;1>hq;`NxpPJ7 zIw7kF@d7<+h0g^(M;|Un#1oX!V=t;#pNO=6@iy#qay@F7wuG>uZ5t=}3+HvT!%9*J zMf_myX7lc-kM zV3^FCP2C-SbucOtc)Vq3>G77KGTxjYAlVVS6?@C&1ZUfb*}`!iH~QfiLU7wVFt)h9 zqfQI0-3?d(YngW<5*Al67+Kw2!|NMhGjx!AW=lA)595~(Pl(Gn-iT~M%gUjXa~m~5 z?4az?olr$`NR6C>u7U=fFb!M;kqsi%5ZU9@GH@+*{MF%B>=>LF2OwwGB-sD3TEo6E z?{~tf4{-Ym7fSI~>MBC6F2Sj71~3ecROAX3*EGRitR2-gJr<1Lm_P}|Tw7gKMY7Xr z9RbIBQ76`ySr|-pN0ehp8OEKJ=>9L{*SZkQi)YH8!L~9z9rmm_0Eb3x7+Ci<)m$Pz zj=ghBC+Tu^YRt(%)$aa}~Zz$?l!mBbzIe<@{D z?yt4u+U$TgE;zb*d7EA3VAI}F4=Gu)<1?#BWz`Bovk<@(#gn-U)dQ>wK1|w#7II`OGjZXuT+xi|FK*#&P;esq^_rJYGY@oR@~Fw zRUB$>Z0%_Z7B^0sR9sqG+`ucdgCP2+VWH)(D4&9Tww~T8*drTQ>n4sp+M&x3v zk%^N{OTDB=IK_IfZssNJMtVSSxNs2Agbi7N=z+jchX8Pn5I16h7Ax7P&a(kX0B&x^ z+>~bBawa9ywX_s&f*`Ul;&LL1Ctk!5YK=fDt~U0_x<8h9Z_f}&2#HVh9p znIa<%2>WHR>+Yn}V0Mw@l42U>P5#fkL5kULwEmt7yu8JanxC}gkGV*|tOTe6=l>Sie z{F_6;E!M`8c0Ip7#&^(sjF<3(G<;mz3Rhjd=C;2|-RE-KU&Wek`y<#ixBc0x>9#*{ z9pkpY0WEghAA0)T_E(&j>2CXb%oex(p=Gt({+#jxxBa2yOS;?swsDc${!Ve5+y3OR z+HHSQIL>WTdf}wux^0 zleG-D{drou+x`-5oZJ55>|Uqa{TdhH zr&725h0{2<{Uy_8H4w*nW6Ur{|2P(pPDFwZ%+>ffnops;@$9@wES0i25hHAB|5RkBfYb2bb_137k{r(C9tp8A4Jy%NpY^^0O z|6NEQjQ*cV{tV4if`Eh-d{M#~T4G%K2UdDgTzU=|s^fQZ&A9XmNgt}&KOjxM^YL2w zldb&tid-K46glfjk4wMKO3#W*=RdB@{CRQduUY8@aq0471;}3*mtKsI*ICc#|EIaD z3yrIY!q-A;#Ue=&TBAbHpn=*;le9IWXnva7z@`oT!CI7U+HAA2O`0aDSPPN|5kbK| z_=6x+p`cjMioO(u_QhHRMJ$LQzA3)=P<<#u)%txi-*5c?nu0G155th~ zPjM(nGfxSR;^7B-8c{Ea?hE41O#x>ucOTg>h*X11iW*o}0 zatTgeK@wTl2%Py0PYMbw0cZWj{pE=Gu~WQ?gt0siH}EC=K%&_s1v1 zAD2TJxW#F4kiM*V!b6J!-^=0uO#I=2PyBxf4^MT%`*5xl^BJC*gdYRmEPs}~CjRi; zrNEDX*USGG;tvmR;$MMdn3!&OcohC5@Mih5cFVAs9Kl-!H=~Tv+-BTu)Ehnwg$rJB4;6>8BW|iV zbo3c5?oXG7({+fe4hIc)M_~XoIdlvQbYPV#KlFj1;>hRO;8Y+C-!Wb2#8RquEM`?}g?4Cj@ir5$x4BrU z0g9Fn3)pL%-4LJ8*Csx`MCEg}doFMJmd~a{WzUz-r$lK*b#PWL6k%z6RxW3emCv=_ z-vG9k&BCax!4`AmU&=#V&g?Zm(G4L{zo#vqbE9g(8>B+7mCtHP)0{wDXf%G6xq$t; zwHCnSTF(t%b2ILNUSwMc|fA+p%;1@vYqh{kw?w$gbiSsf8Vjs!V(&QQo7E4^{bp7l4cR;vJWB*5GEVKY_5u`|ac6W1& zrPV~$%w`$ao4+}xN{3Ky>n*H=hWv&LERA_wHgxy58MF{vv&qzOjxOTx3#SV}HooFcdL=Ds1-fod2R}26!XSgha>JXtfby|?gfNMJ3hfrN7%x#WYeZD<|_RX*ZX6MV=`JmQfaBjvd zZezzB=9jko&6oS8U=pDmqS~vinR{W)TvHBtI&G-SsWl7D)pzQ8Hwz8#98QID&3w_$ ze5m(;G>f@zv47_P9tG|F3LS)RS37CikKh7J43(D-(=C zm0q*JjYzP|qZOT>B=8)`Th6)R+M48G$QRG5<0{wU!+i?KHv!|+)Q#6Eyy*z6uAPTA4=JWU zT=I1r+=tx*by_OJfSs?~VQ*iRd z3%I{@XGvMmzI~IWr!9p0ZOo4nG%sPajc`4QGk>twFqK{Yn75zHxLgXu^1pMd-Fi8` zw;+0la3fkav&-ae_^?D8qW3VkKaw|nnbBrr z6t#77gCB$E%C&2U?f%aweWR^n#Im$=asG#ZV(Bm3|M!wNT2_Ja9_clC9Cq#8DE=v8 z>33m0p3dn0sKBGk{8c1xdOD-j!)9Ha{tuD-`8LmO^i}mI zi^JNFUH=RZmV8|wBxd^RGCqz;7nhgG8~qJD_}){HH~lz2%SmT^{;G0q_+JQM+tsiU z^pP`?w~nQ572>meorWxnD9B51Ir9iWxEc3f`LlG5^7#9#e9&ujc^ON`VlX+oUIAfZ zmVVH$ba{@|j6CDIGJbj+mHxU2Z|L&Cnh3Y(j5bL=VoM&B{6uJ&p2OsfpZcB{W7ug8 zNVju>$+(zzLyr7~m%LEvri?JWv3zfi{2G1$3vL(ZCl``9tzZjAbm$r*i0@}9f$-|?;YziEsLiY{GwL{;QCzq#ZE&a3=daM_BVwLhCb k7;J6NOZfj2KYH54&Y5v>`WznX$-n=r7kV}lh%S?V0Qi@5hyVZp diff --git a/Two Pointers/tripletSum.cpp b/Two Pointers/triplet_sum.cpp similarity index 100% rename from Two Pointers/tripletSum.cpp rename to Two Pointers/triplet_sum.cpp diff --git a/Two Pointers/tripleSum.java b/Two Pointers/triplet_sum.java similarity index 100% rename from Two Pointers/tripleSum.java rename to Two Pointers/triplet_sum.java diff --git a/Two Pointers/tripletSum.py b/Two Pointers/triplet_sum.py similarity index 100% rename from Two Pointers/tripletSum.py rename to Two Pointers/triplet_sum.py From 0832dde33569022c6d208697a1cd4158f8d80072 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 22:25:48 +0530 Subject: [PATCH 0219/1894] move to arrays --- {Two Pointers => Arrays}/triplet_sum.cpp | 7 ++++++- {Two Pointers => Arrays}/triplet_sum.java | 7 ++++++- {Two Pointers => Arrays}/triplet_sum.py | 7 ++++++- 3 files changed, 18 insertions(+), 3 deletions(-) rename {Two Pointers => Arrays}/triplet_sum.cpp (78%) rename {Two Pointers => Arrays}/triplet_sum.java (81%) rename {Two Pointers => Arrays}/triplet_sum.py (73%) diff --git a/Two Pointers/triplet_sum.cpp b/Arrays/triplet_sum.cpp similarity index 78% rename from Two Pointers/triplet_sum.cpp rename to Arrays/triplet_sum.cpp index 221ba382..c7c2d45d 100644 --- a/Two Pointers/triplet_sum.cpp +++ b/Arrays/triplet_sum.cpp @@ -1,4 +1,9 @@ -// C++ program to find a triplet sum in array +/* +Given an array of integers, nums, and an integer value, target, +determine if there are any three integers in nums whose sum equals the target. +Return TRUE if three such integers are found in the array. Otherwise, return FALSE. +*/ + #include using namespace std; string findTriplet(int arr[], int n, int target) diff --git a/Two Pointers/triplet_sum.java b/Arrays/triplet_sum.java similarity index 81% rename from Two Pointers/triplet_sum.java rename to Arrays/triplet_sum.java index 2b41074f..1a77c27e 100644 --- a/Two Pointers/triplet_sum.java +++ b/Arrays/triplet_sum.java @@ -1,5 +1,10 @@ +/* +Given an array of integers, nums, and an integer value, target, +determine if there are any three integers in nums whose sum equals the target. +Return TRUE if three such integers are found in the array. Otherwise, return FALSE. +*/ + import java.util.*; -// Java program to find a triplet sum in array class FindTriplet { boolean findTriplet(int arr[], int n, int sum) { diff --git a/Two Pointers/triplet_sum.py b/Arrays/triplet_sum.py similarity index 73% rename from Two Pointers/triplet_sum.py rename to Arrays/triplet_sum.py index 24c92796..0bb884ef 100644 --- a/Two Pointers/triplet_sum.py +++ b/Arrays/triplet_sum.py @@ -1,4 +1,9 @@ -# Python3 program to find a triplet sum in array +''' +Given an array of integers, nums, and an integer value, target, +determine if there are any three integers in nums whose sum equals the target. +Return TRUE if three such integers are found in the array. Otherwise, return FALSE. +''' + def find3Numbers(A, arr_size, sum): # Sort the elements From 46a3b00ba050a0c292c17d57e59d65d1a1582d09 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 22:26:53 +0530 Subject: [PATCH 0220/1894] rename file --- Arrays/{sum_of_three_values.go => triplet_sum.go} | 0 Arrays/{sum_of_three_values.js => triplet_sum.js} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Arrays/{sum_of_three_values.go => triplet_sum.go} (100%) rename Arrays/{sum_of_three_values.js => triplet_sum.js} (100%) diff --git a/Arrays/sum_of_three_values.go b/Arrays/triplet_sum.go similarity index 100% rename from Arrays/sum_of_three_values.go rename to Arrays/triplet_sum.go diff --git a/Arrays/sum_of_three_values.js b/Arrays/triplet_sum.js similarity index 100% rename from Arrays/sum_of_three_values.js rename to Arrays/triplet_sum.js From 7ce0e2b6b391e0663f0d7ba38aa1c548eee60683 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 22:29:07 +0530 Subject: [PATCH 0221/1894] update link to problems --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bd3f3e2..10e62d8d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The pointers can be used to iterate the data structure in one or both directions - Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) -- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) +- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) - Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) From 9561ab86e65abb580fc1c47af7066db88a3276f2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 22:30:48 +0530 Subject: [PATCH 0222/1894] update link to javascript vertsion of triplet sum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10e62d8d..d44255e9 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ The pointers can be used to iterate the data structure in one or both directions - Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) -- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) +- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) - Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) From 987109c645b9ba036f4924166aacce7fd3dc27ad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 22:36:36 +0530 Subject: [PATCH 0223/1894] update contributing.md and readme.md --- CONTRIBUTING.md | 3 --- README.md | 3 ++- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e2065e20..67f75882 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,5 @@ ## Contributing -🌈 Everyone is welcome! -You can join the fun by following our contributing guide. - ## Fork this repository Get involved! Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account. diff --git a/README.md b/README.md index d44255e9..ab5017d2 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,8 @@ # Implementation of well known Data Structures and Algorithms -Check out [contributing.md](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) +🌈 Everyone is welcome! +You can join the fun by following our [contributing](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) guide. # Pattern 1: Two Pointers From fb90c9df2fedb79c73ccfa7efabca90b05ea826d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 23:08:52 +0530 Subject: [PATCH 0224/1894] add valid pallindrome II in go --- Strings/valid_pallindrome2.go | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Strings/valid_pallindrome2.go diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go new file mode 100644 index 00000000..cd6fb008 --- /dev/null +++ b/Strings/valid_pallindrome2.go @@ -0,0 +1,43 @@ +/* +Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + +Constraints: + string.length + The string only consists of English letters + +Sample Input : "madame" +Output : True + +Sample Input : "masdasd" +Output : False +*/ + +package main + +func validate(s string, left int, right int) bool { + for left < right { + if s[left] != s[right] { + return false + } else { + left += 1 + right -= 1 + } + } + return true +} + +func validPalindrome(s string) bool { + left := 0 + right := len(s) - 1 + for left < right { + if s[left] == s[right] { + left += 1 + right -= 1 + } else { + skipLeft := validate(s, left + 1, right) // skip one from left and check remaining + skipRight := validate(s, left, right - 1) // skip one from right and check remaining + return skipLeft || skipRight // if either is true return true + } + } + return true +} \ No newline at end of file From beecf30027dfe58a74b9cee0778613999fab46ad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 23:10:50 +0530 Subject: [PATCH 0225/1894] add comments --- Strings/valid_pallindrome2.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go index cd6fb008..f991be31 100644 --- a/Strings/valid_pallindrome2.go +++ b/Strings/valid_pallindrome2.go @@ -16,6 +16,7 @@ package main func validate(s string, left int, right int) bool { for left < right { + // doesn't match then return false if s[left] != s[right] { return false } else { @@ -27,13 +28,15 @@ func validate(s string, left int, right int) bool { } func validPalindrome(s string) bool { + // initialize two pointers at opposite end of string left := 0 right := len(s) - 1 for left < right { + // if value at left and right index match then move them closer if s[left] == s[right] { left += 1 right -= 1 - } else { + } else { // if mismatch occurs then skip one and check rest skipLeft := validate(s, left + 1, right) // skip one from left and check remaining skipRight := validate(s, left, right - 1) // skip one from right and check remaining return skipLeft || skipRight // if either is true return true From 8e3ee888f9a92bb8cb9c689f8adab5f35f2815c5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 23:16:44 +0530 Subject: [PATCH 0226/1894] add valid pallindrome in c++ --- Strings/valid_pallindrome2.cpp | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Strings/valid_pallindrome2.cpp diff --git a/Strings/valid_pallindrome2.cpp b/Strings/valid_pallindrome2.cpp new file mode 100644 index 00000000..2d083681 --- /dev/null +++ b/Strings/valid_pallindrome2.cpp @@ -0,0 +1,48 @@ +/* +Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + +Constraints: + string.length + The string only consists of English letters + +Sample Input : "madame" +Output : True + +Sample Input : "masdasd" +Output : False +*/ +class Solution { +public: + bool validate(string s, int start, int end){ + int len = s.size(); + while(start < end){ + if(s[start] == s[end]){ + start++; + end--; + } + // doesn't match then return false + else{ + return false; + } + } + return true; + } + bool validPalindrome(string s) { + int len = s.size(); + // initialize two pointers at opposite end of string + int start = 0, end = len - 1; + while(start < end){ + // if value at left and right index match then move them closer + if(s[start] == s[end]){ + start++; + end--; + } + else{ // if mismatch occurs then skip one and check rest + bool r1 = validate(s, start + 1, end); // skip one from left and check remaining + bool r2 = validate(s, start, end -1); // skip one from right and check remaining + return r1 || r2; // if either is true return true + } + } + return true; + } +}; \ No newline at end of file From 48674c4d8a1e7a8901e426256b53c97c7582cc53 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Feb 2023 23:19:43 +0530 Subject: [PATCH 0227/1894] update readme with link to to go and c++ solution for valid pallindrome II --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ab5017d2..cf0168b0 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ The pointers can be used to iterate the data structure in one or both directions - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) +- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) + # Pattern 2: Fast and Slow Pointers The fast and slow pointer technique (also known as the tortoise and hare algorithm) uses two pointers to determine traits about directional data structures. This can be an array, singly-linked list, or a graph. From 30b97216b1cb65c57948ea1d3f8e1bfc05e6710c Mon Sep 17 00:00:00 2001 From: Munyao Kelvin Date: Tue, 21 Feb 2023 05:18:58 +0300 Subject: [PATCH 0228/1894] push file with program to find the middle of a given linked list --- Linked List/linked_list_find_middle.py | 47 ++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Linked List/linked_list_find_middle.py diff --git a/Linked List/linked_list_find_middle.py b/Linked List/linked_list_find_middle.py new file mode 100644 index 00000000..2a539422 --- /dev/null +++ b/Linked List/linked_list_find_middle.py @@ -0,0 +1,47 @@ +# Python 3 program to find the middle of a +# given linked list + +# Node class +class Node: + + # Function to initialise the node object + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + + def __init__(self): + self.head = None + + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + + + + # Function to get the middle of + # the linked list using pointers + def printMiddle(self): + slow_ptr = self.head + fast_ptr = self.head + + if self.head is not None: + while (fast_ptr is not None and fast_ptr.next is not None): + fast_ptr = fast_ptr.next.next + slow_ptr = slow_ptr.next + print("The middle element is: ", slow_ptr.data) + + + +# Driver code +list1 = LinkedList() +list1.push(25) +list1.push(33) +list1.push(14) +list1.push(22) +list1.push(9) +list1.push(11) +list1.push(20) +list1.printMiddle() From 5a29fb2b352d99bc57c0bda6dfc0a9fd8e6d2577 Mon Sep 17 00:00:00 2001 From: shinymew2 Date: Tue, 21 Feb 2023 13:36:56 +0100 Subject: [PATCH 0229/1894] add method to find median in two sorted arrays --- Binary Search/FindMedianSortedArrays.js | 52 +++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Binary Search/FindMedianSortedArrays.js diff --git a/Binary Search/FindMedianSortedArrays.js b/Binary Search/FindMedianSortedArrays.js new file mode 100644 index 00000000..b0b71baa --- /dev/null +++ b/Binary Search/FindMedianSortedArrays.js @@ -0,0 +1,52 @@ +// Binary Search +function findMedianSortedArrays(arr1, arr2) { + // If arr1 is longer than arr2, swap them to ensure arr1 is shorter + if (arr1.length > arr2.length) { + [arr1, arr2] = [arr2, arr1]; + } + + const m = arr1.length; + const n = arr2.length; + let left = 0; + let right = m; + + while (left <= right) { + // Partition arr1 and arr2 + const partition1 = Math.floor((left + right) / 2); + const partition2 = Math.floor((m + n + 1) / 2) - partition1; + + // Calculate the max and min elements of the left and right partitions + const maxLeft1 = partition1 === 0 ? -Infinity : arr1[partition1 - 1]; + const minRight1 = partition1 === m ? Infinity : arr1[partition1]; + const maxLeft2 = partition2 === 0 ? -Infinity : arr2[partition2 - 1]; + const minRight2 = partition2 === n ? Infinity : arr2[partition2]; + + // If the partitions are correctly balanced, return the median + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { + if ((m + n) % 2 === 0) { + return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2; + } else { + return Math.max(maxLeft1, maxLeft2); + } + } else if (maxLeft1 > minRight2) { + // If maxLeft1 is too big, move partition1 to the left + right = partition1 - 1; + } else { + // If maxLeft2 is too big, move partition1 to the right + left = partition1 + 1; + } + } + } + +// Brute force +function findMedianSortedArrays(arr1, arr2) { + const merged = arr1.concat(arr2).sort((a, b) => a - b); + const n = merged.length; + if (n % 2 === 0) { + const middle = n / 2; + return (merged[middle - 1] + merged[middle]) / 2; + } else { + const middle = Math.floor(n / 2); + return merged[middle]; + } + } \ No newline at end of file From 29774dab6880fe3964fa28ba6cc2feeded2b489b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:26:05 +0530 Subject: [PATCH 0230/1894] add pallindrome number in c++ --- Math/pallindrome_number.cpp | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Math/pallindrome_number.cpp diff --git a/Math/pallindrome_number.cpp b/Math/pallindrome_number.cpp new file mode 100644 index 00000000..6f925fe6 --- /dev/null +++ b/Math/pallindrome_number.cpp @@ -0,0 +1,40 @@ +/* + Given an integer x, return true if x is a palindrome, and false otherwise. + + Example 1: + Input: x = 121 + Output: true + Explanation: 121 reads as 121 from left to right and from right to left. + + Example 2: + Input: x = -121 + Output: false + Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. + + Example 3: + Input: x = 10 + Output: false + + Explanation: Reads 01 from right to left. Therefore it is not a palindrome. + + + Constraints: + + -231 <= x <= 231 - 1 +*/ + +class Solution { +public: + bool isPalindrome(int x) { + int temp = x; + if(x < 0) + return false; + long long new_num = 0; + while(x) { + int rem = x % 10; + new_num = (new_num * 10) + rem; + x /= 10; + } + return new_num == temp; + } +}; \ No newline at end of file From 771263419b04313b3235b8dc2644d86dedd383af Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:36:33 +0530 Subject: [PATCH 0231/1894] add valid parentheses in cpp --- Stacks/valid_parentheses.cpp | 53 ++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Stacks/valid_parentheses.cpp diff --git a/Stacks/valid_parentheses.cpp b/Stacks/valid_parentheses.cpp new file mode 100644 index 00000000..8b125bb4 --- /dev/null +++ b/Stacks/valid_parentheses.cpp @@ -0,0 +1,53 @@ +/* +Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +An input string is valid if: + +Open brackets must be closed by the same type of brackets. +Open brackets must be closed in the correct order. +Every close bracket has a corresponding open bracket of the same type. + + +Example 1: +Input: s = "()" +Output: true + +Example 2: +Input: s = "()[]{}" +Output: true + +Example 3: +Input: s = "(]" +Output: false + +Constraints: + +1 <= s.length <= 104 +s consists of parentheses only '()[]{}'. +*/ + +class Solution { +public: + bool Are_pair(char opening, char closing){ + if (opening == '(' && closing == ')') return true; + else if (opening == '[' && closing == ']') return true; + else if (opening == '{' && closing == '}') return true; + return false; + } + bool isValid(string s) { + stack Sta; + int len = s.size(); + for(int i = 0; i < len; i++){ + if(s[i] == '(' || s[i] == '[' || s[i] == '{'){ + Sta.push(s[i]); + } + else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){ + if(Sta.empty() || !Are_pair(Sta.top(), s[i])) + return false; + else + Sta.pop(); + } + } + return Sta.empty() ? true : false; + } +}; \ No newline at end of file From 565be40995605840e51623897bfad40374aa0ad8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:36:43 +0530 Subject: [PATCH 0232/1894] add description --- Binary Search/FindMedianSortedArrays.js | 118 +++++++++++++++--------- 1 file changed, 72 insertions(+), 46 deletions(-) diff --git a/Binary Search/FindMedianSortedArrays.js b/Binary Search/FindMedianSortedArrays.js index b0b71baa..2f09a6f2 100644 --- a/Binary Search/FindMedianSortedArrays.js +++ b/Binary Search/FindMedianSortedArrays.js @@ -1,52 +1,78 @@ -// Binary Search -function findMedianSortedArrays(arr1, arr2) { - // If arr1 is longer than arr2, swap them to ensure arr1 is shorter - if (arr1.length > arr2.length) { - [arr1, arr2] = [arr2, arr1]; - } +/* +Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. - const m = arr1.length; - const n = arr2.length; - let left = 0; - let right = m; - - while (left <= right) { - // Partition arr1 and arr2 - const partition1 = Math.floor((left + right) / 2); - const partition2 = Math.floor((m + n + 1) / 2) - partition1; - - // Calculate the max and min elements of the left and right partitions - const maxLeft1 = partition1 === 0 ? -Infinity : arr1[partition1 - 1]; - const minRight1 = partition1 === m ? Infinity : arr1[partition1]; - const maxLeft2 = partition2 === 0 ? -Infinity : arr2[partition2 - 1]; - const minRight2 = partition2 === n ? Infinity : arr2[partition2]; - - // If the partitions are correctly balanced, return the median - if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { - if ((m + n) % 2 === 0) { - return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2; - } else { - return Math.max(maxLeft1, maxLeft2); - } - } else if (maxLeft1 > minRight2) { - // If maxLeft1 is too big, move partition1 to the left - right = partition1 - 1; - } else { - // If maxLeft2 is too big, move partition1 to the right - left = partition1 + 1; - } - } + The overall run time complexity should be O(log (m+n)). + + Example 1: + Input: nums1 = [1,3], nums2 = [2] + Output: 2.00000 + Explanation: merged array = [1,2,3] and median is 2. + + Example 2: + Input: nums1 = [1,2], nums2 = [3,4] + Output: 2.50000 + Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. + + Constraints: + nums1.length == m + nums2.length == n + 0 <= m <= 1000 + 0 <= n <= 1000 + 1 <= m + n <= 2000 + -106 <= nums1[i], nums2[i] <= 106 +*/ + +// Approach 1: Brute force +function findMedianSortedArrays(arr1, arr2) { + const merged = arr1.concat(arr2).sort((a, b) => a - b); + const n = merged.length; + if (n % 2 === 0) { + const middle = n / 2; + return (merged[middle - 1] + merged[middle]) / 2; + } else { + const middle = Math.floor(n / 2); + return merged[middle]; } +} -// Brute force +// Approach 2: Binary Search function findMedianSortedArrays(arr1, arr2) { - const merged = arr1.concat(arr2).sort((a, b) => a - b); - const n = merged.length; - if (n % 2 === 0) { - const middle = n / 2; - return (merged[middle - 1] + merged[middle]) / 2; + // If arr1 is longer than arr2, swap them to ensure arr1 is shorter + if (arr1.length > arr2.length) { + [arr1, arr2] = [arr2, arr1]; + } + + const m = arr1.length; + const n = arr2.length; + let left = 0; + let right = m; + + while (left <= right) { + // Partition arr1 and arr2 + const partition1 = Math.floor((left + right) / 2); + const partition2 = Math.floor((m + n + 1) / 2) - partition1; + + // Calculate the max and min elements of the left and right partitions + const maxLeft1 = partition1 === 0 ? -Infinity : arr1[partition1 - 1]; + const minRight1 = partition1 === m ? Infinity : arr1[partition1]; + const maxLeft2 = partition2 === 0 ? -Infinity : arr2[partition2 - 1]; + const minRight2 = partition2 === n ? Infinity : arr2[partition2]; + + // If the partitions are correctly balanced, return the median + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { + if ((m + n) % 2 === 0) { + return ( + (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2 + ); + } else { + return Math.max(maxLeft1, maxLeft2); + } + } else if (maxLeft1 > minRight2) { + // If maxLeft1 is too big, move partition1 to the left + right = partition1 - 1; } else { - const middle = Math.floor(n / 2); - return merged[middle]; + // If maxLeft2 is too big, move partition1 to the right + left = partition1 + 1; } - } \ No newline at end of file + } +} From 3ee05980a8e55f8d7f322a7b6f7fba3170cbc09e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:38:09 +0530 Subject: [PATCH 0233/1894] rename file --- .../{FindMedianSortedArrays.js => median_of_two_sorted_arrays.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary Search/{FindMedianSortedArrays.js => median_of_two_sorted_arrays.js} (100%) diff --git a/Binary Search/FindMedianSortedArrays.js b/Binary Search/median_of_two_sorted_arrays.js similarity index 100% rename from Binary Search/FindMedianSortedArrays.js rename to Binary Search/median_of_two_sorted_arrays.js From b0363671c672c0f96d15bfaaac0c9563adbeeb7b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:38:19 +0530 Subject: [PATCH 0234/1894] move to binary search folder --- .../median_of_two_sorted_arrays.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Leetcode/Median_of_Two_Sorted_Arrays.cpp => Binary Search/median_of_two_sorted_arrays.cpp (100%) diff --git a/Leetcode/Median_of_Two_Sorted_Arrays.cpp b/Binary Search/median_of_two_sorted_arrays.cpp similarity index 100% rename from Leetcode/Median_of_Two_Sorted_Arrays.cpp rename to Binary Search/median_of_two_sorted_arrays.cpp From 0518b1e582f313cf9796cd2470716bdf413c596a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:41:53 +0530 Subject: [PATCH 0235/1894] add search in rotated array in cpp --- Binary Search/search_in_rotated_array.cpp | 60 +++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Binary Search/search_in_rotated_array.cpp diff --git a/Binary Search/search_in_rotated_array.cpp b/Binary Search/search_in_rotated_array.cpp new file mode 100644 index 00000000..3b1563ec --- /dev/null +++ b/Binary Search/search_in_rotated_array.cpp @@ -0,0 +1,60 @@ +/* + There is an integer array nums sorted in ascending order (with distinct values). + + Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + + Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + + You must write an algorithm with O(log n) runtime complexity. + + Example 1: + Input: nums = [4,5,6,7,0,1,2], target = 0 + Output: 4 + + Example 2: + Input: nums = [4,5,6,7,0,1,2], target = 3 + Output: -1 + + Example 3: + Input: nums = [1], target = 0 + Output: -1 + + Constraints: + 1 <= nums.length <= 5000 + -104 <= nums[i] <= 104 + All values of nums are unique. + nums is an ascending array that is possibly rotated. + -104 <= target <= 104 + +*/ + +class Solution { +public: + int search(vector& nums, int target) { + int start = 0, end = nums.size() - 1; + int ans = -1; + while(start <= end){ + int mid = start + (end - start) / 2; + if(target == nums[mid]){ + return mid; + } + if(nums[start] <= nums[mid]){ + if(target >= nums[start] && target <= nums[mid]){ + end = mid - 1; + } + else{ + start = mid + 1; + } + } + else{ + if(target >= nums[mid] && target <= nums[end]){ + start = mid + 1; + } + else { + end = mid - 1; + } + } + } + return ans; + } +}; \ No newline at end of file From fdb12c13be8be5a92c971eb087be6c5be8589f69 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:45:45 +0530 Subject: [PATCH 0236/1894] add unique paths in c++ --- Dynamic Programming/unique_paths.cpp | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic Programming/unique_paths.cpp diff --git a/Dynamic Programming/unique_paths.cpp b/Dynamic Programming/unique_paths.cpp new file mode 100644 index 00000000..b5c63319 --- /dev/null +++ b/Dynamic Programming/unique_paths.cpp @@ -0,0 +1,38 @@ +/* + There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. + + Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. + + The test cases are generated so that the answer will be less than or equal to 2 * 109. + + Example 1: + Input: m = 3, n = 7 + Output: 28 + + Example 2: + Input: m = 3, n = 2 + Output: 3 + Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: + 1. Right -> Down -> Down + 2. Down -> Down -> Right + 3. Down -> Right -> Down +*/ + +class Solution { +public: + int uniquePaths(int m, int n) { + int mat[m][n]; + for(int i = 0; i < m; i++){ + mat[i][0] = 1; + } + for(int i = 0; i < n; i++){ + mat[0][i] = 1; + } + for(int i = 1; i < m; i++){ + for(int j = 1; j < n; j++){ + mat[i][j] = mat[i - 1][j] + mat[i][j - 1]; + } + } + return mat[m-1][n-1]; + } +}; \ No newline at end of file From 25624c2bd8bf7df730febabda40f65f7be583cc6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:48:04 +0530 Subject: [PATCH 0237/1894] add unique paths with obstacles in cpp --- .../unique_paths_with_obstacles.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Dynamic Programming/unique_paths_with_obstacles.cpp diff --git a/Dynamic Programming/unique_paths_with_obstacles.cpp b/Dynamic Programming/unique_paths_with_obstacles.cpp new file mode 100644 index 00000000..01a9ce9b --- /dev/null +++ b/Dynamic Programming/unique_paths_with_obstacles.cpp @@ -0,0 +1,34 @@ +/* + You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. + + An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. + + Return the number of possible unique paths that the robot can take to reach the bottom-right corner. + + The testcases are generated so that the answer will be less than or equal to 2 * 109. + + Example 1: + Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] + Output: 2 + Explanation: There is one obstacle in the middle of the 3x3 grid above. + There are two ways to reach the bottom-right corner: + 1. Right -> Right -> Down -> Down + 2. Down -> Down -> Right -> Right +*/ + +class Solution { +public: + int uniquePathsWithObstacles(vector>& obstacleGrid) { + int m = obstacleGrid.size(), n = obstacleGrid[0].size(); + vector >dp(m + 1, vector (n + 1, 0)); + dp[0][1] = 1; + for(int i = 1; i<= m; i++){ + for(int j = 1; j <= n; j++){ + if(!obstacleGrid[i - 1][j - 1]){ + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + } + } + } + return dp[m][n]; + } +}; \ No newline at end of file From fd09810cb9af52a3f26a5433fc6d1619325a9ddb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 22:54:39 +0530 Subject: [PATCH 0238/1894] add find min in rotated sorted array --- .../minimum_in_rotated_sorted_array.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Binary Search/minimum_in_rotated_sorted_array.cpp diff --git a/Binary Search/minimum_in_rotated_sorted_array.cpp b/Binary Search/minimum_in_rotated_sorted_array.cpp new file mode 100644 index 00000000..3d68af73 --- /dev/null +++ b/Binary Search/minimum_in_rotated_sorted_array.cpp @@ -0,0 +1,55 @@ +/* + Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: + + [4,5,6,7,0,1,2] if it was rotated 4 times. + [0,1,2,4,5,6,7] if it was rotated 7 times. + Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. + + Given the sorted rotated array nums of unique elements, return the minimum element of this array. + + You must write an algorithm that runs in O(log n) time. + + Example 1: + Input: nums = [3,4,5,1,2] + Output: 1 + Explanation: The original array was [1,2,3,4,5] rotated 3 times. + + Example 2: + Input: nums = [4,5,6,7,0,1,2] + Output: 0 + Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. + + Example 3: + Input: nums = [11,13,15,17] + Output: 11 + Explanation: The original array was [11,13,15,17] and it was rotated 4 times. + + Constraints: + n == nums.length + 1 <= n <= 5000 + -5000 <= nums[i] <= 5000 + All the integers of nums are unique. + nums is sorted and rotated between 1 and n times. +*/ + +class Solution { +public: + int findMin(vector& nums) { + int n = nums.size(); + int start = 0, end = n - 1; + while(start <= end){ + int mid = start + (end - start) / 2; + int next = (mid + 1) % n; + int prev = (mid - 1 + n) % n; + if(nums[mid] <= nums[prev] && nums[mid] <= nums[next]) + return nums[mid]; + if(nums[mid] <= nums[end]){ + end = mid - 1; + } + else if(nums[mid] >= nums[start]){ + start = mid + 1; + } + } + return -1; + } +}; \ No newline at end of file From 85b637191bde8b28aa015092a1cf166e0e78927c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 23:35:16 +0530 Subject: [PATCH 0239/1894] add linked list pallindrome --- Linked List/linked_list_pallindrome.cpp | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Linked List/linked_list_pallindrome.cpp diff --git a/Linked List/linked_list_pallindrome.cpp b/Linked List/linked_list_pallindrome.cpp new file mode 100644 index 00000000..f1102d75 --- /dev/null +++ b/Linked List/linked_list_pallindrome.cpp @@ -0,0 +1,33 @@ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + bool isPalindrome(ListNode* head) { + vector contents; + while(head != NULL) { + int val = head->val; + contents.push_back(val); + head = head->next; + } + int low = 0, high = contents.size() - 1; + while(low <= high) { + if(contents[low] == contents[high]){ + low++; + high--; + } + else { + return false; + } + } + return true; + } +}; \ No newline at end of file From 8886e7d76b38860fe3faf1b4ff499b6eef634ebb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 23:36:15 +0530 Subject: [PATCH 0240/1894] add description --- Linked List/linked_list_pallindrome.cpp | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Linked List/linked_list_pallindrome.cpp b/Linked List/linked_list_pallindrome.cpp index f1102d75..c5a38ee5 100644 --- a/Linked List/linked_list_pallindrome.cpp +++ b/Linked List/linked_list_pallindrome.cpp @@ -1,4 +1,30 @@ +/* + Given the head of a singly linked list, return true if it is a + palindrome + or false otherwise. + + + Example 1: + + + Input: head = [1,2,2,1] + Output: true + Example 2: + + + Input: head = [1,2] + Output: false + + + Constraints: + + The number of nodes in the list is in the range [1, 105]. + 0 <= Node.val <= 9 + + + Follow up: Could you do it in O(n) time and O(1) space? +*/ /** * Definition for singly-linked list. * struct ListNode { @@ -9,6 +35,8 @@ * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ + +// TODO: Implement O(1) space class Solution { public: bool isPalindrome(ListNode* head) { From 0e0a2bc432c7e2abcdd9230ce3fb6db4f859493f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Feb 2023 23:37:19 +0530 Subject: [PATCH 0241/1894] add time and space complexity --- Linked List/linked_list_pallindrome.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Linked List/linked_list_pallindrome.cpp b/Linked List/linked_list_pallindrome.cpp index c5a38ee5..3f6b9611 100644 --- a/Linked List/linked_list_pallindrome.cpp +++ b/Linked List/linked_list_pallindrome.cpp @@ -36,7 +36,8 @@ * }; */ -// TODO: Implement O(1) space +// Time Complexity : O(n) Space Complexity: O(n) +// TODO: Implement O(n) Time and O(1) space solution class Solution { public: bool isPalindrome(ListNode* head) { From ad462989b37fd9eb3cef336cf444aed905ec94ad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:29:24 +0530 Subject: [PATCH 0242/1894] add power of two --- Bit Manipulation/power_of_2.cpp | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Bit Manipulation/power_of_2.cpp diff --git a/Bit Manipulation/power_of_2.cpp b/Bit Manipulation/power_of_2.cpp new file mode 100644 index 00000000..0b9572e3 --- /dev/null +++ b/Bit Manipulation/power_of_2.cpp @@ -0,0 +1,34 @@ +/* + Given an integer n, return true if it is a power of two. Otherwise, return false. + + An integer n is a power of two, if there exists an integer x such that n == 2x. + + Example 1: + Input: n = 1 + Output: true + Explanation: 20 = 1 + + Example 2: + Input: n = 16 + Output: true + Explanation: 24 = 16 + + Example 3: + Input: n = 3 + Output: false + + Constraints: + + -231 <= n <= 231 - 1 + + Follow up: Could you solve it without loops/recursion? + +*/ + + +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && !(n &(n - 1)); + } +}; \ No newline at end of file From fc0172bc3da2845019949423f10af8151df65ac8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:34:56 +0530 Subject: [PATCH 0243/1894] add numbers with even number of digits --- Arrays/number_with_even_number_of_digits.cpp | 41 ++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Arrays/number_with_even_number_of_digits.cpp diff --git a/Arrays/number_with_even_number_of_digits.cpp b/Arrays/number_with_even_number_of_digits.cpp new file mode 100644 index 00000000..5e37926c --- /dev/null +++ b/Arrays/number_with_even_number_of_digits.cpp @@ -0,0 +1,41 @@ +/* + Given an array nums of integers, return how many of them contain an even number of digits. + + Example 1: + Input: nums = [12,345,2,6,7896] + Output: 2 + + Explanation: + 12 contains 2 digits (even number of digits). + 345 contains 3 digits (odd number of digits). + 2 contains 1 digit (odd number of digits). + 6 contains 1 digit (odd number of digits). + 7896 contains 4 digits (even number of digits). + Therefore only 12 and 7896 contain an even number of digits. + + Example 2: + Input: nums = [555,901,482,1771] + Output: 1 + + Explanation: + Only 1771 contains an even number of digits. + + Constraints: + + 1 <= nums.length <= 500 + 1 <= nums[i] <= 105 +*/ + +class Solution { +public: + int findNumbers(vector& nums) { + int count = 0; + for(int num : nums){ + if(num > 9 && num < 100 ) + count++; + else if(num > 999 && num < 10000) + count++; + } + return count; + } +}; \ No newline at end of file From db9b2ec54d25adf9ed43d62fe0598426602f04ef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:37:31 +0530 Subject: [PATCH 0244/1894] remove duplicate --- .../subarrays_with_bitwise_or.java | 69 ------------------- 1 file changed, 69 deletions(-) delete mode 100644 Bit Manipulation/subarrays_with_bitwise_or.java diff --git a/Bit Manipulation/subarrays_with_bitwise_or.java b/Bit Manipulation/subarrays_with_bitwise_or.java deleted file mode 100644 index d1b84173..00000000 --- a/Bit Manipulation/subarrays_with_bitwise_or.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Problem Description - * Given an array B of length A with elements 1 or 0. Find the number of subarrays such that - * the bitwise OR of all the elements present in the subarray is 1. - * - * - * Problem Constraints - * 1 <= A <= 105 - * - * - * Input Format - * The first argument is a single integer A. - * The second argument is an integer array B. - * - * - * Output Format - * Return the number of subarrays with bitwise array 1. - * - * - * Example Input - * Input 1: - * A = 3 - * B = [1, 0, 1] - * Input 2: - * A = 2 - * B = [1, 0] - * - * - * Example Output - * Output 1: - * 5 - * Output2: - * 2 - * - * - * Example Explanation - * Explanation 1: - * The subarrays are :- [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] - * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 - * Explanation 2: - * The subarrays are :- [1], [0], [1, 0] - * Except the subarray [0] all the other subarrays has a Bitwise OR = 1 - */ - -package BitManipulation; - -public class subArrayWithBitwiseOR1 { - public static void main(String[] args) { - int[] array = {1, 0, 1}; - int n = 3; - int ans = solve(array, n); - System.out.println(ans); - } - public static int solve(int[] array, int len) { - // O(N) time | O(1) space - int possibleSubarraysWithThisIdx = 0; - int ans = 0; - - for (int i = 0; i < len; i++) { - int currentNum = array[i]; - if (currentNum == 1) - possibleSubarraysWithThisIdx = i + 1; - - ans += possibleSubarraysWithThisIdx; - } - - return ans; - } -} From 1639a1ae8e6b7082f2ca61a98783455420fc2c35 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:38:34 +0530 Subject: [PATCH 0245/1894] remove runner file --- Linked List/tempCodeRunnerFile.cpp | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Linked List/tempCodeRunnerFile.cpp diff --git a/Linked List/tempCodeRunnerFile.cpp b/Linked List/tempCodeRunnerFile.cpp deleted file mode 100644 index 0d12bb3c..00000000 --- a/Linked List/tempCodeRunnerFile.cpp +++ /dev/null @@ -1 +0,0 @@ - print_linked_list(head); From 287c6afe6feb77bd4454647d72353e3a88216fc9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:40:13 +0530 Subject: [PATCH 0246/1894] remove runner file --- Random Problems/tempCodeRunnerFile.cpp | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Random Problems/tempCodeRunnerFile.cpp diff --git a/Random Problems/tempCodeRunnerFile.cpp b/Random Problems/tempCodeRunnerFile.cpp deleted file mode 100644 index 7b90afb8..00000000 --- a/Random Problems/tempCodeRunnerFile.cpp +++ /dev/null @@ -1 +0,0 @@ -ans \ No newline at end of file From 35d409d5de5fdd419eff4eaf65ba8f5dd6065b16 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:40:23 +0530 Subject: [PATCH 0247/1894] rename file --- ...cters.go => longest_substring_without_repeating_characters.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Sliding Window/{longest-substring-without-repeating-characters.go => longest_substring_without_repeating_characters.go} (100%) diff --git a/Sliding Window/longest-substring-without-repeating-characters.go b/Sliding Window/longest_substring_without_repeating_characters.go similarity index 100% rename from Sliding Window/longest-substring-without-repeating-characters.go rename to Sliding Window/longest_substring_without_repeating_characters.go From 5d85e4758f51e25600388d10ab5c033a7a69f148 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:48:34 +0530 Subject: [PATCH 0248/1894] add unique integers that sum up to zero --- Math/unique_integers_that_sum_up_to_0.cpp | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/unique_integers_that_sum_up_to_0.cpp diff --git a/Math/unique_integers_that_sum_up_to_0.cpp b/Math/unique_integers_that_sum_up_to_0.cpp new file mode 100644 index 00000000..982fe3b0 --- /dev/null +++ b/Math/unique_integers_that_sum_up_to_0.cpp @@ -0,0 +1,43 @@ +/* + Given an integer n, return any array containing n unique integers such that they add up to 0. + + Example 1: + Input: n = 5 + Output: [-7,-1,1,3,4] + Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. + + Example 2: + Input: n = 3 + Output: [-1,0,1] + + Example 3: + Input: n = 1 + Output: [0] + + Constraints: + 1 <= n <= 1000 +*/ + +class Solution { +public: + vector sumZero(int n) { + int A[n]; + for(int i = 0; i < n; i++){ A[i] = 0; } + int start = 0; + int end = n - 1; + int i = 1; + // populate start and end with n and -n + while(start < end) { + A[start] = i; + A[end] = -i; + i++; + start++; + end--; + } + vector R; + for(int a: A){ + R.push_back(a); + } + return R; + } +}; \ No newline at end of file From 3b6f8f2aa9fe4f0d681931fd1014df901cc8fbb8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 22:58:46 +0530 Subject: [PATCH 0249/1894] add count negatives in sorted matrix --- .../count_negatives_in_sorted_matrix.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 2D Arrays/count_negatives_in_sorted_matrix.cpp diff --git a/2D Arrays/count_negatives_in_sorted_matrix.cpp b/2D Arrays/count_negatives_in_sorted_matrix.cpp new file mode 100644 index 00000000..27817bfb --- /dev/null +++ b/2D Arrays/count_negatives_in_sorted_matrix.cpp @@ -0,0 +1,39 @@ +/* + Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid. + + Example 1: + Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] + Output: 8 + Explanation: There are 8 negatives number in the matrix. + + Example 2: + Input: grid = [[3,2],[1,0]] + Output: 0 + + Constraints: + m == grid.length + n == grid[i].length + 1 <= m, n <= 100 + -100 <= grid[i][j] <= 100 + + Follow up: Could you find an O(n + m) solution? +*/ + +class Solution { +public: + int countNegatives(vector>& grid) { + int len = grid.size(), m = grid[0].size(); + int ans = 0; + int j = 0, i = len - 1; + while(j < m && i >= 0){ + if(grid[i][j] < 0){ + ans += (m - j); + i--; + } + else{ + j++; + } + } + return ans; + } +}; \ No newline at end of file From 4014400b2071f0a7edf3f9d96bbc2d89b7b0287c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Feb 2023 23:05:25 +0530 Subject: [PATCH 0250/1894] add matrix with diagonal sum --- 2D Arrays/matrix_diagonal_sum.cpp | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 2D Arrays/matrix_diagonal_sum.cpp diff --git a/2D Arrays/matrix_diagonal_sum.cpp b/2D Arrays/matrix_diagonal_sum.cpp new file mode 100644 index 00000000..cdc7948c --- /dev/null +++ b/2D Arrays/matrix_diagonal_sum.cpp @@ -0,0 +1,44 @@ +/* + Given a square matrix mat, return the sum of the matrix diagonals. + + Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. + + Example 1: + Input: mat = [[1,2,3], + [4,5,6], + [7,8,9]] + Output: 25 + Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 + Notice that element mat[1][1] = 5 is counted only once. + + Example 2: + Input: mat = [[1,1,1,1], + [1,1,1,1], + [1,1,1,1], + [1,1,1,1]] + Output: 8 + + Example 3: + Input: mat = [[5]] + Output: 5 + + Constraints: + n == mat.length == mat[i].length + 1 <= n <= 100 + 1 <= mat[i][j] <= 100 +*/ + +class Solution { +public: + int diagonalSum(vector>& mat) { + int len = mat.size(), sum = 0; + for(int i = 0; i < len; i++){ + sum += mat[i][i] + mat[i][len - 1 - i]; + } + // if length is odd then subtract mid element, because its added twice + if(len & 1){ + sum -= mat[len / 2][len / 2]; + } + return sum; + } +}; \ No newline at end of file From b566ceaebdb29dbdf3a8b665e9d1c3badcb81a6d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:47:06 +0530 Subject: [PATCH 0251/1894] add happy number in go --- Fast and Slow Pointers/happy_number.go | 58 ++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Fast and Slow Pointers/happy_number.go diff --git a/Fast and Slow Pointers/happy_number.go b/Fast and Slow Pointers/happy_number.go new file mode 100644 index 00000000..2186796e --- /dev/null +++ b/Fast and Slow Pointers/happy_number.go @@ -0,0 +1,58 @@ +/* +Write an algorithm to determine if a number num is happy. + +A happy number is a number defined by the following process: + +Starting with any positive integer, replace the number by the sum of the squares of its digits. +Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1 + +Those numbers for which this process ends in 1 are happy. +Return TRUE if num is a happy number, and FALSE if not. + +Sample Input : 4 +Output: False + +Sample Input : 19 +Output: True + +*/ + +package main + +import "fmt" + +// pow calculates the power of the given digit +func pow(digit int, power int) int { + res := 1 + for i := 0; i < power; i++ { + res = res * digit + } + return res +} + +// sumDigits is a helper function that calculates the sum of digits. +func sumDigits(number int) int { + totalSum := 0 + for number > 0 { + digit := number % 10 + number = number / 10 + totalSum += pow(digit, 2) + } + return totalSum +} + +func happyNumber(num int) bool { + slow := num + fast := sumDigits(num) + for fast != 1 && fast != slow { + slow = sumDigits(slow) + fast = sumDigits(sumDigits(fast)) + } + return fast == 1 +} + +func main() { + fmt.Println(happyNumber(4)) // false + fmt.Println(happyNumber(19)) // true + fmt.Println(happyNumber(100)) // true +} \ No newline at end of file From 1e971579b389cc650fbfb0cc62ab612051d2f3fa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:49:04 +0530 Subject: [PATCH 0252/1894] update link to happy number in readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cf0168b0..d5570e4f 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ The key idea is that the pointers start at the same location, but they move forw - Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) +- Happy Nuumber [Go](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Fast%20and%20Slow%20Pointers) - Pallindrome Linked List - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) From 541acad9f842e27034a56494ae17f17cc21adbf9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:50:03 +0530 Subject: [PATCH 0253/1894] fix name and link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d5570e4f..c354b31e 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The key idea is that the pointers start at the same location, but they move forw - Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) -- Happy Nuumber [Go](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Fast%20and%20Slow%20Pointers) +- Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) From d520dd0c75547f4698bdf6b50fb10e32620b9fdf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:51:11 +0530 Subject: [PATCH 0254/1894] move inside fast and slow pointers directory --- .../linked_floyds_cycle_detection.cpp | 0 .../linked_list_find_middle.py | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Linked List => Fast and Slow Pointers}/linked_floyds_cycle_detection.cpp (100%) rename {Linked List => Fast and Slow Pointers}/linked_list_find_middle.py (100%) diff --git a/Linked List/linked_floyds_cycle_detection.cpp b/Fast and Slow Pointers/linked_floyds_cycle_detection.cpp similarity index 100% rename from Linked List/linked_floyds_cycle_detection.cpp rename to Fast and Slow Pointers/linked_floyds_cycle_detection.cpp diff --git a/Linked List/linked_list_find_middle.py b/Fast and Slow Pointers/linked_list_find_middle.py similarity index 100% rename from Linked List/linked_list_find_middle.py rename to Fast and Slow Pointers/linked_list_find_middle.py From cb98f231970dc50f1290e813710ca4dc20d27bd4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:53:43 +0530 Subject: [PATCH 0255/1894] move inside fast and slow pointers directory --- .../linked_list_compute_midpoint.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Linked List => Fast and Slow Pointers}/linked_list_compute_midpoint.cpp (100%) diff --git a/Linked List/linked_list_compute_midpoint.cpp b/Fast and Slow Pointers/linked_list_compute_midpoint.cpp similarity index 100% rename from Linked List/linked_list_compute_midpoint.cpp rename to Fast and Slow Pointers/linked_list_compute_midpoint.cpp From 868fea9082dc17e52f55de1a25afd163177e8b7a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 00:54:36 +0530 Subject: [PATCH 0256/1894] update links for computing midpoint --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c354b31e..ed9e559b 100644 --- a/README.md +++ b/README.md @@ -44,8 +44,8 @@ The key idea is that the pointers start at the same location, but they move forw ## Practice problems for fast and slow pointers -- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) -- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) +- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) +- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) From 8d2088696e093b58757a88afaa6e8fe926aaaf18 Mon Sep 17 00:00:00 2001 From: Kushal Lahoti Date: Thu, 23 Feb 2023 08:16:53 +0530 Subject: [PATCH 0257/1894] Code for best time to buy and sell stock in Java --- .../best_time_to_buy_and_sell_stock.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Dynamic Programming/best_time_to_buy_and_sell_stock.java diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.java b/Dynamic Programming/best_time_to_buy_and_sell_stock.java new file mode 100644 index 00000000..fff05a3a --- /dev/null +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.java @@ -0,0 +1,18 @@ +class Solution { + public int maxProfit(int[] prices) { + int minElement = prices[0]; + int maxDiff = 0; + int size = prices.length; + for (int i = 0; i < size; i++){ + minElement = Math.min(prices[i], minElement); + maxDiff = Math.max(prices[i] - minElement, maxDiff); + } + return maxDiff; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] prices = {7, 1, 5, 3, 6, 4}; + System.out.println(solution.maxProfit(prices)); + } +} From 00ee0ab17136e3ea155b0b4794c27b17bb4cdb38 Mon Sep 17 00:00:00 2001 From: Kushal Lahoti Date: Thu, 23 Feb 2023 08:20:39 +0530 Subject: [PATCH 0258/1894] Code for best time to buy and sell stock in Python --- .../best_time_to_buy_and_sell_stock.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Dynamic Programming/best_time_to_buy_and_sell_stock.py diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py new file mode 100644 index 00000000..e96137f9 --- /dev/null +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -0,0 +1,11 @@ +def maxProfit(prices): + minElement = 10000 + maxDiff = 0 + for i in range(len(prices)): + minElement = min(prices[i], minElement) + maxDiff = max(prices[i]-minElement, maxDiff) + + return maxDiff + +prices = [7,1,5,3,6,4] +print(maxProfit(prices)) From 870862802899d45b31a278307838709174306a66 Mon Sep 17 00:00:00 2001 From: Kushal Lahoti Date: Thu, 23 Feb 2023 08:22:48 +0530 Subject: [PATCH 0259/1894] Code for best time to buy and sell stock in C++ --- .../best_time_to_buy_and_sell_stock.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Dynamic Programming/best_time_to_buy_and_sell_stock.cpp diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp new file mode 100644 index 00000000..533f0cc2 --- /dev/null +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -0,0 +1,23 @@ +#include +#include +#include +using namespace std; + +int maxProfit(vector& prices) +{ + int minElement = prices[0], maxDiff = 0; + for (int i = 1; i < prices.size(); i++) { + + minElement = min(minElement, prices[i]); + maxDiff = max(maxDiff, prices[i] - minElement); + } + return maxDiff; +} + +int main() +{ + vector prices = { 7, 1, 5, 3, 6, 4 }; + int maxProfitEarned = maxProfit(prices); + cout << maxProfitEarned << endl; + return 0; +} From e9aaf7ef31ce131a72ceecd5db2f3b84bbb28434 Mon Sep 17 00:00:00 2001 From: Rishabh Dixit <118468693+RishabhDixit1@users.noreply.github.com> Date: Thu, 23 Feb 2023 19:29:04 +0530 Subject: [PATCH 0260/1894] The file bubble_sort.java renamed as BubbleSort.java --- sorting/BubbleSort.java | 51 ++++++++++++++++++++++++++++++++++ sorting/bubble_sort.java | 59 ---------------------------------------- 2 files changed, 51 insertions(+), 59 deletions(-) create mode 100644 sorting/BubbleSort.java delete mode 100644 sorting/bubble_sort.java diff --git a/sorting/BubbleSort.java b/sorting/BubbleSort.java new file mode 100644 index 00000000..90088b91 --- /dev/null +++ b/sorting/BubbleSort.java @@ -0,0 +1,51 @@ +// Implementation of Bubble sort. +// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm +// that repeatedly steps through the input list element by element, +// comparing the current element with the one after it, swapping their values if needed. +// These passes through the list are repeated until no swaps had to be performed during a pass, +// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort + +// Time Complexity worst-case and average complexity O(n^{2}) +// Bubble sort is O(n) on a list that is already sorted i.e. Best case + +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] + + + + +package sorting; + +import java.util.Arrays; + +public class BubbleSort { + public static void main(String[] args) { + int[] nums = {4, 5, 6, 8, 17, 19, 45, -78, -87, 0, 11}; + bubble(nums); + System.out.println(Arrays.toString(nums)); + + + } + static void bubble(int[] arr){ + boolean swapped; + // run the steps n-1 times + for(int i = 0; i < arr.length; i++){ + swapped = false; + // for each step, max item will come at the last respective index + for(int j = 1; j < arr.length-i; j++){ + // swap if the item is smaller than the previous item + if (arr[j] > arr[j-1]){ + int temp = arr[j]; + arr[j] = arr[j-1]; + arr[j-1] = temp; + swapped = true; + } + } + // if you did not swap for a particular of i, it means the array is sorted hence stop the program + if(!swapped){ + break; + } + } + } +} + diff --git a/sorting/bubble_sort.java b/sorting/bubble_sort.java deleted file mode 100644 index 64892db3..00000000 --- a/sorting/bubble_sort.java +++ /dev/null @@ -1,59 +0,0 @@ -// Implementation of Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort - -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case - -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] - - - -package sorting; - -public class Bubblesort { - void bubblesort(int[] array) { - int size = array.length; - int temp = 0; - boolean flag = false; - - for(int i = 0; i < size; i++) { - for(int j = 1; j < (size - i); j++) { - if(array[j - 1] > array[j]) { - //swap elements - temp = array[j-1]; - array[j - 1] = array[j]; - array[j] = temp; - flag = true; - } - - } - if(!flag) { - System.out.println("Already sorted so no further redundant passes best case 0(n)"); - break; - } - } - } - - public static void main(String[] args) { - int[] array = {5, 1, 2, 3, 4, 5}; - - System.out.println("Array Before Bubble Sort"); - for (int j : array) { - System.out.print(j + " "); - } - System.out.println(); - Bubblesort is = new Bubblesort(); - is.bubblesort(array);//sorting array elements using bubble sort - - System.out.println("Array After Bubble Sort"); - for (int j : array) { - System.out.print(j + " "); - } - } - -} From 0f34963e7355e7340d4087b699d210b427331bb7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 22:17:57 +0530 Subject: [PATCH 0261/1894] rename file --- sorting/{BubbleSort.java => bubble_sort.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sorting/{BubbleSort.java => bubble_sort.java} (100%) diff --git a/sorting/BubbleSort.java b/sorting/bubble_sort.java similarity index 100% rename from sorting/BubbleSort.java rename to sorting/bubble_sort.java From bb82e405820b0e64954c9da03286f5e26758005f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 22:29:47 +0530 Subject: [PATCH 0262/1894] update readme with sorting algorithms --- README.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/README.md b/README.md index ed9e559b..20e5b8a6 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,26 @@ 🌈 Everyone is welcome! You can join the fun by following our [contributing](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) guide. +# Sorting + +Sorting a list of items into ascending or descending order can help either a human or a computer find items on that list quickly, perhaps using an algorithm like binary search. Most Programming languages have built-in sorting methods. It works on arrays of numbers, or even on arrays of strings: + +``` +heights = [6, 5, 4, 5, 2, 3]; +heights.sort(); +Output : [2, 3, 4, 5, 5, 6] +``` + +Even though languages have built-in sorting method, sorting is a great example of how there may be many ways to think about the same problem, some perhaps better than others. Understanding sorting is a traditional first step towards mastery of algorithms and computer science. + +### Well known sorting algorithms + +- Bubble Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.py) +- Insertion Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.py) +- Selection Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.py) +- Merge Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.py) +- Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 436589ffb3e49f31ad879e009ebaf9a7a99507c0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 22:33:07 +0530 Subject: [PATCH 0263/1894] update description --- sorting/insertion_sort.cpp | 19 +++++++++++++++++++ sorting/insertion_sort.java | 18 ++++++++++++++---- sorting/insertion_sort.js | 21 ++++++++++++++++++--- sorting/insertion_sort.py | 10 +++++++++- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 3dfc5ce2..050155d1 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,3 +1,22 @@ +/* +Implementation of insertion sort in C++. +Insertion sort is a simple sorting algorith that iterates through +the list starting at the second element. We compare each element +to the preceding elements, slide over the preceding larger (or smaller) +elements, and insert the original element into the empty position. + +Time Complexity worst-case and average complexity O(n^{2}) + +Insertion sort is inefficient for large arrays. However it is fast for +small arrays and typically more efficient than bubble sort and selection +sort due to not making as many comparisons on average. + +Source: https://en.wikipedia.org/wiki/Insertion_sort + +Sample input: [0, 2, 1,-1, 10, 3, 4] +Output: [-1 0 1 2 3 4 10] +*/ + #include using namespace std; diff --git a/sorting/insertion_sort.java b/sorting/insertion_sort.java index 8b915356..5ca92d88 100644 --- a/sorting/insertion_sort.java +++ b/sorting/insertion_sort.java @@ -1,11 +1,21 @@ -// Insertion sort in Java +/* +Implementation of insertion sort in Java. +Insertion sort is a simple sorting algorith that iterates through +the list starting at the second element. We compare each element +to the preceding elements, slide over the preceding larger (or smaller) +elements, and insert the original element into the empty position. -// Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. +Time Complexity worst-case and average complexity O(n^{2}) -// Time complexity = O(n^2) and Space complexity = O(1). +Insertion sort is inefficient for large arrays. However it is fast for +small arrays and typically more efficient than bubble sort and selection +sort due to not making as many comparisons on average. -// Sample input = [ 9, 5, 1, 4, 3] , Output = [1, 3, 4, 5, 9] +Source: https://en.wikipedia.org/wiki/Insertion_sort +Sample input: [0, 2, 1,-1, 10, 3, 4] +Output: [-1 0 1 2 3 4 10] +*/ import java.util.Arrays; diff --git a/sorting/insertion_sort.js b/sorting/insertion_sort.js index 12dedd54..c24b003f 100644 --- a/sorting/insertion_sort.js +++ b/sorting/insertion_sort.js @@ -1,7 +1,22 @@ -/* -Insertion sort is a sorting algorithm that places an unsorted element -at its suitable place in each iteration. +/* +Implementation of insertion sort in JS. +Insertion sort is a simple sorting algorith that iterates through +the list starting at the second element. We compare each element +to the preceding elements, slide over the preceding larger (or smaller) +elements, and insert the original element into the empty position. + +Time Complexity worst-case and average complexity O(n^{2}) + +Insertion sort is inefficient for large arrays. However it is fast for +small arrays and typically more efficient than bubble sort and selection +sort due to not making as many comparisons on average. + +Source: https://en.wikipedia.org/wiki/Insertion_sort + +Sample input: [0, 2, 1,-1, 10, 3, 4] +Output: [-1 0 1 2 3 4 10] */ + const inputArr = [4,5,67,56,3,35,45]; const insertionSort= (arr) => { diff --git a/sorting/insertion_sort.py b/sorting/insertion_sort.py index 05ea303c..005bf603 100644 --- a/sorting/insertion_sort.py +++ b/sorting/insertion_sort.py @@ -1,8 +1,16 @@ """ -Implementation of insertion sort in python. +Implementation of insertion sort in go. +Insertion sort is a simple sorting algorith that iterates through +the list starting at the second element. We compare each element +to the preceding elements, slide over the preceding larger (or smaller) +elements, and insert the original element into the empty position. Time Complexity worst-case and average complexity O(n^{2}) +Insertion sort is inefficient for large arrays. However it is fast for +small arrays and typically more efficient than bubble sort and selection +sort due to not making as many comparisons on average. + Source: https://en.wikipedia.org/wiki/Insertion_sort Sample input: [0, 2, 1,-1, 10, 3, 4] From 106d55a8cae00431edb06062e618edbd7ef99ec4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 22:36:14 +0530 Subject: [PATCH 0264/1894] update description --- sorting/bubble_sort.js | 50 ++++++++++++++++++++++------------------- sorting/merge_sort.java | 21 +++++++++++------ sorting/merge_sort.js | 23 +++++++++++++------ sorting/merge_sort.py | 17 +++++++++++++- 4 files changed, 73 insertions(+), 38 deletions(-) diff --git a/sorting/bubble_sort.js b/sorting/bubble_sort.js index 63c8fb0f..76232be3 100644 --- a/sorting/bubble_sort.js +++ b/sorting/bubble_sort.js @@ -1,29 +1,33 @@ -/* -Bubble sort is a sorting algorithm that compares two adjacent elements -and swaps them until they are in the intended order. -*/ +// Implementation of Bubble sort. +// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm +// that repeatedly steps through the input list element by element, +// comparing the current element with the one after it, swapping their values if needed. +// These passes through the list are repeated until no swaps had to be performed during a pass, +// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort -const inputArr = [4,5,67,56,3,35,45]; +// Time Complexity worst-case and average complexity O(n^{2}) +// Bubble sort is O(n) on a list that is already sorted i.e. Best case -const bubbleSort = (arr) => { - let len = arr.length; - - //loop to access each array element - for(let i = 0; i < len-1; i++) +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] - //loop to compare array elements - for(let j = i+1; j < len; j++) +const inputArr = [4, 5, 67, 56, 3, 35, 45]; - //compare two adjacent elements - if(arr[i] > arr[j]) - { - //swapping elements if elements are not in the intended order - let temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp +const bubbleSort = (arr) => { + let len = arr.length; - } - return arr; -} + //loop to access each array element + for (let i = 0; i < len - 1; i++) + //loop to compare array elements + for (let j = i + 1; j < len; j++) + //compare two adjacent elements + if (arr[i] > arr[j]) { + //swapping elements if elements are not in the intended order + let temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + return arr; +}; bubbleSort(inputArr); -console.log(inputArr); \ No newline at end of file +console.log(inputArr); diff --git a/sorting/merge_sort.java b/sorting/merge_sort.java index 8fc62dcc..71c34e40 100644 --- a/sorting/merge_sort.java +++ b/sorting/merge_sort.java @@ -1,13 +1,20 @@ -// Merge Sort in Java +// In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, +// and comparison-based sorting algorithm. Most implementations produce a stable sort, +// which means that the order of equal elements is the same in the input and output. +// Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. +// A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. +// Conceptually, a merge sort works as follows: -// Merge sort is a sorting algorithm that works by dividing an array into smaller subarrays, sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array. -// In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each half, and then merge the sorted halves back together. This process is repeated until the entire array is sorted. +// Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). +// Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list +// Source(https://en.wikipedia.org/wiki/Merge_sort) -// Time complexity = O(nlogn) and Space complexity = O(n). +// Approach: Divide by finding the number mid of the position midway between left and right. Do this step the same +// way we found the midpoint in binary search +// Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. +// That is, recursively sort the subarray Arr[left. . mid] and recursively sort the subarray Arr[mid + 1. . right]. +// Combine by merging the two sorted subarrays back into the single sorted subarray Arr[left. . right]. -// Sample input = [ 4, 6, 2, 1, 3, 5] , Output = [1, 2, 3, 4, 5, 6] - -// Link for further Reading : [https://www.geeksforgeeks.org/merge-sort/] class MergeSort { void mergeSort(int ar[], int p,int r){ diff --git a/sorting/merge_sort.js b/sorting/merge_sort.js index c768e95d..6d0746c4 100644 --- a/sorting/merge_sort.js +++ b/sorting/merge_sort.js @@ -1,15 +1,24 @@ -/* -Merge sort is a sorting algorithm that takes a list and divides the list into two smaller lists recursively until we are down to the pairs of arrays containing individual elements. +// In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, +// and comparison-based sorting algorithm. Most implementations produce a stable sort, +// which means that the order of equal elements is the same in the input and output. +// Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. +// A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. +// Conceptually, a merge sort works as follows: -At that point, the pairs are compared and are *merged* back together to form a sorted list, recursively popping off the stack until we're back to our final sorted array. -*/ +// Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). +// Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list +// Source(https://en.wikipedia.org/wiki/Merge_sort) + +// Approach: Divide by finding the number mid of the position midway between left and right. Do this step the same +// way we found the midpoint in binary search +// Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. +// That is, recursively sort the subarray Arr[left. . mid] and recursively sort the subarray Arr[mid + 1. . right]. +// Combine by merging the two sorted subarrays back into the single sorted subarray Arr[left. . right]. const inputArr = [4, 5, 67, 56, 3, 35, 45]; function mergeSort(arr) { - if (arr.length > 1) { - // splitting the list into two smaller lists const mid = Math.floor(arr.length / 2); const left = arr.slice(0, mid); @@ -56,4 +65,4 @@ function mergeSort(arr) { } mergeSort(inputArr); -console.log(inputArr); \ No newline at end of file +console.log(inputArr); diff --git a/sorting/merge_sort.py b/sorting/merge_sort.py index d406a046..cdc9672b 100644 --- a/sorting/merge_sort.py +++ b/sorting/merge_sort.py @@ -1,4 +1,19 @@ -# Time Complexity of O(nlogn) +# In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, +# and comparison-based sorting algorithm. Most implementations produce a stable sort, +# which means that the order of equal elements is the same in the input and output. +# Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. +# A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. +# Conceptually, a merge sort works as follows: + +# Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). +# Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list +# Source(https://en.wikipedia.org/wiki/Merge_sort) + +# Approach: Divide by finding the number mid of the position midway between left and right. Do this step the same +# way we found the midpoint in binary search +# Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. +# That is, recursively sort the subarray Arr[left. . mid] and recursively sort the subarray Arr[mid + 1. . right]. +# Combine by merging the two sorted subarrays back into the single sorted subarray Arr[left. . right]. def main(): # test for merge sort From 7f7e245abf14b791b842cb3260bcf706c885e36f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Feb 2023 22:37:05 +0530 Subject: [PATCH 0265/1894] update description --- sorting/selection_sort.java | 16 ++++++---- sorting/selection_sort.js | 61 +++++++++++++++++++------------------ sorting/selection_sort.py | 18 ++++++----- 3 files changed, 52 insertions(+), 43 deletions(-) diff --git a/sorting/selection_sort.java b/sorting/selection_sort.java index d70eabed..5540150c 100644 --- a/sorting/selection_sort.java +++ b/sorting/selection_sort.java @@ -1,9 +1,13 @@ -// Selection sort in Java -// Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list. - -// Time complexity = O(n^2) and Space complexity = O(n). - -// Sample input = [20, 12, 10, 15, 2] , Output = [2, 10, 12, 15, 20] +// Implementation of selection sort. +// Selection sort is an in-place comparison sorting algorithm. +// It has an O(n^{2}) time complexity which makes it inefficient on large lists, +// and generally performs worse than the similar insertion sort. +// Selection sort is noted for its simplicity and has performance advantages +// over more complicated algorithms in certain situations, +// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort + +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] import java.util.Arrays; diff --git a/sorting/selection_sort.js b/sorting/selection_sort.js index ce5d2bcd..e853183e 100644 --- a/sorting/selection_sort.js +++ b/sorting/selection_sort.js @@ -1,36 +1,39 @@ -/* -Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration - and places that element at the beginning of the unsorted list. -*/ +// Implementation of selection sort. +// Selection sort is an in-place comparison sorting algorithm. +// It has an O(n^{2}) time complexity which makes it inefficient on large lists, +// and generally performs worse than the similar insertion sort. +// Selection sort is noted for its simplicity and has performance advantages +// over more complicated algorithms in certain situations, +// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort -const inputArr = [4,5,67,56,3,35,45]; +// Sample Input : [2, 1, 9, 3, 5, 4, 0] +// Output : [0 1 2 3 4 5 9] +const inputArr = [4, 5, 67, 56, 3, 35, 45]; -const selectionSort= (inputArr) => { - let n = inputArr.length; - - //loop to access each array element - for(let i = 0; i < n; i++) { +const selectionSort = (inputArr) => { + let n = inputArr.length; - //assuming first array element as current minimum - let min= i; + //loop to access each array element + for (let i = 0; i < n; i++) { + //assuming first array element as current minimum + let min = i; - //loop to compare current minimum element to other array element - for(let j= i+1; j< n; j++){ - - //comparing and updating cureent minimum element - if(inputArr[j] < inputArr[min]) { - min=j; - } - } + //loop to compare current minimum element to other array element + for (let j = i + 1; j < n; j++) { + //comparing and updating cureent minimum element + if (inputArr[j] < inputArr[min]) { + min = j; + } + } - //swapping array elements if current minimum changes - if (min!= i) { - let temp= inputArr[i]; - inputArr[i] = inputArr[min]; - inputArr[min] = temp; - } + //swapping array elements if current minimum changes + if (min != i) { + let temp = inputArr[i]; + inputArr[i] = inputArr[min]; + inputArr[min] = temp; } - return inputArr; -} + } + return inputArr; +}; -console.log(selectionSort(inputArr)); \ No newline at end of file +console.log(selectionSort(inputArr)); diff --git a/sorting/selection_sort.py b/sorting/selection_sort.py index 6717d6c3..48f923f2 100644 --- a/sorting/selection_sort.py +++ b/sorting/selection_sort.py @@ -1,11 +1,13 @@ -# Selection sort in Python - -# Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list. - -# Time complexity = O(n^2) and Space complexity = O(n). - -# Sample input = [-2, 45, 0, 11, -9] , Output = [-9, -2, 0, 11, 45] - +# Implementation of selection sort. +# Selection sort is an in-place comparison sorting algorithm. +# It has an O(n^{2}) time complexity which makes it inefficient on large lists, +# and generally performs worse than the similar insertion sort. +# Selection sort is noted for its simplicity and has performance advantages +# over more complicated algorithms in certain situations, +# particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort + +# Sample Input : [2, 1, 9, 3, 5, 4, 0] +# Output : [0 1 2 3 4 5 9] def selectionSort(array, size): From d306d4e54fddb54ff0d7a14df4e21e69a1e02ae5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 00:07:48 +0530 Subject: [PATCH 0266/1894] add description --- .../best_time_to_buy_and_sell_stock.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp index 533f0cc2..a3be1898 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -1,3 +1,24 @@ +/* + You are given an array prices where prices[i] is the price of a given stock on the ith day. + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + Example 1: + Input: prices = [7,1,5,3,6,4] + Output: 5 + Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + + Example 2: + Input: prices = [7,6,4,3,1] + Output: 0 + Explanation: In this case, no transactions are done and the max profit = 0. + + Constraints: + 1 <= prices.length <= 105 + 0 <= prices[i] <= 104 +*/ + #include #include #include From 24d23dc082910120181dc28fd26cc3b03eb26bcc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 00:07:55 +0530 Subject: [PATCH 0267/1894] add description --- .../best_time_to_buy_and_sell_stock.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.java b/Dynamic Programming/best_time_to_buy_and_sell_stock.java index fff05a3a..2316d8c5 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.java +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.java @@ -1,3 +1,24 @@ +/* + You are given an array prices where prices[i] is the price of a given stock on the ith day. + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + Example 1: + Input: prices = [7,1,5,3,6,4] + Output: 5 + Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + + Example 2: + Input: prices = [7,6,4,3,1] + Output: 0 + Explanation: In this case, no transactions are done and the max profit = 0. + + Constraints: + 1 <= prices.length <= 105 + 0 <= prices[i] <= 104 +*/ + class Solution { public int maxProfit(int[] prices) { int minElement = prices[0]; From 56db8976768efb61d59827b781f7266a8397f434 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:22:15 +0530 Subject: [PATCH 0268/1894] add halves are alike --- Strings/halves_are_alike.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Strings/halves_are_alike.cpp diff --git a/Strings/halves_are_alike.cpp b/Strings/halves_are_alike.cpp new file mode 100644 index 00000000..c8fc99aa --- /dev/null +++ b/Strings/halves_are_alike.cpp @@ -0,0 +1,19 @@ + +class Solution { +public: + bool halvesAreAlike(string s) { + set X {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + int half = s.size() / 2; + int c = 0, d = 0; + for(int i = 0; i < half; i++){ + if(X.find(s[i]) != X.end()) + c++; + } + for(int i = half; i < s.size(); i++){ + if(X.find(s[i]) != X.end()){ + d++; + } + } + return c == d; + } +}; \ No newline at end of file From db4534b4d37fa7af251557e59c09f894d77129d2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:22:46 +0530 Subject: [PATCH 0269/1894] add description --- Strings/halves_are_alike.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Strings/halves_are_alike.cpp b/Strings/halves_are_alike.cpp index c8fc99aa..755bb392 100644 --- a/Strings/halves_are_alike.cpp +++ b/Strings/halves_are_alike.cpp @@ -1,4 +1,26 @@ +/* + You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. + Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. + + Return true if a and b are alike. Otherwise, return false. + + Example 1: + Input: s = "book" + Output: true + Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. + + Example 2: + Input: s = "textbook" + Output: false + Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. + Notice that the vowel o is counted twice. + + Constraints: + 2 <= s.length <= 1000 + s.length is even. + s consists of uppercase and lowercase letters. +*/ class Solution { public: bool halvesAreAlike(string s) { From 09c1e1d1ec33f4209b759e391fd56297ce10cc36 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:24:15 +0530 Subject: [PATCH 0270/1894] add comment --- Strings/halves_are_alike.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Strings/halves_are_alike.cpp b/Strings/halves_are_alike.cpp index 755bb392..e79cb0ce 100644 --- a/Strings/halves_are_alike.cpp +++ b/Strings/halves_are_alike.cpp @@ -21,16 +21,20 @@ s.length is even. s consists of uppercase and lowercase letters. */ + +// Approach: Count vowels in first and second half and return whether count is equal or not class Solution { public: bool halvesAreAlike(string s) { set X {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; int half = s.size() / 2; int c = 0, d = 0; + // count vowels in first half for(int i = 0; i < half; i++){ if(X.find(s[i]) != X.end()) c++; } + // count vowels in second half for(int i = half; i < s.size(); i++){ if(X.find(s[i]) != X.end()){ d++; From ad1c04bfe9a89049d3212abc806be3543d0815c1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:26:25 +0530 Subject: [PATCH 0271/1894] add count matches in tournament --- Strings/count_matches_in_tournament.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Strings/count_matches_in_tournament.cpp diff --git a/Strings/count_matches_in_tournament.cpp b/Strings/count_matches_in_tournament.cpp new file mode 100644 index 00000000..1dbcad90 --- /dev/null +++ b/Strings/count_matches_in_tournament.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int numberOfMatches(int n) { + int res = 0; + while(n > 1){ + if(n % 2 == 0){ + n = n / 2; + res += n; + } + if(n % 2 == 1){ + n = n / 2; + res += n; + n++; + } + } + return res; + } +}; \ No newline at end of file From 17965d47c31f273d689738eea18980d442922f61 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:27:01 +0530 Subject: [PATCH 0272/1894] add description --- Strings/count_matches_in_tournament.cpp | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Strings/count_matches_in_tournament.cpp b/Strings/count_matches_in_tournament.cpp index 1dbcad90..dc11b9ed 100644 --- a/Strings/count_matches_in_tournament.cpp +++ b/Strings/count_matches_in_tournament.cpp @@ -1,3 +1,32 @@ +/* + You are given an integer n, the number of teams in a tournament that has strange rules: + + If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. + If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. + Return the number of matches played in the tournament until a winner is decided. + + Example 1: + Input: n = 7 + Output: 6 + Explanation: Details of the tournament: + - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. + - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. + - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. + Total number of matches = 3 + 2 + 1 = 6. + + Example 2: + Input: n = 14 + Output: 13 + Explanation: Details of the tournament: + - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. + - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. + - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. + - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. + Total number of matches = 7 + 3 + 2 + 1 = 13. + + Constraints:\ + 1 <= n <= 200 +*/ class Solution { public: int numberOfMatches(int n) { From d1f961814272b085deb4861dd1008c3b8dc0129f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:29:01 +0530 Subject: [PATCH 0273/1894] add comment --- Strings/count_matches_in_tournament.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Strings/count_matches_in_tournament.cpp b/Strings/count_matches_in_tournament.cpp index dc11b9ed..a35c4846 100644 --- a/Strings/count_matches_in_tournament.cpp +++ b/Strings/count_matches_in_tournament.cpp @@ -27,6 +27,9 @@ Constraints:\ 1 <= n <= 200 */ + +// In case of even simply divide number by 2 ad add result +// In case of add simply divide number by 2 ad add result and increase n by 1 class Solution { public: int numberOfMatches(int n) { From c63efb48cecd250457509e5843d9fecd199ab452 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:32:48 +0530 Subject: [PATCH 0274/1894] add coin change --- Dynamic Programming/coin_change.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Dynamic Programming/coin_change.cpp diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp new file mode 100644 index 00000000..20a4cb47 --- /dev/null +++ b/Dynamic Programming/coin_change.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + int dp[amount + 1]; + dp[0] = 0; + for(int i = 1; i <= amount; i++) dp[i] = amount+1; + for(int i = 1; i <= amount; i++){ + for(int j = 0; j < coins.size(); j++){ + if(coins[j] <= i){ + dp[i] = min(dp[i], dp[i - coins[j]] + 1); + } + } + } + return dp[amount] > amount ? -1 : dp[amount]; + } +}; \ No newline at end of file From 427c61efc05a159c3af70ab5dbf75ce5fc11fd44 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:33:35 +0530 Subject: [PATCH 0275/1894] add description --- Dynamic Programming/coin_change.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index 20a4cb47..aa185421 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -1,3 +1,28 @@ +/* + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. + + Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. + + You may assume that you have an infinite number of each kind of coin. + + Example 1: + Input: coins = [1,2,5], amount = 11 + Output: 3 + Explanation: 11 = 5 + 5 + 1 + + Example 2: + Input: coins = [2], amount = 3 + Output: -1 + + Example 3: + Input: coins = [1], amount = 0 + Output: 0 + + Constraints: + 1 <= coins.length <= 12 + 1 <= coins[i] <= 231 - 1 + 0 <= amount <= 104 +*/ class Solution { public: int coinChange(vector& coins, int amount) { From 92bd44705409ad0db5b02f861e763e43073b61cb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:38:32 +0530 Subject: [PATCH 0276/1894] add count primes --- Math/count_primes.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Math/count_primes.cpp diff --git a/Math/count_primes.cpp b/Math/count_primes.cpp new file mode 100644 index 00000000..36a6b3a7 --- /dev/null +++ b/Math/count_primes.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int countPrimes(int n) { + if(n <= 1) return 0; + bool seive[n]; + for(int i = 0; i < n; i++) + seive[i] = true; + seive[0] = false; seive[1] = false; + for(int i = 2; i * i < n; i++){ + if(seive[i]){ + for(int j = i * i; j < n; j += i){ + seive[j] = false; + } + } + } + return count(seive, seive + n, true); + } +}; \ No newline at end of file From 0d5e9e201b52622e53151deb26b122c852ccb5a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:39:13 +0530 Subject: [PATCH 0277/1894] add description --- Math/count_primes.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Math/count_primes.cpp b/Math/count_primes.cpp index 36a6b3a7..63e4b911 100644 --- a/Math/count_primes.cpp +++ b/Math/count_primes.cpp @@ -1,3 +1,21 @@ +/* + Given an integer n, return the number of prime numbers that are strictly less than n. + + Example 1: + Input: n = 10 + Output: 4 + Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. + + Example 2: + Input: n = 0 + Output: 0 + + Example 3: + Input: n = 1 + Output: 0 + Constraints: + 0 <= n <= 5 * 106 +*/ class Solution { public: int countPrimes(int n) { From f235d74466b5784596d53eec9d707e51ca985a29 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:41:42 +0530 Subject: [PATCH 0278/1894] rearrange output --- Math/sieve_of_eratosthenes.cpp | 27 ++------------------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/Math/sieve_of_eratosthenes.cpp b/Math/sieve_of_eratosthenes.cpp index 9633d8c7..79b5a43b 100644 --- a/Math/sieve_of_eratosthenes.cpp +++ b/Math/sieve_of_eratosthenes.cpp @@ -7,31 +7,8 @@ // the remaining unmarked numbers are primes. Source(https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) // Sample INput: 100 -// Output : -// 3 -// 5 -// 7 -// 11 -// 13 -// 17 -// 19 -// 23 -// 29 -// 31 -// 37 -// 41 -// 43 -// 47 -// 53 -// 59 -// 61 -// 67 -// 71 -// 73 -// 79 -// 83 -// 89 -// 97 +// Output : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 + #include using namespace std; const int nmax = 100001; From 4a3829bf9bc597ecd85ff0823dd7d0995519d149 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Feb 2023 22:41:51 +0530 Subject: [PATCH 0279/1894] add description --- Math/count_primes.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Math/count_primes.cpp b/Math/count_primes.cpp index 63e4b911..75e25ef4 100644 --- a/Math/count_primes.cpp +++ b/Math/count_primes.cpp @@ -16,6 +16,8 @@ Constraints: 0 <= n <= 5 * 106 */ + +// Refer to Sieve Of Eratosthenes explanation under Math folder class Solution { public: int countPrimes(int n) { From 307f57d4e90058f47bfbd19d0c49751981b98b64 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Fri, 24 Feb 2023 16:09:13 -0500 Subject: [PATCH 0280/1894] Find Maximum in Sliding Window with Python. #761 --- .../Find Maximum in Sliding Window in Python | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Sliding Window/Find Maximum in Sliding Window in Python diff --git a/Sliding Window/Find Maximum in Sliding Window in Python b/Sliding Window/Find Maximum in Sliding Window in Python new file mode 100644 index 00000000..357eba8f --- /dev/null +++ b/Sliding Window/Find Maximum in Sliding Window in Python @@ -0,0 +1,18 @@ +from collections import deque + +def slidingWindowMax(arr,windowSize) -> list[int]: + dq=deque() + max_elements=[] + for i in range(len(arr)): + if(len(dq)!=0 and dq[0]== i-windowSize): + dq.popleft() + while(len(dq)!=0 and arr[dq[-1]]=windowSize-1): + max_elements.append(arr[dq[0]]) + return max_elements + +arr=list(map(int,input().split())) +windowSize=int(input()) +print(slidingWindowMax(arr,windowSize)) From eb612e5e0ccaeb99c088471baca5dddff13af5a3 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Fri, 24 Feb 2023 16:54:30 -0500 Subject: [PATCH 0281/1894] Created Graphs_dfs.py --- Graphs/Graphs_dfs.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Graphs/Graphs_dfs.py diff --git a/Graphs/Graphs_dfs.py b/Graphs/Graphs_dfs.py new file mode 100644 index 00000000..3dcf74fa --- /dev/null +++ b/Graphs/Graphs_dfs.py @@ -0,0 +1,33 @@ +from collections import defaultdict + +class Graph: + def __init__(self): + self.graph = defaultdict(list) + + def insertEdge(self,v1,v2): + self.graph[v1].append(v2) + + def dfsSub(self,v,visited): + + visited.add(v) + print(v,end=" ") + + for neighbour in self.graph[v]: + if neighbour not in visited: + self.dfsSub(neighbour,visited) + + def dfs(self,v): + + visited = set() + self.dfsSub(v,visited) + +g=Graph() +g.insertEdge(1,2) +g.insertEdge(2,1) +g.insertEdge(3,4) +g.insertEdge(4,5) +g.insertEdge(5,6) +g.insertEdge(2,6) + +g.dfs(2) + From a3a75de5d99582024b0732542d61c1811371f403 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Fri, 24 Feb 2023 17:09:37 -0500 Subject: [PATCH 0282/1894] Create Graph_bfs.py --- Graphs/Graphs_bfs.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Graphs/Graphs_bfs.py diff --git a/Graphs/Graphs_bfs.py b/Graphs/Graphs_bfs.py new file mode 100644 index 00000000..bc39ec56 --- /dev/null +++ b/Graphs/Graphs_bfs.py @@ -0,0 +1,35 @@ +from collections import defaultdict + +class Graph: + def __init__(self): + self.graph = defaultdict(list) + + def insertEdge(self,v1,v2): + self.graph[v1].append(v2) + + def subBfs(self,visited,queue): + while(queue): + v=queue.pop(0) + visited.add(v) + print(v,end=" ") + + for neighbour in self.graph[v]: + if neighbour not in visited: + queue.append(neighbour) + visited.add(neighbour) + + def bfs(self,v): + visited=set() + queue=[v] + self.subBfs(visited,queue) + +g=Graph() +g.insertEdge(1,2) +g.insertEdge(2,1) +g.insertEdge(2,3) +g.insertEdge(3,4) +g.insertEdge(4,5) +g.insertEdge(5,6) +g.insertEdge(2,6) + +g.bfs(1) From 093c96f4a6c0b7640db0339acb740bc58709073e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:26:28 +0530 Subject: [PATCH 0283/1894] add sliding window pattern intro in readme.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 20e5b8a6..5e93cac7 100644 --- a/README.md +++ b/README.md @@ -70,3 +70,13 @@ The key idea is that the pointers start at the same location, but they move forw - Pallindrome Linked List - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) + +# Pattern 3: Sliding Window + +The sliding window pattern is a computational method aimed at reducing the use of nested loops in an algorithm. It’s a variation of the two pointers pattern, where the pointers can be used to set window bounds. + +A window is a sublist formed over a part of an iterable data structure. It can be used to slide over the data in chunks corresponding to the window size. The sliding window pattern allows us to process the data in segments instead of the entire list. The segment or window size can be set according to the problem’s requirements. For example, if we have to find three consecutive integers with the largest sum in an array, we can set the window size to 3. This will allow us to process the data three elements at a time. + +Why is this method more efficient? It isn’t if, for each window, we iterate over all the elements of the window because that gives us the same O(kn) time complexity. + +Instead, what if we focused on the element entering the window and the one leaving it? For example, after calculating the sum of the first three elements, we move the window one step forward, subtract the element that is no longer in the window from the sum, and add the new element that has entered it. Next we check if the new sum is greater than the first. If it is, we update the max sum found so far. Now, each time we move the window forward, we perform at most four operations, reducing the time complexity to O(4n), that is, O(n). From 44c2f2213204585ccdad3c8791639f263adb4110 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:27:24 +0530 Subject: [PATCH 0284/1894] update intro --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5e93cac7..4d55e4c7 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,8 @@ The key idea is that the pointers start at the same location, but they move forw # Pattern 3: Sliding Window +The Sliding window is a problem-solving technique of data structure and algorithm for problems that apply arrays or lists. These problems are painless to solve using a brute force approach in O(n²) or O(n³). However, the Sliding window technique can reduce the time complexity to O(n). + The sliding window pattern is a computational method aimed at reducing the use of nested loops in an algorithm. It’s a variation of the two pointers pattern, where the pointers can be used to set window bounds. A window is a sublist formed over a part of an iterable data structure. It can be used to slide over the data in chunks corresponding to the window size. The sliding window pattern allows us to process the data in segments instead of the entire list. The segment or window size can be set according to the problem’s requirements. For example, if we have to find three consecutive integers with the largest sum in an array, we can set the window size to 3. This will allow us to process the data three elements at a time. From c0180d6f6c5ffbc145e818ecd318e036c3fbf489 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:29:02 +0530 Subject: [PATCH 0285/1894] update practice problems --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 4d55e4c7..011a5189 100644 --- a/README.md +++ b/README.md @@ -82,3 +82,10 @@ A window is a sublist formed over a part of an iterable data structure. It can b Why is this method more efficient? It isn’t if, for each window, we iterate over all the elements of the window because that gives us the same O(kn) time complexity. Instead, what if we focused on the element entering the window and the one leaving it? For example, after calculating the sum of the first three elements, we move the window one step forward, subtract the element that is no longer in the window from the sum, and add the new element that has entered it. Next we check if the new sum is greater than the first. If it is, we update the max sum found so far. Now, each time we move the window forward, we perform at most four operations, reducing the time complexity to O(4n), that is, O(n). + +## Practice problems for sliding window + +- Find Maximum in Sliding Window +- Minimum Window Subsequence +- Repeated DNA Sequences +- Minimum Window Substring From f925726f25611a662f6e2ba5234612f19539d40f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:31:39 +0530 Subject: [PATCH 0286/1894] update problem --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 011a5189..ceb013d3 100644 --- a/README.md +++ b/README.md @@ -89,3 +89,4 @@ Instead, what if we focused on the element entering the window and the one leavi - Minimum Window Subsequence - Repeated DNA Sequences - Minimum Window Substring +- Longest Substring without Repeating Characters From 3702a39750cc25686123784484c4fad5e1a79add Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:35:27 +0530 Subject: [PATCH 0287/1894] add merge interval pattern intro --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index ceb013d3..fa9a32b3 100644 --- a/README.md +++ b/README.md @@ -90,3 +90,11 @@ Instead, what if we focused on the element entering the window and the one leavi - Repeated DNA Sequences - Minimum Window Substring - Longest Substring without Repeating Characters + +# Pattern 4: Merge Interval + +The merge intervals pattern deals with problems involving overlapping intervals. Each interval is represented by a start and an end time. For example, an interval of [10,20] seconds means that the interval starts at 10 seconds and ends at 20seconds, such that both 10 and time 20 are included in the interval. + +The most common problems solved using this pattern are scheduling problems. + +The key to understanding this pattern and exploiting its power lies in understanding how any two intervals may overlap. From fae38907dadf14deb77eb0788e7b3a254d0d0c29 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:36:27 +0530 Subject: [PATCH 0288/1894] update example --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index fa9a32b3..821632c9 100644 --- a/README.md +++ b/README.md @@ -98,3 +98,11 @@ The merge intervals pattern deals with problems involving overlapping intervals. The most common problems solved using this pattern are scheduling problems. The key to understanding this pattern and exploiting its power lies in understanding how any two intervals may overlap. + +Many problems in the real world use the merge intervals pattern. Let’s look at some examples. + +- Display busy schedule: Display the busy hours of a user to other users without revealing the individual meeting slots in a calendar. + +- Schedule a new meeting: Add a new meeting to the tentative meeting schedule of a user in such a way that no two meetings overlap each other. + +- Task scheduling in operating systems (OS): Schedule tasks for the OS based on task priority and the free slots in the machine’s processing schedule. From baa1e9ba8c5a3606e02a674188c50e3152049f73 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:37:49 +0530 Subject: [PATCH 0289/1894] update problem list --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 821632c9..79fc2d57 100644 --- a/README.md +++ b/README.md @@ -106,3 +106,11 @@ Many problems in the real world use the merge intervals pattern. Let’s look at - Schedule a new meeting: Add a new meeting to the tentative meeting schedule of a user in such a way that no two meetings overlap each other. - Task scheduling in operating systems (OS): Schedule tasks for the OS based on task priority and the free slots in the machine’s processing schedule. + +## Practice problems for merge intervals + +- Merge Intervals +- Insert Interval +- Interval List Intersections +- Employee Free Time +- Meeting Rooms From 49a7f5c9e6de91647fdeca8045edecd9cde2ba74 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:41:22 +0530 Subject: [PATCH 0290/1894] update readme.md with In-place Reversal of a Linked List: Introduction pattern --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 79fc2d57..44d8ae24 100644 --- a/README.md +++ b/README.md @@ -114,3 +114,16 @@ Many problems in the real world use the merge intervals pattern. Let’s look at - Interval List Intersections - Employee Free Time - Meeting Rooms + +# Pattern 5: In-place Reversal of a Linked List: Introduction + +The in-place reversal of a linked list pattern allows us to reverse a linked list without any additional memory, using only the given nodes. + +Many problems require a reversal of a set of nodes in a linked list without using additional memory. In such cases, using the in-place reversal pattern is the simplest solution. Instead of making a new linked list with reversed links, we can do it in place, without using additional memory. + +How can we achieve an in-place reversal of nodes? We iterate in a linked list and keep track of the current node, the next node, and the previous node simultaneously. Keeping track of the nodes allows us to easily change the links between them and make them point to a different node than before. + +When solving such problems, the naive approach of iterating the linked list using nested loops takes O(n²) time. However, using the in-place reversal pattern, the time complexity is O(n) +time, since we use a single loop to iterate the linked list. + +Similarly, for space complexity: the naive approach requires the use of additional memory—if a linked list contains thousands of nodes, we’d need to allocate a lot of additional memory resources to solve the problem. However, the in-place reversal of a linked pattern will use only O(1) space. From e1d5b10047a2947758726733ebce00a773b3e8f0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:43:37 +0530 Subject: [PATCH 0291/1894] update problem list --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 44d8ae24..e1f94853 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ Many problems in the real world use the merge intervals pattern. Let’s look at - Employee Free Time - Meeting Rooms -# Pattern 5: In-place Reversal of a Linked List: Introduction +# Pattern 5: In-place Reversal of a Linked List The in-place reversal of a linked list pattern allows us to reverse a linked list without any additional memory, using only the given nodes. @@ -127,3 +127,11 @@ When solving such problems, the naive approach of iterating the linked list usin time, since we use a single loop to iterate the linked list. Similarly, for space complexity: the naive approach requires the use of additional memory—if a linked list contains thousands of nodes, we’d need to allocate a lot of additional memory resources to solve the problem. However, the in-place reversal of a linked pattern will use only O(1) space. + +## Practice problems for in-place reversal of a linked list + +- Reverse Linked List +- Reverse Nodes in k-group +- Reorder List +- Swapping Nodes in a Linked List +- Swapping Nodes in Ppairs From 79783ad5ffa39ad8153b3bb06f8d7d05bad8d308 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:44:16 +0530 Subject: [PATCH 0292/1894] update problem --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e1f94853..11e74a84 100644 --- a/README.md +++ b/README.md @@ -134,4 +134,5 @@ Similarly, for space complexity: the naive approach requires the use of addition - Reverse Nodes in k-group - Reorder List - Swapping Nodes in a Linked List -- Swapping Nodes in Ppairs +- Swapping Nodes in Pairs +- reverse Nodes in Even Length Groups From df878e3f836b6ac07a3eba16de3e19e4810e8fe1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:47:01 +0530 Subject: [PATCH 0293/1894] add Two heaps pattern in readme.m --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 11e74a84..9220fe28 100644 --- a/README.md +++ b/README.md @@ -135,4 +135,14 @@ Similarly, for space complexity: the naive approach requires the use of addition - Reorder List - Swapping Nodes in a Linked List - Swapping Nodes in Pairs -- reverse Nodes in Even Length Groups +- Reverse Nodes in Even Length Groups + +# Pattern 5: Two Heaps + +As the name suggests, the two heaps pattern uses either two min-heaps, two max-heaps, or a min-heap and a max-heap simultaneously to solve the problem. + +Given that there are n elements in a heap, it takes O(log n) time to insert an element in it, O(log n) time to remove an element from it, and O(1) time to access the element at the root of the heap. The root stores the smallest element in the case of a min-heap and the largest element in a max-heap. + +In some problems, we’re given a set of data such that it can be divided into two parts. We can either use the first part to find the smallest element using the min-heap and the second part to find the largest element using the max-heap, or we can do the reverse and use the first part to find the largest element using the max-heap and the second part to find the smallest element using the min-heap. + +There might be cases where we need to find the two largest numbers from two different data sets. We’ll use two max-heaps to store two different data sets in that case. In other cases, we might need to find the two smallest numbers from two different data sets, and then we would use two min-heaps. From 3b4fc884ed9aa6f4778ffeec91cecac33ee188dd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:47:38 +0530 Subject: [PATCH 0294/1894] update example for two heaps --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 9220fe28..ed965dbd 100644 --- a/README.md +++ b/README.md @@ -146,3 +146,9 @@ Given that there are n elements in a heap, it takes O(log n) time to insert an e In some problems, we’re given a set of data such that it can be divided into two parts. We can either use the first part to find the smallest element using the min-heap and the second part to find the largest element using the max-heap, or we can do the reverse and use the first part to find the largest element using the max-heap and the second part to find the smallest element using the min-heap. There might be cases where we need to find the two largest numbers from two different data sets. We’ll use two max-heaps to store two different data sets in that case. In other cases, we might need to find the two smallest numbers from two different data sets, and then we would use two min-heaps. + +Many problems in the real world use the two heaps pattern. Let’s look at some examples. + +- Video streaming: During a user session, there is often a possibility that packet drops and buffering might occur. We want to record the median number of buffering events that might occur in a particular session, which could then be used to improve the user experience. + +- Netflix: As part of a demographic study, we’re interested in the median age of our viewers. We want to implement a functionality whereby the median age can be updated efficiently whenever a new user signs up for video streaming. From b093766a1fa37bea49002666b4964b196a469ee6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:48:55 +0530 Subject: [PATCH 0295/1894] update example problems --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index ed965dbd..6b30cab5 100644 --- a/README.md +++ b/README.md @@ -152,3 +152,9 @@ Many problems in the real world use the two heaps pattern. Let’s look at some - Video streaming: During a user session, there is often a possibility that packet drops and buffering might occur. We want to record the median number of buffering events that might occur in a particular session, which could then be used to improve the user experience. - Netflix: As part of a demographic study, we’re interested in the median age of our viewers. We want to implement a functionality whereby the median age can be updated efficiently whenever a new user signs up for video streaming. + +## Practice problems for two heaps + +- Maximize Capital +- Find Median from a data stream +- Schedule Tasks on a minimum machines From 5ccac4999a69a203eff47736f6baf19019735dd2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:49:09 +0530 Subject: [PATCH 0296/1894] update example problems --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b30cab5..e68f32a9 100644 --- a/README.md +++ b/README.md @@ -157,4 +157,4 @@ Many problems in the real world use the two heaps pattern. Let’s look at some - Maximize Capital - Find Median from a data stream -- Schedule Tasks on a minimum machines +- Schedule Tasks on minimum machines From 6a0eb2dce978ebd92d303fecec1a4ae9adc873c6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Feb 2023 22:50:27 +0530 Subject: [PATCH 0297/1894] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e68f32a9..26a8cfe7 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ Similarly, for space complexity: the naive approach requires the use of addition - Swapping Nodes in Pairs - Reverse Nodes in Even Length Groups -# Pattern 5: Two Heaps +# Pattern 6: Two Heaps As the name suggests, the two heaps pattern uses either two min-heaps, two max-heaps, or a min-heap and a max-heap simultaneously to solve the problem. From 02af35827d06f9f9d810bda94a791892001081df Mon Sep 17 00:00:00 2001 From: LalitAswal Date: Sun, 26 Feb 2023 02:01:55 +0530 Subject: [PATCH 0298/1894] added valid pallindrome2 704 --- Strings/valid_pallindrome2.js | 45 +++++++++++++++++++++++++++++++++++ Strings/valid_pallindrome2.py | 37 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 Strings/valid_pallindrome2.js create mode 100644 Strings/valid_pallindrome2.py diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js new file mode 100644 index 00000000..892681f5 --- /dev/null +++ b/Strings/valid_pallindrome2.js @@ -0,0 +1,45 @@ +/* +Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + +Constraints: + string.length + The string only consists of English letters + +Sample Input : "madame" +Output : True + +Sample Input : "masdasd" +Output : False +*/ + +// using two-pointer Technique +function validPalindrome(s) { + let left = 0; + let right = s.length - 1; + + while (left < right) { + if (s[left] !== s[right]) { + // to check if deleting from either left or right char. would create a palindrome + return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); + } + left++; + right--; + } + + return true; + } + +function isPalindrome(s, left, right) { + while (left < right) { + if (s[left] !== s[right]) { + return false; + } + left++; + right--; + } + return true; +} + +console.log(validPalindrome("aba")); // true +console.log(validPalindrome("abca")); // true +console.log(validPalindrome("abc")); // false \ No newline at end of file diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py new file mode 100644 index 00000000..77c4d275 --- /dev/null +++ b/Strings/valid_pallindrome2.py @@ -0,0 +1,37 @@ +# Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + +# Constraints: +# string.length +# The string only consists of English letters + +# Sample Input : "madame" +# Output : True + +# Sample Input : "masdasd" +# Output : False + + +# using two-pointer Technique +def valid_palindrome(s: str) -> bool: + left, right = 0, len(s) - 1 + + while left < right: + if s[left] != s[right]: + # Check if deleting either left or right char will create a palindrome + return is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1) + left += 1 + right -= 1 + + return True + +def is_palindrome(s: str, left: int, right: int) -> bool: + while left < right: + if s[left] != s[right]: + return False + left += 1 + right -= 1 + return True + +print(valid_palindrome("aba")) # True +print(valid_palindrome("abca")) # True +print(valid_palindrome("abc")) # False \ No newline at end of file From 1d9ee3ff04033f01d51c5f087b1f0073c97c4ed2 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sat, 25 Feb 2023 15:53:14 -0500 Subject: [PATCH 0299/1894] Create Valid_Palindrome_II.py --- Recursion/Valid_Palindrome_II.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Recursion/Valid_Palindrome_II.py diff --git a/Recursion/Valid_Palindrome_II.py b/Recursion/Valid_Palindrome_II.py new file mode 100644 index 00000000..c70a9052 --- /dev/null +++ b/Recursion/Valid_Palindrome_II.py @@ -0,0 +1,18 @@ +class Solution: + def subPalindrome(self,s,low,high,count): + if(low>high): + return True + if(count>1): + return False + if(s[low]!=s[high]): + return Solution.subPalindrome(self,s,low+1,high,count+1) or Solution.subPalindrome(self,s,low,high-1,count+1) + else: + return Solution.subPalindrome(self,s,low+1,high-1,count) + + def validPalindrome(self, s: str) -> bool: + if(s==s[::-1]): + return True + return Solution.subPalindrome(self,s,0,len(s)-1,0) + +print(Solution().validPalindrome("ebcbbececabbacecbbcbe")) +print(Solution().validPalindrome("cdbeeeabddddbaeedebdc")) From fec4a9da4812c8a3347d1f9b01f64637b033af5e Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sat, 25 Feb 2023 17:22:38 -0500 Subject: [PATCH 0300/1894] Create Linkedlist_remove_nth_node_from_end.py --- .../linkedlist_remove_nth_node_from_end.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Linked List/linkedlist_remove_nth_node_from_end.py diff --git a/Linked List/linkedlist_remove_nth_node_from_end.py b/Linked List/linkedlist_remove_nth_node_from_end.py new file mode 100644 index 00000000..d814e50a --- /dev/null +++ b/Linked List/linkedlist_remove_nth_node_from_end.py @@ -0,0 +1,16 @@ +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + dummy_header = ListNode('*') + dummy_header.next=head + slow = dummy_header + fast = dummy_header + + for _ in range(1,n+2): + fast=fast.next + + while(fast!=None): + slow = slow.next + fast = fast.next + + slow.next = slow.next.next + return dummy_header.next From 509e5c87c088290db50518e76944827df26923cf Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sat, 25 Feb 2023 17:48:29 -0500 Subject: [PATCH 0301/1894] Create BinarySearch_sorted_2d_matrix.py --- .../BinarySearch_sorted_2d_matrix.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Binary Search/BinarySearch_sorted_2d_matrix.py diff --git a/Binary Search/BinarySearch_sorted_2d_matrix.py b/Binary Search/BinarySearch_sorted_2d_matrix.py new file mode 100644 index 00000000..4ac7da8d --- /dev/null +++ b/Binary Search/BinarySearch_sorted_2d_matrix.py @@ -0,0 +1,25 @@ +class Solution: + def __init__(self): + self.index = -1 + def binarySearch(self,arr,low,high,key): + if(low>high): + return self.index + mid=(low+high)//2 + if(arr[mid]>key): + return Solution.binarySearch(self,arr,low,mid-1,key) + elif(arr[mid] bool: + n = len(matrix[0]) + m = len(matrix) + + arr = [matrix[i][0] for i in range(m)] + ind1 = Solution.binarySearch(self,arr,0,m-1,target) + self.index=-1 + ind2 = Solution.binarySearch(self,matrix[ind1],0,n-1,target) + if(matrix[ind1][ind2] == target): + return True + return False From 03675232d18c6ae1cac1487bb76aafd5423c05ca Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:38:22 +0530 Subject: [PATCH 0302/1894] add k-way merge --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 26a8cfe7..21e6e88c 100644 --- a/README.md +++ b/README.md @@ -158,3 +158,15 @@ Many problems in the real world use the two heaps pattern. Let’s look at some - Maximize Capital - Find Median from a data stream - Schedule Tasks on minimum machines + +# Pattern 7: K-way Merge + +The k-way merge pattern helps to solve problems involving a list of sorted arrays. + +Here is what the pattern looks like: + +1. Insert the first element of each array in a min-heap. +2. Next, remove the smallest element from the heap and add it to the merged array. +3. Keep track of which array each element comes from. +4. Then, insert the next element of the same array into the heap. +5. Repeat steps 2 to 4 to fill the merged array in sorted order. From edba0fb830a701a6c303f751e878d0dd91fe7253 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:40:58 +0530 Subject: [PATCH 0303/1894] add example --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 21e6e88c..1fc3abf7 100644 --- a/README.md +++ b/README.md @@ -170,3 +170,9 @@ Here is what the pattern looks like: 3. Keep track of which array each element comes from. 4. Then, insert the next element of the same array into the heap. 5. Repeat steps 2 to 4 to fill the merged array in sorted order. + +Many problems in the real world use the k-way merge pattern. Let’s look at some examples. + +- Merge tweets in twitter feed: Sometimes we need to implement a module that adds a user’s Tweets into an already populated Twitter feed in chronological order. + +- Used in external sorting procedures: When an algorithm is processing huge amounts of data, it needs to repeatedly fetch it from external storage because RAM capacity is fixed. To overcome the speed limitation of external storage, k-way merges are used in external sorting. Let’s consider a case where we need to perform six merges. A binary merge requires three merge passes while a 6-way merge only requires one pass. K-way merge reduces the number of accesses to external storage, which in turn greatly improves performance when dealing with large amounts of data. From 32b2c0e3c671467866d5215e1d2d09712041a44b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:43:36 +0530 Subject: [PATCH 0304/1894] add example problems --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 1fc3abf7..2254f7d8 100644 --- a/README.md +++ b/README.md @@ -176,3 +176,10 @@ Many problems in the real world use the k-way merge pattern. Let’s look at som - Merge tweets in twitter feed: Sometimes we need to implement a module that adds a user’s Tweets into an already populated Twitter feed in chronological order. - Used in external sorting procedures: When an algorithm is processing huge amounts of data, it needs to repeatedly fetch it from external storage because RAM capacity is fixed. To overcome the speed limitation of external storage, k-way merges are used in external sorting. Let’s consider a case where we need to perform six merges. A binary merge requires three merge passes while a 6-way merge only requires one pass. K-way merge reduces the number of accesses to external storage, which in turn greatly improves performance when dealing with large amounts of data. + +## Practice problems for k-way Merge + +- Merge Sorted Array +- Kth smallest number in M sorted list +- Find K pairs with smallest sums +- Merge K sorted lists From 3893ffc94606a78733c46f56eebce00210fe8f90 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:45:06 +0530 Subject: [PATCH 0305/1894] update problem list --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2254f7d8..676a7005 100644 --- a/README.md +++ b/README.md @@ -183,3 +183,5 @@ Many problems in the real world use the k-way merge pattern. Let’s look at som - Kth smallest number in M sorted list - Find K pairs with smallest sums - Merge K sorted lists +- Kth Smallest element in a sorted matrix +- Median of two sorted arrays From da4ebf4e7a9467a18ce327b4807d32a1c9514717 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:51:40 +0530 Subject: [PATCH 0306/1894] add top k elements pattern --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index 676a7005..dc0e1047 100644 --- a/README.md +++ b/README.md @@ -185,3 +185,18 @@ Many problems in the real world use the k-way merge pattern. Let’s look at som - Merge K sorted lists - Kth Smallest element in a sorted matrix - Median of two sorted arrays + +# Pattern 8: Top K Elements + +The top K elements pattern helps find some specific k number of elements from the given data with optimum time complexity. Many problems ask us to find the top, the smallest, or the most/least frequent k elements in an unsorted list of elements. To solve such problems, sorting the list takes O(nlog(n)) time, then finding the k elements takes O(k) time. However, the top k elements pattern can allow us to solve the problem using O(n logk) time without sorting the list first. + +Which data structure can we use to solve such problems? The best data structure to keep track of the smallest or largest k elements is heap. With this pattern, we either use a max-heap or a min-heap to find the smallest or largest k elements, respectively. + +For example, let’s look at how this pattern takes steps to solve the problem of finding the top k largest elements (using min-heap) or top k smallest elements (using max-heap): +Insert the first k elements from the given set of elements to the min-heap or max-heap. + +Iterate through the rest of the elements. + +For min-heap, if you find the larger element, remove the top (smallest number) of the min-heap and insert the new larger element. +For max-heap, if you find the smaller element, remove the top (largest number) of the max-heap and insert the new smaller element. +Iterating the complete list takes O(n) time, and the heap takes O(logk) time for insertion. However, we get the O(1) access to the k elements using the heap. From f9b9e198c9543cd72425a6072d88a40f0399ff9d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:53:12 +0530 Subject: [PATCH 0307/1894] update example --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index dc0e1047..9c380b32 100644 --- a/README.md +++ b/README.md @@ -200,3 +200,9 @@ Iterate through the rest of the elements. For min-heap, if you find the larger element, remove the top (smallest number) of the min-heap and insert the new larger element. For max-heap, if you find the smaller element, remove the top (largest number) of the max-heap and insert the new smaller element. Iterating the complete list takes O(n) time, and the heap takes O(logk) time for insertion. However, we get the O(1) access to the k elements using the heap. + +Many problems in the real world use the top K elements pattern. Let’s look at some examples. + +- Uber: Select at least the n nearest drivers within the user’s vicinity, avoiding the drivers that are too far away. + +- Stocks: Given the set of IDs of brokers, determine the top K broker’s performance with the frequently repeated IDs in the given data set. From 6fbb7b3b4dfbb1df9fe32b1690dfda88b58aa372 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:56:03 +0530 Subject: [PATCH 0308/1894] dd example problems --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 9c380b32..5eb4b542 100644 --- a/README.md +++ b/README.md @@ -206,3 +206,10 @@ Many problems in the real world use the top K elements pattern. Let’s look at - Uber: Select at least the n nearest drivers within the user’s vicinity, avoiding the drivers that are too far away. - Stocks: Given the set of IDs of brokers, determine the top K broker’s performance with the frequently repeated IDs in the given data set. + +## Practice problems for Top K Elements + +- Kth largest element in a stream +- Reorganize string +- K closest point to origin +- Top K frequent element From c9464c343f1f7ebc785e84f1d2b0906930ce04f5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Feb 2023 21:56:53 +0530 Subject: [PATCH 0309/1894] update problems --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5eb4b542..ecb58e78 100644 --- a/README.md +++ b/README.md @@ -213,3 +213,5 @@ Many problems in the real world use the top K elements pattern. Let’s look at - Reorganize string - K closest point to origin - Top K frequent element +- Kth largest element in an array +- Kth smallest element in an BST From d77db2add94fdb9990fa2ad70b45345189a70bf1 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Sun, 26 Feb 2023 22:53:18 +0530 Subject: [PATCH 0310/1894] added the solution of sliding window in java --- .../Find Maximum in Sliding Window in Java | 58 +++++++++++++++++++ data-structures-and-algorithms.iml | 18 ++++++ 2 files changed, 76 insertions(+) create mode 100644 Sliding Window/Find Maximum in Sliding Window in Java create mode 100644 data-structures-and-algorithms.iml diff --git a/Sliding Window/Find Maximum in Sliding Window in Java b/Sliding Window/Find Maximum in Sliding Window in Java new file mode 100644 index 00000000..3c46fecb --- /dev/null +++ b/Sliding Window/Find Maximum in Sliding Window in Java @@ -0,0 +1,58 @@ +import java.util.*; + +public class SlidingWindowMax { + public static int[] findMaxSlidingWindow(int[] nums, int windowSize) { + if (nums == null || windowSize <= 0 || nums.length < windowSize) { + return new int[0]; + } + + int n = nums.length; + int[] result = new int[n - windowSize + 1]; + Deque deque = new ArrayDeque<>(); // deque stores the indices of elements in the window + + // process the first window separately + for (int i = 0; i < windowSize; i++) { + while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) { + deque.removeLast(); + } + deque.addLast(i); + } + result[0] = nums[deque.peekFirst()]; + + // process the remaining windows + for (int i = windowSize; i < n; i++) { + while (!deque.isEmpty() && deque.peekFirst() <= i - windowSize) { + deque.removeFirst(); // remove elements outside the window + } + while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) { + deque.removeLast(); // remove elements smaller than nums[i] + } + deque.addLast(i); + result[i - windowSize + 1] = nums[deque.peekFirst()]; + } + + return result; + } + + public static void main(String[] args) { + int[] nums = {1, 3, -1, -3, 5, 3, 6, 7}; + int windowSize = 3; + + int[] maxInWindow = findMaxSlidingWindow(nums, windowSize); + + System.out.println("Max values in sliding window of size " + windowSize + ": "); + for (int i = 0; i < maxInWindow.length; i++) { + System.out.print(maxInWindow[i] + " "); + } + } +} + +---------------Explanation--------------------- + +This program defines a findMaxSlidingWindow method that takes an array nums and a window size windowSize as input and returns an array containing the maximum value in each sliding window. The method first checks if the input is valid and creates a deque to store the indices of elements in the window. + +The method then processes the first window separately by adding the indices of its elements to the deque in decreasing order of their values. This way, the first element in the deque will always be the maximum value in the window. The method stores this maximum value in the first element of the result array. + +The method then processes the remaining windows by first removing any elements in the deque that are outside the current window. The method then adds the index of the current element to the deque and removes any elements in the deque that are smaller than the current element. The method stores the maximum value in the window in the corresponding element of the result array. + +Finally, the method returns the result array. \ No newline at end of file diff --git a/data-structures-and-algorithms.iml b/data-structures-and-algorithms.iml new file mode 100644 index 00000000..fb5b217f --- /dev/null +++ b/data-structures-and-algorithms.iml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file From 4b437e0f829b4e69493ba9187a5ed90a6ad4be26 Mon Sep 17 00:00:00 2001 From: LalitAswal Date: Mon, 27 Feb 2023 00:03:19 +0530 Subject: [PATCH 0311/1894] added js&py solution of buy/sell stock --- .../best_time_to_buy_and_sell_stock.js | 42 +++++++++++++++++++ .../best_time_to_buy_and_sell_stock.py | 39 +++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 Dynamic Programming/best_time_to_buy_and_sell_stock.js diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.js b/Dynamic Programming/best_time_to_buy_and_sell_stock.js new file mode 100644 index 00000000..a1e27eba --- /dev/null +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.js @@ -0,0 +1,42 @@ +/* + You are given an array prices where prices[i] is the price of a given stock on the ith day. + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + Example 1: + Input: prices = [7,1,5,3,6,4] + Output: 5 + Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + + Example 2: + Input: prices = [7,6,4,3,1] + Output: 0 + Explanation: In this case, no transactions are done and the max profit = 0. + + Constraints: + 1 <= prices.length <= 105 + 0 <= prices[i] <= 104 +*/ +function maxProfit(prices) { + if (!prices || prices.length <= 1) { + return 0; + } + + let minPrice = prices[0]; + let maxProfit = 0; + + for (let i = 1; i < prices.length; i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; + } else if (prices[i] - minPrice > maxProfit) { + maxProfit = prices[i] - minPrice; + } + } + + return maxProfit; +} + +console.log(maxProfit([7,1,5,3,6,4]))// 5 +console.log(maxProfit([7,6,4,3,1]))// 0 + diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index e96137f9..370ca79c 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -1,3 +1,25 @@ +''' + You are given an array prices where prices[i] is the price of a given stock on the ith day. + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. + + Example 1: + Input: prices = [7,1,5,3,6,4] + Output: 5 + Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. + Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. + + Example 2: + Input: prices = [7,6,4,3,1] + Output: 0 + Explanation: In this case, no transactions are done and the max profit = 0. + + Constraints: + 1 <= prices.length <= 105 + 0 <= prices[i] <= 104 +''' + + def maxProfit(prices): minElement = 10000 maxDiff = 0 @@ -9,3 +31,20 @@ def maxProfit(prices): prices = [7,1,5,3,6,4] print(maxProfit(prices)) + +# Optimize solution +def max_profit(prices): + min_price = prices[0] + max_profit = 0 + + for price in prices: + if price < min_price: + min_price = price + elif price - min_price > max_profit: + max_profit = price - min_price + + return max_profit + + +print(maxProfit([7,1,5,3,6,4])) # 5 +print(maxProfit([7,6,4,3,1]))# 0 \ No newline at end of file From 684a5501a62ed597446963bff3ceadaf79df30cd Mon Sep 17 00:00:00 2001 From: LalitAswal Date: Mon, 27 Feb 2023 00:07:59 +0530 Subject: [PATCH 0312/1894] minor changes in js file --- Dynamic Programming/best_time_to_buy_and_sell_stock.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.js b/Dynamic Programming/best_time_to_buy_and_sell_stock.js index a1e27eba..ac3572c7 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.js +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.js @@ -19,9 +19,6 @@ 0 <= prices[i] <= 104 */ function maxProfit(prices) { - if (!prices || prices.length <= 1) { - return 0; - } let minPrice = prices[0]; let maxProfit = 0; From d205c4321a609e631e0e93487aadda086d0c6a41 Mon Sep 17 00:00:00 2001 From: Vanshaj Bajaj <95224854+VANSHAJB10@users.noreply.github.com> Date: Mon, 27 Feb 2023 00:28:16 +0530 Subject: [PATCH 0313/1894] Create Graphs_bfs_sankes_ladders.py --- Graphs/Graphs_bfs_sankes_ladders.py | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Graphs/Graphs_bfs_sankes_ladders.py diff --git a/Graphs/Graphs_bfs_sankes_ladders.py b/Graphs/Graphs_bfs_sankes_ladders.py new file mode 100644 index 00000000..b9e143d2 --- /dev/null +++ b/Graphs/Graphs_bfs_sankes_ladders.py @@ -0,0 +1,32 @@ +from collections import deque + +def snakesAndLadders(board): + n = len(board) + target = n*n + moves = {1: 0} + queue = deque([1]) + + while queue: + curr = queue.popleft() + if curr == target: + return moves[curr] + for i in range(1, 7): + next = curr + i + if next > target: + break + row, col = getRowCol(next, n) + if board[row][col] != -1: + next = board[row][col] + if next not in moves: + moves[next] = moves[curr] + 1 + queue.append(next) + + return -1 + +def getRowCol(idx, n): + row = (idx - 1) // n + col = (idx - 1) % n + if row % 2 == 1: + col = n - col - 1 + row = n - row - 1 + return row, col From 05e5f44881859622ae0a69c2298e6b72d95ce47b Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sun, 26 Feb 2023 22:40:06 -0500 Subject: [PATCH 0314/1894] Create Linkedlist_Add_two_numbers.py --- Linked List/LinkedList_Add_Two_numbers.py | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Linked List/LinkedList_Add_Two_numbers.py diff --git a/Linked List/LinkedList_Add_Two_numbers.py b/Linked List/LinkedList_Add_Two_numbers.py new file mode 100644 index 00000000..9ca11523 --- /dev/null +++ b/Linked List/LinkedList_Add_Two_numbers.py @@ -0,0 +1,29 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + carry = 0 + head = ListNode('*'); + header_pointer = head; + while(l1!=None or l2!=None): + temp = carry + if(l1==None): + temp+= l2.val + l2 = l2.next + elif(l2==None): + temp += l1.val + l1 = l1.next + else: + temp+=l1.val+l2.val + l1=l1.next + l2=l2.next + head.next = ListNode(temp%10) + carry = temp//10 + head = head.next + if(carry!=0): + head.next = ListNode(carry) + head = head.next + return header_pointer.next From 081aa6139bd327e73bfb08b23a4c68a3bf3f411d Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sun, 26 Feb 2023 23:36:54 -0500 Subject: [PATCH 0315/1894] Create LinkedList_Intersection_of_two.py --- Linked List/LinkedList_Intersection_of_two.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Linked List/LinkedList_Intersection_of_two.py diff --git a/Linked List/LinkedList_Intersection_of_two.py b/Linked List/LinkedList_Intersection_of_two.py new file mode 100644 index 00000000..d44b0649 --- /dev/null +++ b/Linked List/LinkedList_Intersection_of_two.py @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def __init__(self): + self.s=set() + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: + while(headA!=None): + self.s.add(headA) + headA=headA.next + while(headB!=None): + if(headB in self.s): + return headB + headB=headB.next From 851bfa9d57f73bff997b8f93cfb1090f26cd4f9e Mon Sep 17 00:00:00 2001 From: Mahesh Kumar <72140079+mahehsblogs@users.noreply.github.com> Date: Mon, 27 Feb 2023 11:03:34 +0530 Subject: [PATCH 0316/1894] Delete data-structures-and-algorithms.iml --- data-structures-and-algorithms.iml | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 data-structures-and-algorithms.iml diff --git a/data-structures-and-algorithms.iml b/data-structures-and-algorithms.iml deleted file mode 100644 index fb5b217f..00000000 --- a/data-structures-and-algorithms.iml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file From 390163435d0e7bc14504a04b1f9fd8244531f6d0 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Mon, 27 Feb 2023 11:16:09 +0530 Subject: [PATCH 0317/1894] added Find Maximum in Sliding Window in javaScript --- ...nd Maximum in Sliding Window in javaScript | 52 +++++++++++++++++++ data-structures-and-algorithms.iml | 18 ------- 2 files changed, 52 insertions(+), 18 deletions(-) create mode 100644 Sliding Window/Find Maximum in Sliding Window in javaScript delete mode 100644 data-structures-and-algorithms.iml diff --git a/Sliding Window/Find Maximum in Sliding Window in javaScript b/Sliding Window/Find Maximum in Sliding Window in javaScript new file mode 100644 index 00000000..23726651 --- /dev/null +++ b/Sliding Window/Find Maximum in Sliding Window in javaScript @@ -0,0 +1,52 @@ +function findMaxSlidingWindow(nums, windowSize) { + if (!nums || windowSize <= 0 || nums.length < windowSize) { + return []; + } + + const n = nums.length; + const result = new Array(n - windowSize + 1).fill(0); + const deque = []; // deque stores the indices of elements in the window + + // process the first window separately + for (let i = 0; i < windowSize; i++) { + while (deque.length > 0 && nums[i] >= nums[deque[deque.length - 1]]) { + deque.pop(); + } + deque.push(i); + } + result[0] = nums[deque[0]]; + + // process the remaining windows + for (let i = windowSize; i < n; i++) { + while (deque.length > 0 && deque[0] <= i - windowSize) { + deque.shift(); // remove elements outside the window + } + while (deque.length > 0 && nums[i] >= nums[deque[deque.length - 1]]) { + deque.pop(); // remove elements smaller than nums[i] + } + deque.push(i); + result[i - windowSize + 1] = nums[deque[0]]; + } + + return result; +} + +const nums = [1, 3, -1, -3, 5, 3, 6, 7]; +const windowSize = 3; + +const maxInWindow = findMaxSlidingWindow(nums, windowSize); + +console.log(`Max values in sliding window of size ${windowSize}:`); +console.log(maxInWindow.join(' ')); + +-------------Explanation--------------------- + +This code defines a findMaxSlidingWindow function that takes an array nums and a window size windowSize as input and returns an array containing the maximum value in each sliding window. The function first checks if the input is valid and creates an empty array result and a deque to store the indices of elements in the window. + +The function then processes the first window separately by adding the indices of its elements to the deque in decreasing order of their values. This way, the first element in the deque will always be the maximum value in the window. The function stores this maximum value in the first element of the result array. + +The function then processes the remaining windows by first removing any elements in the deque that are outside the current window. The function then adds the index of the current element to the deque and removes any elements in the deque that are smaller than the current element. The function stores the maximum value in the window in the corresponding element of the result array. + +Finally, the function returns the result array. + +The code also includes an example usage of the findMaxSlidingWindow function on an example array and window size. When the code is executed, it prints the maximum values in each sliding window to the console. \ No newline at end of file diff --git a/data-structures-and-algorithms.iml b/data-structures-and-algorithms.iml deleted file mode 100644 index fb5b217f..00000000 --- a/data-structures-and-algorithms.iml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file From 5cce30a93906e657f1e0420d31b2e7378c47b0e8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:16:52 +0530 Subject: [PATCH 0318/1894] rename file --- ...nkedList_Add_Two_numbers.py => linked_list_add_two_numbers.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Linked List/{LinkedList_Add_Two_numbers.py => linked_list_add_two_numbers.py} (100%) diff --git a/Linked List/LinkedList_Add_Two_numbers.py b/Linked List/linked_list_add_two_numbers.py similarity index 100% rename from Linked List/LinkedList_Add_Two_numbers.py rename to Linked List/linked_list_add_two_numbers.py From 64caa95e3b410c53110adb5ae052a853a762e846 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:17:45 +0530 Subject: [PATCH 0319/1894] add description --- Linked List/linked_list_add_two_numbers.py | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Linked List/linked_list_add_two_numbers.py b/Linked List/linked_list_add_two_numbers.py index 9ca11523..4fdcef1c 100644 --- a/Linked List/linked_list_add_two_numbers.py +++ b/Linked List/linked_list_add_two_numbers.py @@ -1,3 +1,29 @@ +''' +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +Example 1: +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +Explanation: 342 + 465 = 807. + +Example 2: +Input: l1 = [0], l2 = [0] +Output: [0] + +Example 3: +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] + + +Constraints: + +The number of nodes in each linked list is in the range [1, 100]. +0 <= Node.val <= 9 +It is guaranteed that the list represents a number that does not have leading zeros. +''' + # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): From 0a834a15ee8e5d25034abb987d6fad83886399f5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:21:00 +0530 Subject: [PATCH 0320/1894] add time and space complexity and rfmt code --- Linked List/linked_list_add_two_numbers.py | 25 +++++++++++++--------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/Linked List/linked_list_add_two_numbers.py b/Linked List/linked_list_add_two_numbers.py index 4fdcef1c..2021deca 100644 --- a/Linked List/linked_list_add_two_numbers.py +++ b/Linked List/linked_list_add_two_numbers.py @@ -22,6 +22,11 @@ The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros. + +Complexity +Time complexity : O(max(l1,l2)). +Space complexity : O(n). + ''' # Definition for singly-linked list. @@ -34,22 +39,22 @@ def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optio carry = 0 head = ListNode('*'); header_pointer = head; - while(l1!=None or l2!=None): + while(l1 != None or l2 != None): temp = carry - if(l1==None): - temp+= l2.val + if(l1 == None): + temp += l2.val l2 = l2.next - elif(l2==None): + elif(l2 == None): temp += l1.val l1 = l1.next else: - temp+=l1.val+l2.val - l1=l1.next - l2=l2.next - head.next = ListNode(temp%10) - carry = temp//10 + temp += l1.val+l2.val + l1 = l1.next + l2 = l2.next + head.next = ListNode(temp % 10) + carry = temp // 10 head = head.next - if(carry!=0): + if(carry != 0): head.next = ListNode(carry) head = head.next return header_pointer.next From 652c7072c650650c96695d199c0908f8f479ec1f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:25:23 +0530 Subject: [PATCH 0321/1894] remove duplicate file --- Linked List/reverse_linked_list.cpp | 60 ----------------------------- 1 file changed, 60 deletions(-) delete mode 100644 Linked List/reverse_linked_list.cpp diff --git a/Linked List/reverse_linked_list.cpp b/Linked List/reverse_linked_list.cpp deleted file mode 100644 index 6bd9d91b..00000000 --- a/Linked List/reverse_linked_list.cpp +++ /dev/null @@ -1,60 +0,0 @@ - -/* -Given the head of a singly linked list, reverse the list, and return the reversed list. - - - -Example 1: - - -Input: head = [1,2,3,4,5] -Output: [5,4,3,2,1] -Example 2: - - -Input: head = [1,2] -Output: [2,1] -Example 3: - -Input: head = [] -Output: [] - - -Constraints: - -The number of nodes in the list is the range [0, 5000]. --5000 <= Node.val <= 5000 - -*/ - -//iterative solution----- - -ListNode* reverseList(ListNode* head) { - if(head==NULL){ - return NULL; - } - ListNode* prev=NULL; - ListNode* curr=head; - ListNode* next; - while(curr!=NULL){ - next=curr->next; - curr->next=prev; - prev=curr; - curr=next; - } - curr=prev; - return curr; - - } - - -//recursive solution--- -ListNode* reverseList(ListNode* head) { - if (!head || !(head -> next)) { - return head; - } - ListNode* node = reverseList(head -> next); - head -> next -> next = head; - head -> next = NULL; - return node; - } From 5029f9d53d95c411c1459c68da1ce5e0a71b4738 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:25:29 +0530 Subject: [PATCH 0322/1894] rename file --- .../Find Maximum in Sliding Window in Python | 18 ------------------ ... Window in Java => sliding_window_max.java} | 0 ...dow in javaScript => sliding_window_max.js} | 0 Sliding Window/sliding_window_max.py | 18 ++++++++++++++++++ 4 files changed, 18 insertions(+), 18 deletions(-) delete mode 100644 Sliding Window/Find Maximum in Sliding Window in Python rename Sliding Window/{Find Maximum in Sliding Window in Java => sliding_window_max.java} (100%) rename Sliding Window/{Find Maximum in Sliding Window in javaScript => sliding_window_max.js} (100%) create mode 100644 Sliding Window/sliding_window_max.py diff --git a/Sliding Window/Find Maximum in Sliding Window in Python b/Sliding Window/Find Maximum in Sliding Window in Python deleted file mode 100644 index 357eba8f..00000000 --- a/Sliding Window/Find Maximum in Sliding Window in Python +++ /dev/null @@ -1,18 +0,0 @@ -from collections import deque - -def slidingWindowMax(arr,windowSize) -> list[int]: - dq=deque() - max_elements=[] - for i in range(len(arr)): - if(len(dq)!=0 and dq[0]== i-windowSize): - dq.popleft() - while(len(dq)!=0 and arr[dq[-1]]=windowSize-1): - max_elements.append(arr[dq[0]]) - return max_elements - -arr=list(map(int,input().split())) -windowSize=int(input()) -print(slidingWindowMax(arr,windowSize)) diff --git a/Sliding Window/Find Maximum in Sliding Window in Java b/Sliding Window/sliding_window_max.java similarity index 100% rename from Sliding Window/Find Maximum in Sliding Window in Java rename to Sliding Window/sliding_window_max.java diff --git a/Sliding Window/Find Maximum in Sliding Window in javaScript b/Sliding Window/sliding_window_max.js similarity index 100% rename from Sliding Window/Find Maximum in Sliding Window in javaScript rename to Sliding Window/sliding_window_max.js diff --git a/Sliding Window/sliding_window_max.py b/Sliding Window/sliding_window_max.py new file mode 100644 index 00000000..213345b6 --- /dev/null +++ b/Sliding Window/sliding_window_max.py @@ -0,0 +1,18 @@ +from collections import deque + +def slidingWindowMax(arr,windowSize) -> list[int]: + dq = deque() + max_elements = [] + for i in range(len(arr)): + if(len(dq) != 0 and dq[0]== i - windowSize): + dq.popleft() + while(len(dq) !=0 and arr[dq[-1]] < arr[i]): + dq.pop() + dq.append(i) + if(i >= windowSize - 1): + max_elements.append(arr[dq[0]]) + return max_elements + +arr = list(map(int, input().split())) +windowSize = int(input()) +print(slidingWindowMax(arr, windowSize)) From a42c91936702cd8e557607c38427460e71f34e3f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:29:59 +0530 Subject: [PATCH 0323/1894] rename file and add description --- Graphs/Graphs_bfs_sankes_ladders.py | 32 --- ...ers.cpp => graphs_bfs_snackes_ladders.cpp} | 214 +++++++++++------- Graphs/graphs_bfs_snakes_ladders.py | 70 ++++++ 3 files changed, 198 insertions(+), 118 deletions(-) delete mode 100644 Graphs/Graphs_bfs_sankes_ladders.py rename Graphs/{Graphs_bfs_snack_ladders.cpp => graphs_bfs_snackes_ladders.cpp} (50%) create mode 100644 Graphs/graphs_bfs_snakes_ladders.py diff --git a/Graphs/Graphs_bfs_sankes_ladders.py b/Graphs/Graphs_bfs_sankes_ladders.py deleted file mode 100644 index b9e143d2..00000000 --- a/Graphs/Graphs_bfs_sankes_ladders.py +++ /dev/null @@ -1,32 +0,0 @@ -from collections import deque - -def snakesAndLadders(board): - n = len(board) - target = n*n - moves = {1: 0} - queue = deque([1]) - - while queue: - curr = queue.popleft() - if curr == target: - return moves[curr] - for i in range(1, 7): - next = curr + i - if next > target: - break - row, col = getRowCol(next, n) - if board[row][col] != -1: - next = board[row][col] - if next not in moves: - moves[next] = moves[curr] + 1 - queue.append(next) - - return -1 - -def getRowCol(idx, n): - row = (idx - 1) // n - col = (idx - 1) % n - if row % 2 == 1: - col = n - col - 1 - row = n - row - 1 - return row, col diff --git a/Graphs/Graphs_bfs_snack_ladders.cpp b/Graphs/graphs_bfs_snackes_ladders.cpp similarity index 50% rename from Graphs/Graphs_bfs_snack_ladders.cpp rename to Graphs/graphs_bfs_snackes_ladders.cpp index a6dd988d..b1cf8e99 100644 --- a/Graphs/Graphs_bfs_snack_ladders.cpp +++ b/Graphs/graphs_bfs_snackes_ladders.cpp @@ -1,87 +1,129 @@ -// Graphs Adjacency List implementation for Generic Data -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; - -template -class Graph{ - map > adjList; - public: - Graph(){ - - } - void addEdge(T u, T v, bool bidir = true){ - adjList[u].push_back(v); - if(bidir){ - adjList[v].push_back(u); - } - } - void printAdjList(){ - for(auto obj : adjList){ - cout << obj.first << "->"; - for(auto element : obj.second){ - cout << element << ","; - } - cout << endl; - } - } - int bfs_sssp(int n, int m){ - queue q; - map dist; - map parent; - for(auto i : adjList){ - dist[i.first] = INT_MAX; - } - q.push(n); - dist[n] = 0; - parent[n] = n; - while(!q.empty()){ - int node_element = q.front(); - q.pop(); - for(int neighbour : adjList[node_element]){ - if(dist[neighbour] == INT_MAX){ - q.push(neighbour); - dist[neighbour] = dist[node_element] + 1; - parent[neighbour] = node_element; - } - } - } - cout << endl; - int temp = m; - while(temp != n){ - cout << temp << "-->"; - temp = parent[temp]; - } - cout << n << endl; - /* - for(auto i : adjList){ - int node = i.first; - cout << "Distance of " << node << " is " << dist[node] << endl; - } - */ - return dist[m]; - - } -}; -int main(){ - Graph g; - int board[50] = {0}; - board[2] = 13; - board[5] = 2; - board[9] = 18; - board[18] = 11; - board[17] = -13; - board[20] = -14; - board[24] = -8; - board[25] = -10; - board[32] = -2; - board[34] = -22; - for(int u = 0; u <= 36; u++){ - for(int dice = 1; dice <= 6; dice++){ - int v = u + dice + board[u + dice]; - g.addEdge(u, v, false); - } - } - cout << "The shortest distance is " << g.bfs_sssp(1, 36) << endl; - return 0; +/* +You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. + +You start on square 1 of the board. In each move, starting from square curr, do the following: + +Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. +This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. +If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. +The game ends when you reach the square n2. +A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder. + +Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. + +For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. +Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1. + + + +Example 1: + + +Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] +Output: 4 +Explanation: +In the beginning, you start at square 1 (at row 5, column 0). +You decide to move to square 2 and must take the ladder to square 15. +You then decide to move to square 17 and must take the snake to square 13. +You then decide to move to square 14 and must take the ladder to square 35. +You then decide to move to square 36, ending the game. +This is the lowest possible number of moves to reach the last square, so return 4. +Example 2: + +Input: board = [[-1,-1],[-1,3]] +Output: 1 + + +Constraints: + +n == board.length == board[i].length +2 <= n <= 20 +board[i][j] is either -1 or in the range [1, n2]. +The squares labeled 1 and n2 do not have any ladders or snakes. +*/ + +#include +using namespace std; + +template +class Graph{ + map > adjList; + public: + Graph(){ + + } + void addEdge(T u, T v, bool bidir = true){ + adjList[u].push_back(v); + if(bidir){ + adjList[v].push_back(u); + } + } + void printAdjList(){ + for(auto obj : adjList){ + cout << obj.first << "->"; + for(auto element : obj.second){ + cout << element << ","; + } + cout << endl; + } + } + int bfs_sssp(int n, int m){ + queue q; + map dist; + map parent; + for(auto i : adjList){ + dist[i.first] = INT_MAX; + } + q.push(n); + dist[n] = 0; + parent[n] = n; + while(!q.empty()){ + int node_element = q.front(); + q.pop(); + for(int neighbour : adjList[node_element]){ + if(dist[neighbour] == INT_MAX){ + q.push(neighbour); + dist[neighbour] = dist[node_element] + 1; + parent[neighbour] = node_element; + } + } + } + cout << endl; + int temp = m; + while(temp != n){ + cout << temp << "-->"; + temp = parent[temp]; + } + cout << n << endl; + /* + for(auto i : adjList){ + int node = i.first; + cout << "Distance of " << node << " is " << dist[node] << endl; + } + */ + return dist[m]; + + } +}; +int main(){ + Graph g; + int board[50] = {0}; + board[2] = 13; + board[5] = 2; + board[9] = 18; + board[18] = 11; + board[17] = -13; + board[20] = -14; + board[24] = -8; + board[25] = -10; + board[32] = -2; + board[34] = -22; + for(int u = 0; u <= 36; u++){ + for(int dice = 1; dice <= 6; dice++){ + int v = u + dice + board[u + dice]; + g.addEdge(u, v, false); + } + } + cout << "The shortest distance is " << g.bfs_sssp(1, 36) << endl; + return 0; } \ No newline at end of file diff --git a/Graphs/graphs_bfs_snakes_ladders.py b/Graphs/graphs_bfs_snakes_ladders.py new file mode 100644 index 00000000..3aef1e48 --- /dev/null +++ b/Graphs/graphs_bfs_snakes_ladders.py @@ -0,0 +1,70 @@ +''' + You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. + + You start on square 1 of the board. In each move, starting from square curr, do the following: + + Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. + This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. + If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. + The game ends when you reach the square n2. + A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder. + + Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. + + For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. + Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1. + + Example 1: + Input: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]] + Output: 4 + + Explanation: + In the beginning, you start at square 1 (at row 5, column 0). + You decide to move to square 2 and must take the ladder to square 15. + You then decide to move to square 17 and must take the snake to square 13. + You then decide to move to square 14 and must take the ladder to square 35. + You then decide to move to square 36, ending the game. + This is the lowest possible number of moves to reach the last square, so return 4. + + Example 2: + Input: board = [[-1,-1],[-1,3]] + Output: 1 + + Constraints: + n == board.length == board[i].length + 2 <= n <= 20 + board[i][j] is either -1 or in the range [1, n2]. + The squares labeled 1 and n2 do not have any ladders or snakes. +''' +from collections import deque + +def snakesAndLadders(board): + n = len(board) + target = n*n + moves = {1: 0} + queue = deque([1]) + + while queue: + curr = queue.popleft() + if curr == target: + return moves[curr] + for i in range(1, 7): + next = curr + i + if next > target: + break + row, col = getRowCol(next, n) + if board[row][col] != -1: + next = board[row][col] + if next not in moves: + moves[next] = moves[curr] + 1 + queue.append(next) + + return -1 + +def getRowCol(idx, n): + row = (idx - 1) // n + col = (idx - 1) % n + if row % 2 == 1: + col = n - col - 1 + row = n - row - 1 + return row, col From 9729a9285c9178fe99aacd1cbf2a29ed2714992a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:36:51 +0530 Subject: [PATCH 0324/1894] move matrix related problems ito 2d arrays directory --- .../matrix_rotate_90_anti_clockwise.cpp | 0 {Random Problems => 2D Arrays}/matrix_rotate_90_clockwise.cpp | 0 {Random Problems => 2D Arrays}/matrix_search_in_sorted_mat.cpp | 0 {Random Problems => 2D Arrays}/matrix_spiral_print.cpp | 0 {Random Problems => 2D Arrays}/matrix_wave_print.cpp | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => 2D Arrays}/matrix_rotate_90_anti_clockwise.cpp (100%) rename {Random Problems => 2D Arrays}/matrix_rotate_90_clockwise.cpp (100%) rename {Random Problems => 2D Arrays}/matrix_search_in_sorted_mat.cpp (100%) rename {Random Problems => 2D Arrays}/matrix_spiral_print.cpp (100%) rename {Random Problems => 2D Arrays}/matrix_wave_print.cpp (100%) diff --git a/Random Problems/matrix_rotate_90_anti_clockwise.cpp b/2D Arrays/matrix_rotate_90_anti_clockwise.cpp similarity index 100% rename from Random Problems/matrix_rotate_90_anti_clockwise.cpp rename to 2D Arrays/matrix_rotate_90_anti_clockwise.cpp diff --git a/Random Problems/matrix_rotate_90_clockwise.cpp b/2D Arrays/matrix_rotate_90_clockwise.cpp similarity index 100% rename from Random Problems/matrix_rotate_90_clockwise.cpp rename to 2D Arrays/matrix_rotate_90_clockwise.cpp diff --git a/Random Problems/matrix_search_in_sorted_mat.cpp b/2D Arrays/matrix_search_in_sorted_mat.cpp similarity index 100% rename from Random Problems/matrix_search_in_sorted_mat.cpp rename to 2D Arrays/matrix_search_in_sorted_mat.cpp diff --git a/Random Problems/matrix_spiral_print.cpp b/2D Arrays/matrix_spiral_print.cpp similarity index 100% rename from Random Problems/matrix_spiral_print.cpp rename to 2D Arrays/matrix_spiral_print.cpp diff --git a/Random Problems/matrix_wave_print.cpp b/2D Arrays/matrix_wave_print.cpp similarity index 100% rename from Random Problems/matrix_wave_print.cpp rename to 2D Arrays/matrix_wave_print.cpp From bd449c108dcb517fc046e1cdfd689cabd2230a2f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:44:46 +0530 Subject: [PATCH 0325/1894] move into Linked List directory --- Leetcode/linked_list_find_length.cpp | 44 ------ Leetcode/linked_list_merge_k_sorted_lists.cpp | 100 ------------- Leetcode/linked_list_reverse_recursive.cpp | 60 -------- ...nked_list_swap_nodes_in_pair_iterative.cpp | 71 ---------- .../linked_list_sum_lists.cpp | 134 +++++++++--------- 5 files changed, 67 insertions(+), 342 deletions(-) delete mode 100644 Leetcode/linked_list_find_length.cpp delete mode 100644 Leetcode/linked_list_merge_k_sorted_lists.cpp delete mode 100644 Leetcode/linked_list_reverse_recursive.cpp delete mode 100644 Leetcode/linked_list_swap_nodes_in_pair_iterative.cpp rename {Leetcode => Linked List}/linked_list_sum_lists.cpp (96%) diff --git a/Leetcode/linked_list_find_length.cpp b/Leetcode/linked_list_find_length.cpp deleted file mode 100644 index 1ebd3d6e..00000000 --- a/Leetcode/linked_list_find_length.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Find length of a LinkedList -// Program Author : Abhisek Kumar Gupta - -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -int length(node* head){ - int len = 0; - while(head != NULL){ - head = head->next; - len++; - } - return len; -} -void insert_at_head(node *&head, int data){ - node *n = new node(data); - n->next = head; - head = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -int main(){ - node *head = NULL; - insert_at_head(head, 1); - insert_at_head(head, 2); - insert_at_head(head, 3); - print_linked_list(head); - int len = length(head); - cout << endl < -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; - -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -istream& operator>>(istream &is, node *&head){ - makeLinkedList(head); - return is; -} -ostream& operator<<(ostream &os, node *&head){ - print_linked_list(head); - return os; -} -node* merge_two_lists(node *a, node *b){ - if(a == NULL){ - return b; - } - else if(b == NULL){ - return a; - } - node *c = NULL; - if(a->data < b->data){ - c = a; - c->next = merge_two_lists(a->next, b); - } - else{ - c = b; - c->next = merge_two_lists(a, b->next); - } - return c; -} -node* merge_k_lists(node *arr[], int last){ - while(last != 0){ - int i = 0, j = last; - while(i < j){ - arr[i] = merge_two_lists(arr[i], arr[j]); - i++; - j--; - if(i >= j) - last = j; - } - } - return arr[0]; -} -int main(){ - - int n; - cin >> n; - node *arr[n]; - for(int i = 0; i < n; i++){ - arr[i] = NULL; - } - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - cout << endl; - for(int i = 0; i < n; i++){ - cout << arr[i] << endl;; - } - node *head = merge_k_lists(arr, n-1); - cout << head; - return 0; -} \ No newline at end of file diff --git a/Leetcode/linked_list_reverse_recursive.cpp b/Leetcode/linked_list_reverse_recursive.cpp deleted file mode 100644 index ec360e09..00000000 --- a/Leetcode/linked_list_reverse_recursive.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// Given the head of a singly linked list, reverse the list, and return the reversed list recursively -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} - -node* recursive_reverse(node *head){ - if(head->next == NULL || head == NULL){ - return head; - } - node *mini_head = recursive_reverse(head->next); - node *current = head; - current->next->next = current; - current->next = NULL; - return mini_head; -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - cout << endl; - head = recursive_reverse(head); - print_linked_list(head); - return 0; -} \ No newline at end of file diff --git a/Leetcode/linked_list_swap_nodes_in_pair_iterative.cpp b/Leetcode/linked_list_swap_nodes_in_pair_iterative.cpp deleted file mode 100644 index 03a85460..00000000 --- a/Leetcode/linked_list_swap_nodes_in_pair_iterative.cpp +++ /dev/null @@ -1,71 +0,0 @@ -// Given a linked list, swap every two adjacent nodes and return its head. -// You must solve the problem without modifying the values in the list's nodes -// (i.e., only nodes themselves may be changed.) Iterative -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - cout << endl; - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} - -node* swapNodesInPairIterative(node *head){ - node *dummy = new node(0); - node *prev = dummy; - node *curr = head; - node *second = NULL; - node *nextPair = NULL; - while(curr && curr->next){ - nextPair = curr->next->next; - second = curr->next; - - second->next = curr; - curr->next = nextPair; - prev->next = second; - - prev = curr; - curr = nextPair; - } - return dummy->next; - -} -int main(){ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - head = swapNodesInPairIterative(head); - print_linked_list(head); - return 0; -} \ No newline at end of file diff --git a/Leetcode/linked_list_sum_lists.cpp b/Linked List/linked_list_sum_lists.cpp similarity index 96% rename from Leetcode/linked_list_sum_lists.cpp rename to Linked List/linked_list_sum_lists.cpp index e3aeb672..824c4b7f 100644 --- a/Leetcode/linked_list_sum_lists.cpp +++ b/Linked List/linked_list_sum_lists.cpp @@ -1,68 +1,68 @@ -// sum Lists : you have two numbers represented by a linked list -// where each node contains a single digit, write a function -// to add two numbers and returns the sum as linked list -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -class Node{ - public: - int data; - Node *next; - - Node(int d){ - data = d; - } -}; - -void insert_at_head(Node *&head, int data){ - Node *new_node = new Node(data); - new_node->next = head; - head = new_node; -} -void print_linked_list(Node *head){ - if(head == NULL) - return; - cout << head->data << "->"; - print_linked_list(head->next); -} -void make_linked_list(Node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_head(head, data); - cin >> data; - } -} -Node* add_lists(Node *l1, Node *l2, int carry){ - - if(l1 == NULL && l2 == NULL && carry == 0) - return NULL; - int value = carry; - - if(l1 != NULL) - value += l1->data; - - if(l2 != NULL) - value += l2->data; - - Node *result = new Node(value % 10); - - if(l1 != NULL || l2 != NULL) - result->next = add_lists(l1 == NULL ? NULL : l1->next, l2 == NULL ? NULL : l2->next, value >= 10 ? 1 : 0); - else - result->next = NULL; - - return result; -} -int main(){ - Node *head1 = NULL; - Node *head2 = NULL; - make_linked_list(head1); - make_linked_list(head2); - print_linked_list(head1); - cout << endl; - print_linked_list(head2); - Node *result = add_lists(head1, head2, 0); - cout << endl; - print_linked_list(result); +// sum Lists : you have two numbers represented by a linked list +// where each node contains a single digit, write a function +// to add two numbers and returns the sum as linked list +// Program Author: Abhisek Kumar Gupta +#include +using namespace std; +class Node{ + public: + int data; + Node *next; + + Node(int d){ + data = d; + } +}; + +void insert_at_head(Node *&head, int data){ + Node *new_node = new Node(data); + new_node->next = head; + head = new_node; +} +void print_linked_list(Node *head){ + if(head == NULL) + return; + cout << head->data << "->"; + print_linked_list(head->next); +} +void make_linked_list(Node *&head){ + int data; + cin >> data; + while(data != -1){ + insert_at_head(head, data); + cin >> data; + } +} +Node* add_lists(Node *l1, Node *l2, int carry){ + + if(l1 == NULL && l2 == NULL && carry == 0) + return NULL; + int value = carry; + + if(l1 != NULL) + value += l1->data; + + if(l2 != NULL) + value += l2->data; + + Node *result = new Node(value % 10); + + if(l1 != NULL || l2 != NULL) + result->next = add_lists(l1 == NULL ? NULL : l1->next, l2 == NULL ? NULL : l2->next, value >= 10 ? 1 : 0); + else + result->next = NULL; + + return result; +} +int main(){ + Node *head1 = NULL; + Node *head2 = NULL; + make_linked_list(head1); + make_linked_list(head2); + print_linked_list(head1); + cout << endl; + print_linked_list(head2); + Node *result = add_lists(head1, head2, 0); + cout << endl; + print_linked_list(result); } \ No newline at end of file From 35c7e677982c1261fe4a202e18b8186e6bcee718 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:44:54 +0530 Subject: [PATCH 0326/1894] remove duplicate file --- .../reverse_words_in_string_algoexpect.java | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 Leetcode/reverse_words_in_string_algoexpect.java diff --git a/Leetcode/reverse_words_in_string_algoexpect.java b/Leetcode/reverse_words_in_string_algoexpect.java deleted file mode 100644 index 60ca4a3c..00000000 --- a/Leetcode/reverse_words_in_string_algoexpect.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Reverse Words In String - * - * Write a function that takes in a string of words separated by one or more whitespaces and returns a string that has these words in reverse order. For example, given the string "tim is great", your function should return "great is tim". - * - * For this problem, a word can contain special characters, punctuation, and numbers. The words in the string will be separated by one or more whitespaces, and the reversed string must contain the same whitespaces as the original string. For example, given the string "whitespaces 4" you would be expected to return "4 whitespaces". - * - * Note that you're not allowed to to use any built-in split or reverse methods/functions. However, you are allowed to use a built-in join method/function. - * - * Also note that the input string isn't guaranteed to always contain words. - * Sample Input - * - * string = "AlgoExpert is the best!" - * - * Sample Output - * - * "best! the is AlgoExpert" - */ - -package Strings; - -import java.util.*; - -public class ReverseWordsInStringAlgoExpert { - public static void main(String[] args) { -// String string = "great! is Uday"; - String string = "the sky is blue"; - - String res = solve(string); - System.out.println(res); - } - public static String solve(String string) { - // O(N) time | O(N) space where N is the length of the string - ArrayList words = new ArrayList<>(); - int startOfWord = 0; // keeps track of first idx to - - for (int idx = 0; idx < string.length(); idx++) { - char character = string.charAt(idx); - - if (character == ' ') { - words.add(string.substring(startOfWord, idx)); - startOfWord = idx; - } else if (string.charAt(startOfWord) == ' ') { - words.add(" "); - startOfWord = idx; - } - } - - words.add(string.substring(startOfWord)); // last substring - - Collections.reverse(words); - System.out.println(words); - return String.join("", words); - } -} From 0c5315822fd35c071aaebef30e1c0a14540b6050 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:44:58 +0530 Subject: [PATCH 0327/1894] rename file --- .../{reverse_word_in_a_string.go => reverse_words_in_a_string.go} | 0 .../{reverse_word_in_a_string.js => reverse_words_in_a_string.js} | 0 {Leetcode => Strings}/reverse_words_in_string.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Strings/{reverse_word_in_a_string.go => reverse_words_in_a_string.go} (100%) rename Strings/{reverse_word_in_a_string.js => reverse_words_in_a_string.js} (100%) rename {Leetcode => Strings}/reverse_words_in_string.java (100%) diff --git a/Strings/reverse_word_in_a_string.go b/Strings/reverse_words_in_a_string.go similarity index 100% rename from Strings/reverse_word_in_a_string.go rename to Strings/reverse_words_in_a_string.go diff --git a/Strings/reverse_word_in_a_string.js b/Strings/reverse_words_in_a_string.js similarity index 100% rename from Strings/reverse_word_in_a_string.js rename to Strings/reverse_words_in_a_string.js diff --git a/Leetcode/reverse_words_in_string.java b/Strings/reverse_words_in_string.java similarity index 100% rename from Leetcode/reverse_words_in_string.java rename to Strings/reverse_words_in_string.java From 695ef84523eee30c33e43b430671c42ecd918857 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Feb 2023 22:46:17 +0530 Subject: [PATCH 0328/1894] remove duplicate file --- Leetcode/Graphs_flood_fill.cpp | 113 --------------------------------- 1 file changed, 113 deletions(-) delete mode 100644 Leetcode/Graphs_flood_fill.cpp diff --git a/Leetcode/Graphs_flood_fill.cpp b/Leetcode/Graphs_flood_fill.cpp deleted file mode 100644 index ccdab3ff..00000000 --- a/Leetcode/Graphs_flood_fill.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Flood fill, also called seed fill, is a flooding algorithm that determines and alters the area connected to a given node -// in a multi-dimensional array with some matching attribute. It is used in the "bucket" fill tool of paint programs to fill -// connected, similarly-colored areas with a different color, and in games such as Go and Minesweeper for determining -// which pieces are cleared. Source(https://en.wikipedia.org/wiki/Flood_fill) -#include -using namespace std; -int R, C; -void print_matrix(char input[][50]){ - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << input[i][j]; - } - cout << "\n"; - } -} -int dx[] = {-1, 0, 1, 0}; -int dy[] = {0, -1, 0, 1}; -void flood_fill(char input[][50], int i, int j, char ch, char color){ - // base case : make sure we do not cross boundries of input matrix - if(i < 0 || j < 0 || i >= R || j >= C) - return; - // if we are coming to a cell that is not equal to ch then we dont do anything - if(input[i][j] != ch) - return; - // fill the color - input[i][j] = color; - - // dfs flood_fill on all directions - for(int k = 0; k < 4; k++){ - flood_fill(input, i + dx[k], j + dy[k], ch, color); - } -} -int main(){ - cin >> R >> C; - char input[15][50]; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> input[i][j]; - } - } - print_matrix(input); - flood_fill(input, 8, 13, '.', 'r'); - print_matrix(input); - flood_fill(input, 2, 15, '.', 'b'); - print_matrix(input); -return 0; -} - -/* -Input -15 30 -.............................. -.............#####............ -.............#...#............ -.....#########...#######...... -....###.....######.....###.... -...##....................##... -..##......................#... -..##.....................##... -..###...................##.... -....###................###.... -......###............###...... -........###........###........ -..........##########.......... -.............................. -...........A.P.P.L.E.......... -Output : -.............................. -.............#####............ -.............#...#............ -.....#########...#######...... -....###.....######.....###.... -...##....................##... -..##......................#... -..##.....................##... -..###...................##.... -....###................###.... -......###............###...... -........###........###........ -..........##########.......... -.............................. -...........A.P.P.L.E.......... -.............................. -.............#####............ -.............#...#............ -.....#########...#######...... -....###rrrrr######rrrrr###.... -...##rrrrrrrrrrrrrrrrrrrr##... -..##rrrrrrrrrrrrrrrrrrrrrr#... -..##rrrrrrrrrrrrrrrrrrrrr##... -..###rrrrrrrrrrrrrrrrrrr##.... -....###rrrrrrrrrrrrrrrr###.... -......###rrrrrrrrrrrr###...... -........###rrrrrrrr###........ -..........##########.......... -.............................. -...........A.P.P.L.E.......... -.............................. -.............#####............ -.............#bbb#............ -.....#########bbb#######...... -....###rrrrr######rrrrr###.... -...##rrrrrrrrrrrrrrrrrrrr##... -..##rrrrrrrrrrrrrrrrrrrrrr#... -..##rrrrrrrrrrrrrrrrrrrrr##... -..###rrrrrrrrrrrrrrrrrrr##.... -....###rrrrrrrrrrrrrrrr###.... -......###rrrrrrrrrrrr###...... -........###rrrrrrrr###........ -..........##########.......... -.............................. -...........A.P.P.L.E.......... -*/ \ No newline at end of file From 49ba90411ab4bd27482bc3a534db3ccff526948b Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Mon, 27 Feb 2023 22:10:06 -0500 Subject: [PATCH 0329/1894] Updated comments --- Linked List/LinkedList_Intersection_of_two.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Linked List/LinkedList_Intersection_of_two.py b/Linked List/LinkedList_Intersection_of_two.py index d44b0649..6e728c4f 100644 --- a/Linked List/LinkedList_Intersection_of_two.py +++ b/Linked List/LinkedList_Intersection_of_two.py @@ -5,12 +5,19 @@ # self.next = None class Solution: + #Maintaining hashset to store all the values def __init__(self): self.s=set() + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: + #Iterating through all the elements linked with headA + #Inserting them in the hashset while(headA!=None): self.s.add(headA) headA=headA.next + + #While iterating through elements linked with headB + #Return the first element which is already present in the hashset while(headB!=None): if(headB in self.s): return headB From f2ecaba2448e463ffce110638ef20f8ed39e8499 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Mon, 27 Feb 2023 22:35:45 -0500 Subject: [PATCH 0330/1894] Create Merge_sorted_arrays.py --- sorting/Merge_sorted_arrays.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 sorting/Merge_sorted_arrays.py diff --git a/sorting/Merge_sorted_arrays.py b/sorting/Merge_sorted_arrays.py new file mode 100644 index 00000000..e76136be --- /dev/null +++ b/sorting/Merge_sorted_arrays.py @@ -0,0 +1,33 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + #Time Complexity - O(M+N) + #Space Complexity - O(1) + + #Using similar to merge sort algorithm implementation. + #Traversing in reverse order and comparing m,n values. + #Placing the highest element last and continuing with the algorithm. + i,j,k=m-1,n-1,m+n-1 + while(i>=0 and j>=0): + if(nums1[i]>nums2[j]): + nums1[k]=nums1[i] + i-=1 + k-=1 + else: + nums1[k]=nums2[j] + j-=1 + k-=1 + + #placing left over elements from num1 to nums1 + while(i>=0): + nums1[k]=nums1[i] + i-=1 + k-=1 + + #placing left over elements from num2 to num1 + while(j>=0): + nums1[k]=nums2[j] + j-=1 + k-=1 From 1cb51faa8dcc5d6ecda28e1e6da32c47ba0cde5e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:24:56 +0530 Subject: [PATCH 0331/1894] remove duplicate files --- Leetcode/Graphs_jump.cpp | 91 ------------------- Leetcode/Graphs_kill_process.cpp | 77 ---------------- .../Median_of_Two_Sorted_Arrays_MergeSort.cpp | 73 --------------- Leetcode/arrays_strings_is_unique.cpp | 59 ------------ Leetcode/binary_tree_count_nodes.cpp | 52 ----------- ...binary_tree_diameter_of_a_tree_optimal.cpp | 68 -------------- Leetcode/binary_tree_preorder_traversal.cpp | 54 ----------- Leetcode/change_character.java | 77 ---------------- Leetcode/count_primes.py | 39 -------- Leetcode/edit_distance_dp.cpp | 53 ----------- Leetcode/is_al_num.java | 76 ---------------- Leetcode/longest_common_prefix.java | 72 --------------- ...min_steps_to_reduce_a_number_to_one_dp.cpp | 43 --------- Leetcode/next_greater_element.cpp | 35 ------- Leetcode/rod_cutting_problem_dp.cpp | 36 -------- Leetcode/sort_colors.java | 58 ------------ Leetcode/string_operations.java | 78 ---------------- Leetcode/validate_ip.java | 86 ------------------ 18 files changed, 1127 deletions(-) delete mode 100644 Leetcode/Graphs_jump.cpp delete mode 100644 Leetcode/Graphs_kill_process.cpp delete mode 100644 Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp delete mode 100644 Leetcode/arrays_strings_is_unique.cpp delete mode 100644 Leetcode/binary_tree_count_nodes.cpp delete mode 100644 Leetcode/binary_tree_diameter_of_a_tree_optimal.cpp delete mode 100644 Leetcode/binary_tree_preorder_traversal.cpp delete mode 100644 Leetcode/change_character.java delete mode 100644 Leetcode/count_primes.py delete mode 100644 Leetcode/edit_distance_dp.cpp delete mode 100644 Leetcode/is_al_num.java delete mode 100644 Leetcode/longest_common_prefix.java delete mode 100644 Leetcode/min_steps_to_reduce_a_number_to_one_dp.cpp delete mode 100644 Leetcode/next_greater_element.cpp delete mode 100644 Leetcode/rod_cutting_problem_dp.cpp delete mode 100644 Leetcode/sort_colors.java delete mode 100644 Leetcode/string_operations.java delete mode 100644 Leetcode/validate_ip.java diff --git a/Leetcode/Graphs_jump.cpp b/Leetcode/Graphs_jump.cpp deleted file mode 100644 index 42b3139e..00000000 --- a/Leetcode/Graphs_jump.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - Given an array of non-negative integers arr, - you are initially positioned at start index of the array. - When you are at index i, you can jump to i + arr[i] or i - arr[i], - check if you can reach to any index with value 0. - Notice that you can not jump outside of the array at any time. - Input: arr = [4,2,3,0,3,1,2], start = 5 - Output: true -*/ -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -template -class Graph{ - map > L; - public: - Graph(){ - - } - void add_edge(T u, T v, bool bidir = false){ - L[u].push_back(v); - if(bidir) - L[v].push_back(u); - } - void print_adj_list(){ - for(auto x : L){ - cout << x.first << "->"; - for(auto element : x.second){ - cout << element << ","; - } - cout << endl; - } - } - bool can_jump(T source, T destination){ - queue q; - map visited; - q.push(source); - visited[source] = true; - while(!q.empty()){ - T node = q.front(); - q.pop(); - for(T neighbours : L[node]){ - if(!visited[neighbours]){ - visited[neighbours] = true; - q.push(neighbours); - } - - } - } - if(!visited[destination]){ - return false; - } - return true; - } -}; -int main(){ - Graph g; - int n, starting_node; - - cin >> n >> starting_node; - vector vertices(n); - int pos_of_zero = 3; - - for(int i = 0; i < n; i++){ - cin >> vertices[i]; - } - for(int i = 0; i < n; i++){ - cout << vertices[i] << ","; - } - cout << endl; - g.add_edge(0, 0 + vertices[0]); - for(int i = 1; i < n - 1; i++){ - if(vertices[i] == 0) - continue; - if(i + vertices[i] > 0 && i + vertices[i] < n){ - g.add_edge(i, i + vertices[i]); - } - if(i - vertices[i] >= 0 && i - vertices[i] < n-1){ - g.add_edge(i, i - vertices[i]); - } - } - g.add_edge(n-1, (n-1) - vertices[n - 1]); - g.print_adj_list(); - cout << endl; - if(g.can_jump(starting_node, pos_of_zero)) - cout << "YES"; - else - cout << "No"; - - return 0; -} \ No newline at end of file diff --git a/Leetcode/Graphs_kill_process.cpp b/Leetcode/Graphs_kill_process.cpp deleted file mode 100644 index ff64d407..00000000 --- a/Leetcode/Graphs_kill_process.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* - Given a list of process where each process has a unique id and parent id. - Parent id is the id of the process that initiated that process. - You have to kill a particular process given by an integer kill. - Print id of all the processes that will be killed to kill that process - In order to kill a process, all its child processes should be killed as well - also only one process have parent id as 0 ie the process that started itself - Input : process id : [3, 1, 5, 7, 10, 11, 12] - parent id : [0, 3, 3, 5, 5, 10, 10] - kill_id : 5 - Output: [5, 7, 10, 11, 12] -*/ -#include -using namespace std; - -template -class Graph{ - map > L; - public: - Graph(){ - - } - void add_list(int u, int v, bool bidir = false){ - L[u].push_back(v); - if(bidir){ - L[v].push_back(u); - } - } - void print_graph(){ - for(T node : L){ - cout << node.first << "->"; - for(T neighbour: node.second){ - cout << neighbour << ","; - } - cout << endl; - } - } - void kill_process(int process){ - map visited; - queue q; - q.push(process); - visited[process] = true; - while(!q.empty()){ - int node = q.front(); - cout << node << "->"; - q.pop(); - for(T neighbour : L[node]){ - if(!visited[neighbour]){ - q.push(neighbour); - visited[neighbour] = true; - } - } - } - } -}; -int main(){ - Graph g; - int n; - cout << "Enter number of process : "; - cin >> n; - vector process_id(n); - vector parent_id(n); - for(int i = 0; i < n; i++){ - cin >> process_id[i]; - } - for(int i = 0; i < n; i++){ - cin >> parent_id[i]; - } - for(int i = 0; i < n; i++){ - g.add_list(parent_id[i], process_id[i]); - } - int kill; - cout << "Enter process to be killed : "; - cin >> kill; - g.kill_process(kill); - return 0; -} \ No newline at end of file diff --git a/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp b/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp deleted file mode 100644 index 81d81a2d..00000000 --- a/Leetcode/Median_of_Two_Sorted_Arrays_MergeSort.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Approach: - let nums1 = [1, 3, 4, 7, 10, 12], nums2 = [2, 3, 6, 15] - - In order to find the median, we need a single sorted array. So a naive approach is that, just merge the 2 sorted arrays and find the median of that array. - This will have a time Complexity of O(n1 + n2), Space Complexity of O(n1 + n2) -*/ - -# include - -class Solution { - std::vector merge(std::vector& nums1, std::vector& nums2){ - int n1 = nums1.size(); - int n2 = nums2.size(); - - int i=0, j=0; - - std::vector res; - while(i < n1 and j < n2){ - if(nums1[i] < nums2[j]){ - res.push_back(nums1[i]); - i++; - } else { - res.push_back(nums2[j]); - j++; - } - } - - while(i < n1){ - res.push_back(nums1[i]); - i++; - } - - while(j < n2){ - res.push_back(nums2[j]); - j++; - } - - return res; - } -public: - double findMedianSortedArrays(std::vector& nums1, std::vector& nums2) { - std::vector sortedarr = merge(nums1, nums2); - - if(sortedarr.size() % 2 == 0){ - return (sortedarr[sortedarr.size()/2] + sortedarr[sortedarr.size()/2 - 1])/2.0; - } else { - return (double)sortedarr[sortedarr.size()/2]; - } - } -}; - -int main(int argc, char const* argv[]) { - int n; - - std::cin >> n; - std::vector arr1(n, 0); - for (int i = 0;i < n;i++) { - std::cin >> arr1[i]; - } - - std::cin >> n; - std::vector arr2(n, 0); - for (int i = 0;i < n;i++) { - std::cin >> arr2[i]; - } - - Solution sol = Solution(); - double res = sol.findMedianSortedArrays(arr1, arr2); - - std::cout << res << "\n"; - return 0; -} \ No newline at end of file diff --git a/Leetcode/arrays_strings_is_unique.cpp b/Leetcode/arrays_strings_is_unique.cpp deleted file mode 100644 index 222aa54a..00000000 --- a/Leetcode/arrays_strings_is_unique.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Implement an algorithm to determine if a string has all unique characters. -// what if you cannot use additional data structures? -// Program Author : Abhisek Kumar Gupta -// Approach 1 : compare every character of string with other character TC O(n^2) -// Approach 2 : Sort the string and compare neighbouring character for dups -// TC of approach 2 : O(n log(n)) -#include -using namespace std; -bool is_unique_normal(string s){ - // using additional data structure - // TC O(min(c, n)) c being size of character set n = len of string - // SC is O(1) here - if(s.length() > 128) - return true; - bool visited[128]; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(visited[val]){ - return false; - } - visited[val] = true; - } - return true; -} -bool is_unique(string s){ - // without using additional data structures - // here we reduce our space usage - if(s.length() > 128) - return false; - int checker = 0; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(checker & (1 << val)) - return false; - checker |= (1 << val); - } - return true; -} -void print_ans(bool ans, string s){ - if(ans){ - cout << s << " is unique\n"; - } - else{ - cout << s << " is not unique\n"; - } -} -int main(){ - string s = "ABCDD"; - string t = "ABCD"; - string u = "AAAAAABCD"; - is_unique_normal(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique_normal(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique_normal(u) == true ? print_ans(true, u) : print_ans(false, u); - cout << "\n***********************\n"; - is_unique(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique(u) == true ? print_ans(true, u) : print_ans(false, u); - return 0; -} \ No newline at end of file diff --git a/Leetcode/binary_tree_count_nodes.cpp b/Leetcode/binary_tree_count_nodes.cpp deleted file mode 100644 index 236998bb..00000000 --- a/Leetcode/binary_tree_count_nodes.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Binary Tree : Count Number of Nodes -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : 9 -*/ - -#include -using namespace std; -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int d){ - data = d; - } -}; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1){ - return NULL; - } - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} -int count_number_of_nodes(Node* root){ - if(root == NULL) - return 0; - return 1 + count_number_of_nodes(root->left) + count_number_of_nodes(root->right); -} -int main(){ - Node* root = build_binary_tree(); - int number_of_nodes = count_number_of_nodes(root); - cout << number_of_nodes; - return 0; -} \ No newline at end of file diff --git a/Leetcode/binary_tree_diameter_of_a_tree_optimal.cpp b/Leetcode/binary_tree_diameter_of_a_tree_optimal.cpp deleted file mode 100644 index f21b774b..00000000 --- a/Leetcode/binary_tree_diameter_of_a_tree_optimal.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// Binary Tree : Diameter of tree O(n) -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : Height : 5 - Diameter : 7 -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -class Pair{ - public: - int height; - int diameter; -}; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} -Pair compute_diameter(Node* root){ - Pair p; - if(root == NULL){ - p.height = 0; - p.diameter = 0; - return p; - } - Pair left = compute_diameter(root->left); - Pair right = compute_diameter(root->right); - p.height = max(left.height, right.height) + 1; - p.diameter = max(left.height + right.height, max(left.diameter, right.diameter)); - return p; -} -int main(){ - Node* root = build_binary_tree(); - Pair p = compute_diameter(root); - cout << p.height << endl; - cout << p.diameter << endl; - return 0; -} \ No newline at end of file diff --git a/Leetcode/binary_tree_preorder_traversal.cpp b/Leetcode/binary_tree_preorder_traversal.cpp deleted file mode 100644 index b9456a0a..00000000 --- a/Leetcode/binary_tree_preorder_traversal.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Pre-Order Traversal of a Binary-Tree -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - -1 -1 -1 -1 -1 -1 - Input : 40 10 5 1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : 40->10->5->1->30->28->15->20 -*/ -#include -using namespace std; -class Node{ - public: - int data; - Node *left; - Node *right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } - -}; - -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} - -void print_binary_tree(Node* root){ - if(root == NULL) - return; - cout << root->data << "->"; - print_binary_tree(root->left); - print_binary_tree(root->right); -} - -int main(){ - Node* root = build_binary_tree(); - print_binary_tree(root); -} \ No newline at end of file diff --git a/Leetcode/change_character.java b/Leetcode/change_character.java deleted file mode 100644 index 28f05899..00000000 --- a/Leetcode/change_character.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * You are given a string A of size N consisting of lowercase alphabets. - * - * You can change at most B characters in the given string to any other lowercase alphabet such that the number of distinct characters in the string is minimized. - * - * Find the minimum number of distinct characters in the resulting string. - * - * - * - * Problem Constraints - * 1 <= N <= 100000 - * - * 0 <= B < N - * - * - * - * Input Format - * The first argument is a string A. - * - * The second argument is an integer B. - * - * - * - * Output Format - * Return an integer denoting the minimum number of distinct characters in the string. - * - * - * - * Example Input - * A = "abcabbccd" - * B = 3 - * - * - * - * Example Output - * 2 - * - * - * - * Example Explanation - * We can change both 'a' and one 'd' into 'b'.So the new string becomes "bbcbbbccb". - * So the minimum number of distinct character will be 2. - */ - -package Strings; - -import java.util.ArrayList; -import java.util.Collections; - -public class ChangeCharacter { - public static void main(String[] args) { - String string = "abcabbccd"; - int b = 3; - - int res = solve(string, b); - System.out.println(res); - } - public static int solve(String string, int b) { - - //count chars - int[] charsCount = new int[26]; - for (int i = 0; i < string.length(); i++) - ++charsCount[string.charAt(i) - 'a']; - - ArrayList arrayList = new ArrayList<>(); - for (int i = 0; i < 26; ++i) { - if (charsCount[i] > 0) arrayList.add(charsCount[i]); - } - - Collections.sort(arrayList); - for (int i = 0; i < arrayList.size(); ++i) { - b -= arrayList.get(i); - if (b < 0) return arrayList.size() - i; - } - return 1; - } -} diff --git a/Leetcode/count_primes.py b/Leetcode/count_primes.py deleted file mode 100644 index d0692e2a..00000000 --- a/Leetcode/count_primes.py +++ /dev/null @@ -1,39 +0,0 @@ -# Given an integer n, return the number of prime numbers that are strictly less than n. -# Program Author: https://github.com/abhis1n - -# Solution- We will be using Sieve of Eratosthenes to solve the given problem - -class Solution: - def countPrimes(self, n: int) -> int: - # First we declare an array of - # size n and initialize all of - # its values with False - nums = [False] * n - - # Storing primes in ans variable - ans = 0 - - for num in range(2, n): - # if the num index in nums list - # is True, if block runs and loop - # is continued to next iteration - if nums[num]: - continue - - # else if the num index in nums list - # is False, ans variable is incremented - # by 1 and the indexes of all values - # greater than num and divisible by num - # are updated with True value, since they - # can not be prime - else: - ans += 1 - nums[num*num:n:num] = [True] * ((n - 1) // num - num + 1) - - return ans - -if __name__=='__main__': - n = int(input()) - solution = Solution() - answer = solution.countPrimes(n) - print(answer) \ No newline at end of file diff --git a/Leetcode/edit_distance_dp.cpp b/Leetcode/edit_distance_dp.cpp deleted file mode 100644 index 5b110203..00000000 --- a/Leetcode/edit_distance_dp.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - Given two strings str1 and str2 and following three operations that can performed on str1. - 1) Insert - 2) Remove - 3) Replace - Find minimum number of operations required to convert ‘str1’ into ‘str2’. - For example if input strings are CAT AND CAR the edit distance is 1. - - Input : s1 : saturday s2 : sunday - Output : 3 -*/ -// Dynamic Programming Solution : TC O(n^2) -// Porgram Author : Abhisek Kumar Gupta -#include -using namespace std; -int find_edit_distance(string s1, string s2, int l1, int l2){ - int dp[100][100] = {}; - for(int i = 0; i <= l1; i++){ - dp[i][0] = i; - } - for(int i = 0; i <= l2; i++){ - dp[0][i] = i; - } - for(int i = 1; i <= l1; i++){ - for(int j = 1; j <= l2; j++){ - if(s1[i] == s2[j]){ - dp[i][j] = dp[i - 1][j - 1]; - } - else{ - int del = dp[i][j - 1]; - int replace = dp[i - 1][j - 1]; - int insert = dp[i - 1][j]; - dp[i][j] = min(del, min(replace, insert)) + 1; - } - } - } - for(int i = 0; i <= l1; i++){ - for(int j = 0; j <= l2; j++){ - cout << setw(5) < -using namespace std; -int dp[10000]; -int find_min_steps(int number){ - int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - dp[0] = 0; - dp[1] = 0; - dp[2] = 1; - dp[3] = 1; - for(int i = 4; i <= number; i++){ - r1 = 1 + dp[i - 1]; - if(i % 2 == 0) - r2 = 1 + dp[i / 2]; - if(i % 3 == 0) - r3 = 1 + dp[i / 3]; - dp[i] = min(r1, min(r2, r3)); - r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - } - - return dp[number]; -} -int main(){ - int number; - cin >> number; - memset(dp, 0, sizeof(dp)); - int result = find_min_steps(number); - cout << result; - return 0; -} \ No newline at end of file diff --git a/Leetcode/next_greater_element.cpp b/Leetcode/next_greater_element.cpp deleted file mode 100644 index c8dbd7d1..00000000 --- a/Leetcode/next_greater_element.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* -You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2. -Find all the next greater numbers for nums1's elements in the corresponding places of nums2. -The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. -If it does not exist, return -1 for this number. -Input: nums1 = [4,1,2], nums2 = [1,3,4,2] -Output: [-1,3,-1] -Explanation: -For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. -For number 1 in the first array, the next greater number for it in the second array is 3. -For number 2 in the first array, there is no next greater number for it in the second array, so output -1. -*/ - vector nextGreaterElement(vector& nums1, vector& nums2) { - vector result(nums1.size(), -1); - stack st; - unordered_map umap; - // we will keep pushing the element into stack unless element in num2 is less than TOS - // if element is greater then we map TOS with element and pop out the TOS - for(auto element : nums2){ - while(!st.empty() && element > st.top()){ - umap[st.top()] = element; - st.pop(); - } - st.push(element); - } - // mapping is complete now we just traverse first array i.e num1 and check if its present in map - // if its present in map then we store it in result or we escape - // note : result already is populated with -1's for cases such as if NGE is not present - for(int i = 0; i < nums1.size(); i++){ - if(umap.find(nums1[i]) != umap.end()){ - result[i] = umap[nums1[i]]; - } - } - return result; - } \ No newline at end of file diff --git a/Leetcode/rod_cutting_problem_dp.cpp b/Leetcode/rod_cutting_problem_dp.cpp deleted file mode 100644 index 0aa8e363..00000000 --- a/Leetcode/rod_cutting_problem_dp.cpp +++ /dev/null @@ -1,36 +0,0 @@ - /* - Given a rod of length n inches and an array of prices that contains prices of all - pieces of size smaller than n. Determine the maximum value obtainable by cutting - up the rod and selling the pieces. For example, if length of the rod is 8 and the - values of different pieces are given as following, then the maximum obtainable - value is 22 (by cutting in two pieces of lengths 2 and 6) - Input : 8 - : 1 5 8 9 10 17 17 20 - Output : 22 -*/ -// Dynamic Programming solution TC : O(n^2) -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -int max_profit(vector profit, int total_length){ - int dp[100] = {}; - for(int length = 1; length <= total_length; length++){ - int best = 0; - for(int cut = 1; cut <= length; cut++){ - best = max(best, profit[cut] + dp[length - cut]); - } - dp[length] = best; - } - return dp[total_length]; -} -int main(){ - int total_length; - cin >> total_length; - vector profit(total_length + 1); - for(int length = 1; length <= total_length; length++) - cin >> profit[length]; - int result = max_profit(profit, total_length); - cout << result; - return 0; -} - diff --git a/Leetcode/sort_colors.java b/Leetcode/sort_colors.java deleted file mode 100644 index b977ca04..00000000 --- a/Leetcode/sort_colors.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ------ Problem explanation ----- -Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. - -We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. - -You must solve this problem without using the library's sort function. - -Example 1: - -Input: nums = [2,0,2,1,1,0] -Output: [0,0,1,1,2,2] - -Example 2: - -Input: nums = [2,0,1] -Output: [0,1,2] - -Constraints: - -n == nums.length -1 <= n <= 300 -nums[i] is either 0, 1, or 2. - ------ Approach ----- - -Take 3 Pointers low = 0, mid = 0 and high = nums.length -1; -Use loop to iterate the array with condition mid <= high.(Since we only need to check middle elements of low and high). -if element is 0 swap with low and low++, mid++. -if element is 1 then mid++. -if element is 2 then swap with high and high--. -*/ -class Solution { - public void sortColors(int[] nums) { - int low = 0, mid = 0, high = nums.length-1; - - while(mid <= high){ - if(nums[mid] == 0 ){ - //swap with left - swap(nums,low, mid ); - low++; - mid++; - }else if(nums[mid] == 2){ - swap(nums, mid, high); - high--; - }else{ - mid++; - } - } - System.out.println(nums); - } - - public static void swap(int[] nums, int i, int j){ - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } -} diff --git a/Leetcode/string_operations.java b/Leetcode/string_operations.java deleted file mode 100644 index 01a42793..00000000 --- a/Leetcode/string_operations.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Akash likes playing with strings. One day he thought of applying following operations on the string in the given order: - * - * Concatenate the string with itself. - * Delete all the uppercase letters. - * Replace each vowel with '#'. - * You are given a string A of size N consisting of lowercase and uppercase alphabets. Return the resultant string after applying the above operations. - * - * NOTE: 'a' , 'e' , 'i' , 'o' , 'u' are defined as vowels. - * - * - * - * Problem Constraints - * - * 1<=N<=100000 - * - * - * Input Format - * - * First argument is a string A of size N. - * - * - * - * Output Format - * - * Return the resultant string. - * - * - * - * Example Input - * - * A="AbcaZeoB" - * - * - * - * Example Output - * - * "bc###bc###" - * - * - * - * Example Explanation - * - * First concatenate the string with itself so string A becomes "AbcaZeoBAbcaZeoB". - * Delete all the uppercase letters so string A becomes "bcaeobcaeo". - * Now replace vowel with '#'. - * A becomes "bc###bc###". - */ -package Strings; - -public class StringOperations { - public static void main(String[] args) { - String string = "AbcaZeoB"; - - String res = solve(string); - System.out.println(res); - } - public static String solve(String string) { - // O(N) time | O(N) space - where N is the length of string - StringBuilder stringBuilder = new StringBuilder(); - - for (int i = 0; i < string.length(); i++) { - char currentChar = string.charAt(i); - - if (currentChar >= 'a' && currentChar <= 'z') { - if (currentChar == 'a' || - currentChar == 'e' || - currentChar == 'i' || - currentChar == 'o' || - currentChar == 'u' - ) stringBuilder.append('#'); - else stringBuilder.append(string.charAt(i)); - } - } - - return stringBuilder.toString().concat(stringBuilder.toString()); - } -} diff --git a/Leetcode/validate_ip.java b/Leetcode/validate_ip.java deleted file mode 100644 index 48eefc5d..00000000 --- a/Leetcode/validate_ip.java +++ /dev/null @@ -1,86 +0,0 @@ -/* -Given a string queryIP, return "IPv4" if IP is a valid IPv4 address, - "IPv6" if IP is a valid IPv6 address or "Neither" if IP is not a correct IP of any type. - -A valid IPv4 address is an IP in the form "x1.x2.x3.x4" where 0 <= xi <= 255 and -xi cannot contain leading zeros. For example, "192.168.1.1" and "192.168.1.0" are -valid IPv4 addresses while "192.168.01.1", "192.168.1.00", and "192.168@1.1" are invalid IPv4 addresses. - -A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8" where: - -1 <= xi.length <= 4 -xi is a hexadecimal -string which may contain digits, lowercase English letter - ('a' to 'f') and upper-case English letters ('A' to 'F'). -Leading zeros are allowed in xi. -For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334" and - "2001:db8:85a3:0:0:8A2E:0370:7334" are valid IPv6 addresses, while - "2001:0db8:85a3::8A2E:037j:7334" and "02001:0db8:85a3:0000:0000:8a2e:0370:7334" are invalid IPv6 addresses. */ - - -/* - * Input: queryIP = "172.16.254.1" -Output: "IPv4" -Explanation: This is a valid IPv4 address, return "IPv4". - -Input: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334" -Output: "IPv6" -Explanation: This is a valid IPv6 address, return "IPv6". - -Input: queryIP = "256.256.256.256" -Output: "Neither" -Explanation: This is neither a IPv4 address nor a IPv6 address. - */ - - - - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.Scanner; - class Solution{ - public String validIPAddress(String queryIP) { - if(isValidIPv4(queryIP)) - return "IPv4"; - else if(isValidIPv6(queryIP)) - return "IPv6"; - - return "Neither"; - - } - - public static boolean isValidIPv4(String ip) - { - String parts - = "^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; - String regex - = "^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\\.(?!$)|$)){4}$"; - Pattern checkIp = Pattern.compile(regex); - - if (ip == null) - return false; - Matcher m = checkIp.matcher(ip); - return m.matches(); - } - public static boolean isValidIPv6(String ip) - { - String regex - = "^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$"; - Pattern checkIp= Pattern.compile(regex,Pattern.CASE_INSENSITIVE); - - if (ip == null) - return false; - Matcher m = checkIp.matcher(ip); - return m.matches(); - } - -} - -class ValiDateIp{ -public static void main(String args[]){ - Scanner inp=new Scanner(System.in); - Solution sol=new Solution(); - String queryIp=inp.next(); - System.out.print(sol.validIPAddress(queryIp)); - } -} \ No newline at end of file From 6196015f52161e3b9e97f78e80587b900ef3c209 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:29:45 +0530 Subject: [PATCH 0332/1894] remove intersection of two --- Linked List/LinkedList_Intersection_of_two.py | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 Linked List/LinkedList_Intersection_of_two.py diff --git a/Linked List/LinkedList_Intersection_of_two.py b/Linked List/LinkedList_Intersection_of_two.py deleted file mode 100644 index 6e728c4f..00000000 --- a/Linked List/LinkedList_Intersection_of_two.py +++ /dev/null @@ -1,24 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - #Maintaining hashset to store all the values - def __init__(self): - self.s=set() - - def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: - #Iterating through all the elements linked with headA - #Inserting them in the hashset - while(headA!=None): - self.s.add(headA) - headA=headA.next - - #While iterating through elements linked with headB - #Return the first element which is already present in the hashset - while(headB!=None): - if(headB in self.s): - return headB - headB=headB.next From 8dead5fdae3f80a1ef7dbee3c53c27c7742889c6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:31:10 +0530 Subject: [PATCH 0333/1894] rfmt code --- sorting/Merge_sorted_arrays.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/sorting/Merge_sorted_arrays.py b/sorting/Merge_sorted_arrays.py index e76136be..e7d0813d 100644 --- a/sorting/Merge_sorted_arrays.py +++ b/sorting/Merge_sorted_arrays.py @@ -9,25 +9,25 @@ def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: #Using similar to merge sort algorithm implementation. #Traversing in reverse order and comparing m,n values. #Placing the highest element last and continuing with the algorithm. - i,j,k=m-1,n-1,m+n-1 - while(i>=0 and j>=0): - if(nums1[i]>nums2[j]): - nums1[k]=nums1[i] - i-=1 - k-=1 + i, j, k = m - 1, n - 1, m + n - 1 + while(i >= 0 and j >= 0): + if(nums1[i] > nums2[j]): + nums1[k] = nums1[i] + i -= 1 + k -= 1 else: - nums1[k]=nums2[j] - j-=1 - k-=1 + nums1[k] = nums2[j] + j -= 1 + k -= 1 #placing left over elements from num1 to nums1 - while(i>=0): - nums1[k]=nums1[i] - i-=1 - k-=1 + while(i >= 0): + nums1[k] = nums1[i] + i -= 1 + k -= 1 #placing left over elements from num2 to num1 - while(j>=0): - nums1[k]=nums2[j] - j-=1 - k-=1 + while(j >= 0): + nums1[k] = nums2[j] + j -= 1 + k -= 1 From 0b54b4bfc3767aaeb243c1fd29ed6b7c18a03da8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:33:05 +0530 Subject: [PATCH 0334/1894] add link to pallindrome linked list --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ecb58e78..ed55001d 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ The key idea is that the pointers start at the same location, but they move forw - Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) -- Pallindrome Linked List +- Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) - Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) From a24d67c507d9e8f6d0f9fd2c3703cda01b303002 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:35:03 +0530 Subject: [PATCH 0335/1894] update link for max in sliding window --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ed55001d..6f9342c5 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ Instead, what if we focused on the element entering the window and the one leavi ## Practice problems for sliding window -- Find Maximum in Sliding Window +- Find Maximum in Sliding Window [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.py) - Minimum Window Subsequence - Repeated DNA Sequences - Minimum Window Substring From f759f1a699b9992a56e9097e9e55a881a979c834 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:36:59 +0530 Subject: [PATCH 0336/1894] add link for longest substring without repeating character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6f9342c5..abb3cf51 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ Instead, what if we focused on the element entering the window and the one leavi - Minimum Window Subsequence - Repeated DNA Sequences - Minimum Window Substring -- Longest Substring without Repeating Characters +- Longest Substring without Repeating Characters [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/longest_substring_without_repeating_characters.go) # Pattern 4: Merge Interval From 88eec448557020b9bce42f2235ae1e43aaf67d50 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Feb 2023 22:39:49 +0530 Subject: [PATCH 0337/1894] add link for linked list swap and reverse --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index abb3cf51..2baeb2c1 100644 --- a/README.md +++ b/README.md @@ -130,11 +130,11 @@ Similarly, for space complexity: the naive approach requires the use of addition ## Practice problems for in-place reversal of a linked list -- Reverse Linked List +- Reverse Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_reverse.cpp) - Reverse Nodes in k-group - Reorder List - Swapping Nodes in a Linked List -- Swapping Nodes in Pairs +- Swapping Nodes in Pairs [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_swap_nodes_in_pair.cpp) - Reverse Nodes in Even Length Groups # Pattern 6: Two Heaps From a1d6e3e78fcb30883e7b895c3cfab5741019a035 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:44:51 +0530 Subject: [PATCH 0338/1894] remove oop directory --- OOP/basic.cpp | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 OOP/basic.cpp diff --git a/OOP/basic.cpp b/OOP/basic.cpp deleted file mode 100644 index fe8f4a42..00000000 --- a/OOP/basic.cpp +++ /dev/null @@ -1,15 +0,0 @@ -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class Car{ - public: - int price; - int model_no; - char name[20]; -}; -int main(){ - Car C; - cout << sizeof(C) << "\n"; - cout << sizeof(Car); - return 0; -} \ No newline at end of file From 47c3110da0807ca2c04598e603e7a6b7fabf756e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:45:07 +0530 Subject: [PATCH 0339/1894] remove duplicate file --- CCTI/linked_list_kth_node_from_end.cpp | 89 -------------------------- 1 file changed, 89 deletions(-) delete mode 100644 CCTI/linked_list_kth_node_from_end.cpp diff --git a/CCTI/linked_list_kth_node_from_end.cpp b/CCTI/linked_list_kth_node_from_end.cpp deleted file mode 100644 index fdc9e80d..00000000 --- a/CCTI/linked_list_kth_node_from_end.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Finding Kth node from end of a LinkedList -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class node{ - public: - int data; - node* next; - node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(node *&head, int data){ - if(head == NULL){ - head = new node(data); - return; - } - node *n = new node(data); - node * temp = head; - while(temp -> next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void makeLinkedList(node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -node* kth_node_from_end(node *head, int k){ - if(head->next == NULL || head == NULL){ - return head; - } - node *slow = head; - node *fast = head; - while(k--){ - fast = fast->next; - } - while(fast){ - fast = fast->next; - slow = slow->next; - } - return slow; -} -node* kth_node_from_end_recursive(node *head, int k, int &i){ - if(head == NULL) - return NULL; - node *n = kth_node_from_end_recursive(head->next, k, i); - i = i + 1; - // cout << "i is " << i << "\n"; - if(i == k){ - // cout<<"i equals k\n"; - return head; - } - return n; -} -int main(){ - /* - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - int k; - cin >> k; - node *kth_node = kth_node_from_end(head, k); - cout << endl; - cout << kth_node->data << endl; - */ - node *head = NULL; - makeLinkedList(head); - print_linked_list(head); - int k; - cin >> k; - int i = 0; - node *kth_node = kth_node_from_end_recursive(head, k, i); - cout << endl; - cout << kth_node->data << endl; - - return 0; -} \ No newline at end of file From 9497b4a3cb305733876a0266bfbde1ec188fa1fb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:45:31 +0530 Subject: [PATCH 0340/1894] remove duplicate file --- CCTI/Graphs_cycle_detection_dfs.cpp | 69 ----------------------------- 1 file changed, 69 deletions(-) delete mode 100644 CCTI/Graphs_cycle_detection_dfs.cpp diff --git a/CCTI/Graphs_cycle_detection_dfs.cpp b/CCTI/Graphs_cycle_detection_dfs.cpp deleted file mode 100644 index 3fb137a8..00000000 --- a/CCTI/Graphs_cycle_detection_dfs.cpp +++ /dev/null @@ -1,69 +0,0 @@ -#include -using namespace std; -template -class Graph{ - map > L; - public: - Graph(){ - - } - void add_edge(int u, int v, bool bidir = false){ - L[u].push_back(v); - if(bidir){ - L[v].push_back(u); - } - } - void print_graph(){ - for(auto i : L){ - cout << i.first << "->"; - for(auto x: i.second){ - cout << x << ","; - } - cout << endl; - } - } - bool is_cyclic_helper(T node, map &visited, map &in_stack){ - visited[node] = true; - in_stack[node] = true; - for(T neighbour : L[node]){ - if((!visited[neighbour] && is_cyclic_helper(neighbour, visited, in_stack)) || in_stack[neighbour]){ - return true; - } - } - in_stack[node] = false; - return false; - } - bool is_cyclic(){ - map visited; - map in_stack; - for(auto i : L){ - T node = i.first; - bool result = is_cyclic_helper(node, visited, in_stack); - if(result){ - return true; - } - else{ - return false; - } - - } - } -}; -int main(){ - Graph g; - g.add_edge(0, 2); - g.add_edge(0, 1); - g.add_edge(2, 3); - g.add_edge(2, 4); - g.add_edge(3, 4); - //g.add_edge(5, 0); // uncomment to make cycle - //g.add_edge(3, 0); //uncomment to make cycle - g.add_edge(4, 5); - g.add_edge(1, 5); - if(g.is_cyclic()){ - cout << "Graph is Cyclic\n"; - } - else{ - cout << "Graph is Not Cyclic\n"; - } -} \ No newline at end of file From e68aa99053228323a653af34098e481c1ccc72e3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:45:51 +0530 Subject: [PATCH 0341/1894] remove duplicate file --- CCTI/linked_list_delete_middle.cpp | 55 ------------------------------ 1 file changed, 55 deletions(-) delete mode 100644 CCTI/linked_list_delete_middle.cpp diff --git a/CCTI/linked_list_delete_middle.cpp b/CCTI/linked_list_delete_middle.cpp deleted file mode 100644 index c2ad9ed3..00000000 --- a/CCTI/linked_list_delete_middle.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// Delete Middle node [given only access to that node] -// Note : No head node is given -// Program Author : Abhisek Kumar Gupta -// Sample Input : 5 4 3 2 1, delete 3rd node -// Output: 5 4 2 1 -#include -using namespace std; -class Node{ - public: - int data; - Node *next; - - Node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_head(Node *&head, int data){ - Node *n = new Node(data); - n->next = head; - head = n; -} -void make_linked_list(Node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_head(head, data); - cin >> data; - } -} -void print_linked_list(Node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -bool delete_from_middle(Node *that_node){ - if(that_node == NULL || that_node->next == NULL){ - return false; - } - Node *forward = that_node->next; - that_node->data = forward->data; - that_node->next = forward->next; - delete forward; -} -int main(){ - Node *head = NULL; - make_linked_list(head); - print_linked_list(head); cout << endl; - - if(delete_from_middle(head->next->next)){ - print_linked_list(head); - } - return 0; -} \ No newline at end of file From 69e315ba2f1f498babe20b84c1d18649545561b4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:46:10 +0530 Subject: [PATCH 0342/1894] remove duplicate file --- CCTI/linked_list_remove_dups.cpp | 91 -------------------------------- 1 file changed, 91 deletions(-) delete mode 100644 CCTI/linked_list_remove_dups.cpp diff --git a/CCTI/linked_list_remove_dups.cpp b/CCTI/linked_list_remove_dups.cpp deleted file mode 100644 index ab0ae0ec..00000000 --- a/CCTI/linked_list_remove_dups.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// Remove duplicates from an unsorted linked list -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -class Node{ - public: - int data; - Node *next; - - Node(int d){ - data = d; - next = NULL; - } -}; -void insert_at_tail(Node *&head, int data){ - if(head == NULL){ - head = new Node(data); - return; - } - Node *n = new Node(data); - Node *temp = head; - while(temp->next != NULL){ - temp = temp->next; - } - temp->next = n; -} -void print_linked_list(Node *head){ - while(head != NULL){ - cout << head->data << "->"; - head = head->next; - } -} -void make_linked_list(Node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_tail(head, data); - cin >> data; - } -} -void remove_duplicates(Node *&head){ - set S; - Node *temp = head; - Node *prev = NULL; - Node *remove = NULL; - while(temp != NULL){ - if(S.find(temp->data) != S.end()){ - remove = temp; - prev->next = temp->next; - } - else{ - S.insert(temp->data); - prev = temp; - } - temp = temp->next; - delete remove; - } -} -void remove_duplicates_without_buffer(Node *&head){ - Node *current = head; - Node *remove = NULL; - while(current != NULL){ - Node *runner = current; - while(runner->next != NULL){ - if(runner->next->data == current->data){ - remove = runner->next; - runner->next = runner->next->next; - delete remove; - } - else{ - runner = runner->next; - } - } - current = current->next; - } -} -int main(){ - Node *head = NULL; - /* - make_linked_list(head); - print_linked_list(head); - cout << endl; - remove_duplicates(head); - print_linked_list(head); - */ - make_linked_list(head); - print_linked_list(head); - cout << endl; - remove_duplicates_without_buffer(head); - print_linked_list(head); -} \ No newline at end of file From 32104a47b6b776686a9e0eb077001a36f7d06347 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:46:26 +0530 Subject: [PATCH 0343/1894] remove duplicate file --- CCTI/linked_list_sum_lists.cpp | 68 ---------------------------------- 1 file changed, 68 deletions(-) delete mode 100644 CCTI/linked_list_sum_lists.cpp diff --git a/CCTI/linked_list_sum_lists.cpp b/CCTI/linked_list_sum_lists.cpp deleted file mode 100644 index e3aeb672..00000000 --- a/CCTI/linked_list_sum_lists.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// sum Lists : you have two numbers represented by a linked list -// where each node contains a single digit, write a function -// to add two numbers and returns the sum as linked list -// Program Author: Abhisek Kumar Gupta -#include -using namespace std; -class Node{ - public: - int data; - Node *next; - - Node(int d){ - data = d; - } -}; - -void insert_at_head(Node *&head, int data){ - Node *new_node = new Node(data); - new_node->next = head; - head = new_node; -} -void print_linked_list(Node *head){ - if(head == NULL) - return; - cout << head->data << "->"; - print_linked_list(head->next); -} -void make_linked_list(Node *&head){ - int data; - cin >> data; - while(data != -1){ - insert_at_head(head, data); - cin >> data; - } -} -Node* add_lists(Node *l1, Node *l2, int carry){ - - if(l1 == NULL && l2 == NULL && carry == 0) - return NULL; - int value = carry; - - if(l1 != NULL) - value += l1->data; - - if(l2 != NULL) - value += l2->data; - - Node *result = new Node(value % 10); - - if(l1 != NULL || l2 != NULL) - result->next = add_lists(l1 == NULL ? NULL : l1->next, l2 == NULL ? NULL : l2->next, value >= 10 ? 1 : 0); - else - result->next = NULL; - - return result; -} -int main(){ - Node *head1 = NULL; - Node *head2 = NULL; - make_linked_list(head1); - make_linked_list(head2); - print_linked_list(head1); - cout << endl; - print_linked_list(head2); - Node *result = add_lists(head1, head2, 0); - cout << endl; - print_linked_list(result); -} \ No newline at end of file From 2df236204e9e9a04185881ebce5e0ec1b6bc899f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:47:33 +0530 Subject: [PATCH 0344/1894] move from ccti to arrays --- .../arrays_strings_check_permutations.cpp | 90 ++++++------ {CCTI => Arrays}/arrays_strings_is_unique.cpp | 116 ++++++++-------- {CCTI => Arrays}/arrays_strings_is_unique.go | 0 {CCTI => Arrays}/arrays_strings_one_away.cpp | 128 +++++++++--------- ...rays_strings_pallindromic_permutations.cpp | 122 ++++++++--------- ...gs_pallindromic_permutations_effecient.cpp | 116 ++++++++-------- {CCTI => Arrays}/arrays_strings_urlify.cpp | 74 +++++----- {CCTI => Arrays}/urlify.go | 0 8 files changed, 323 insertions(+), 323 deletions(-) rename {CCTI => Arrays}/arrays_strings_check_permutations.cpp (96%) rename {CCTI => Arrays}/arrays_strings_is_unique.cpp (97%) rename {CCTI => Arrays}/arrays_strings_is_unique.go (100%) rename {CCTI => Arrays}/arrays_strings_one_away.cpp (96%) rename {CCTI => Arrays}/arrays_strings_pallindromic_permutations.cpp (97%) rename {CCTI => Arrays}/arrays_strings_pallindromic_permutations_effecient.cpp (96%) rename {CCTI => Arrays}/arrays_strings_urlify.cpp (96%) rename {CCTI => Arrays}/urlify.go (100%) diff --git a/CCTI/arrays_strings_check_permutations.cpp b/Arrays/arrays_strings_check_permutations.cpp similarity index 96% rename from CCTI/arrays_strings_check_permutations.cpp rename to Arrays/arrays_strings_check_permutations.cpp index 1b029443..52b27a3d 100644 --- a/CCTI/arrays_strings_check_permutations.cpp +++ b/Arrays/arrays_strings_check_permutations.cpp @@ -1,46 +1,46 @@ -// Implement an algorithm to determine if a string is permutation of other. -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -bool check_permutation(string s, string t){ - // Time complexity O(n log (n)) n = len of string - // but its clean simple and easy to understand - if(s.length() != t.length()) - return false; - sort(s.begin(), s.end()); - sort(t.begin(), t.end()); - if(s.compare(t) == 0) - return true; - return false; -} -bool check_permutation_fast(string s, string t){ - // TC O(n) - if(s.length() != t.length()) - return false; - map letters; - for(char c : s){ - letters[c]++; - } - for(char c : t){ - letters[c]--; - if(letters[c] < 0){ - return false; - } - } - return true; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -int main(){ - check_permutation("ABDE", "DEBA") == true ? print_ans(true) : print_ans(false); - check_permutation("ABCD", "DEFG") == true ? print_ans(true) : print_ans(false); - check_permutation_fast("AA", "DEBA") == true ? print_ans(true) : print_ans(false); - check_permutation_fast("ADEB", "ABED") == true ? print_ans(true) : print_ans(false); - return 0; +// Implement an algorithm to determine if a string is permutation of other. +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +bool check_permutation(string s, string t){ + // Time complexity O(n log (n)) n = len of string + // but its clean simple and easy to understand + if(s.length() != t.length()) + return false; + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + if(s.compare(t) == 0) + return true; + return false; +} +bool check_permutation_fast(string s, string t){ + // TC O(n) + if(s.length() != t.length()) + return false; + map letters; + for(char c : s){ + letters[c]++; + } + for(char c : t){ + letters[c]--; + if(letters[c] < 0){ + return false; + } + } + return true; +} +void print_ans(bool ans){ + if(ans){ + cout << "YES\n"; + } + else{ + cout << "NO\n"; + } +} +int main(){ + check_permutation("ABDE", "DEBA") == true ? print_ans(true) : print_ans(false); + check_permutation("ABCD", "DEFG") == true ? print_ans(true) : print_ans(false); + check_permutation_fast("AA", "DEBA") == true ? print_ans(true) : print_ans(false); + check_permutation_fast("ADEB", "ABED") == true ? print_ans(true) : print_ans(false); + return 0; } \ No newline at end of file diff --git a/CCTI/arrays_strings_is_unique.cpp b/Arrays/arrays_strings_is_unique.cpp similarity index 97% rename from CCTI/arrays_strings_is_unique.cpp rename to Arrays/arrays_strings_is_unique.cpp index 1cee4c23..de7376ea 100644 --- a/CCTI/arrays_strings_is_unique.cpp +++ b/Arrays/arrays_strings_is_unique.cpp @@ -1,59 +1,59 @@ -// Implement an algorithm to determine if a string has all unique characters. -// what if you cannot use additional data structures? -// Program Author : Abhisek Kumar Gupta -// Approach 1 : compare every character of string with other character TC O(n^2) -// Approach 2 : Sort the string and compare neighbouring character for dups -// TC of approach 2 : O(n log(n)) -#include -using namespace std; -bool is_unique_normal(string s){ - // using additional data structure - // TC O(min(c, n)) c being size of character set n = len of string - // SC is O(1) here - if(s.length() > 128) - return false; - bool visited[128]; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(visited[val]){ - return false; - } - visited[val] = true; - } - return true; -} -bool is_unique(string s){ - // without using additional data structures - // here we reduce our space usage - if(s.length() > 128) - return false; - int checker = 0; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(checker & (1 << val)) - return false; - checker |= (1 << val); - } - return true; -} -void print_ans(bool ans, string s){ - if(ans){ - cout << s << " is unique\n"; - } - else{ - cout << s << " is not unique\n"; - } -} -int main(){ - string s = "ABCDD"; - string t = "ABCD"; - string u = "AAAAAABCD"; - is_unique_normal(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique_normal(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique_normal(u) == true ? print_ans(true, u) : print_ans(false, u); - cout << "\n***********************\n"; - is_unique(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique(u) == true ? print_ans(true, u) : print_ans(false, u); - return 0; +// Implement an algorithm to determine if a string has all unique characters. +// what if you cannot use additional data structures? +// Program Author : Abhisek Kumar Gupta +// Approach 1 : compare every character of string with other character TC O(n^2) +// Approach 2 : Sort the string and compare neighbouring character for dups +// TC of approach 2 : O(n log(n)) +#include +using namespace std; +bool is_unique_normal(string s){ + // using additional data structure + // TC O(min(c, n)) c being size of character set n = len of string + // SC is O(1) here + if(s.length() > 128) + return false; + bool visited[128]; + for(int i = 0; i < s.length(); i++){ + int val = s[i] - 'a'; + if(visited[val]){ + return false; + } + visited[val] = true; + } + return true; +} +bool is_unique(string s){ + // without using additional data structures + // here we reduce our space usage + if(s.length() > 128) + return false; + int checker = 0; + for(int i = 0; i < s.length(); i++){ + int val = s[i] - 'a'; + if(checker & (1 << val)) + return false; + checker |= (1 << val); + } + return true; +} +void print_ans(bool ans, string s){ + if(ans){ + cout << s << " is unique\n"; + } + else{ + cout << s << " is not unique\n"; + } +} +int main(){ + string s = "ABCDD"; + string t = "ABCD"; + string u = "AAAAAABCD"; + is_unique_normal(s) == true ? print_ans(true, s) : print_ans(false, s); + is_unique_normal(t) == true ? print_ans(true, t) : print_ans(false, t); + is_unique_normal(u) == true ? print_ans(true, u) : print_ans(false, u); + cout << "\n***********************\n"; + is_unique(s) == true ? print_ans(true, s) : print_ans(false, s); + is_unique(t) == true ? print_ans(true, t) : print_ans(false, t); + is_unique(u) == true ? print_ans(true, u) : print_ans(false, u); + return 0; } \ No newline at end of file diff --git a/CCTI/arrays_strings_is_unique.go b/Arrays/arrays_strings_is_unique.go similarity index 100% rename from CCTI/arrays_strings_is_unique.go rename to Arrays/arrays_strings_is_unique.go diff --git a/CCTI/arrays_strings_one_away.cpp b/Arrays/arrays_strings_one_away.cpp similarity index 96% rename from CCTI/arrays_strings_one_away.cpp rename to Arrays/arrays_strings_one_away.cpp index 13114755..c7332b3a 100644 --- a/CCTI/arrays_strings_one_away.cpp +++ b/Arrays/arrays_strings_one_away.cpp @@ -1,64 +1,64 @@ -// Given two strings write a function to check if they are one edit(or zero edits) away -// Program Author : Abhisek Kumar Gupta - -// Sample Input : Pale Ple -// Output : Yes Pale -// Sample Input : Pale bae -// Output : No -#include -using namespace std; -bool one_edit_replace(string a, string b){ - bool found_difference = false; - for(int i = 0; i < a.length(); i++){ - if(a[i] != b[i]){ - if(found_difference){ - return false; - } - found_difference = true; - } - } - return true; -} -bool one_edit_insert(string a, string b){ - int i1 = 0, i2 = 0; - while(i1 < a.length() && i2 < b.length()){ - if(a[i1] != b[i2]){ - if(i1 != i2){ - return false; - } - i2++; - } - else{ - i1++; - i2++; - } - } - return true; -} -bool is_one_edit_away(string a, string b){ - if(a.length() == b.length()){ - return one_edit_replace(a, b); - } - else if(a.length() + 1 == b.length()){ - return one_edit_insert(a, b); - } - else if(a.length() - 1 == b.length()){ - return one_edit_insert(b, a); - } - return false; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -int main(){ - is_one_edit_away("Pale", "Ple") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pales", "Pale") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bale") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bae") == true ? print_ans(true) : print_ans(false); - return 0; -} +// Given two strings write a function to check if they are one edit(or zero edits) away +// Program Author : Abhisek Kumar Gupta + +// Sample Input : Pale Ple +// Output : Yes Pale +// Sample Input : Pale bae +// Output : No +#include +using namespace std; +bool one_edit_replace(string a, string b){ + bool found_difference = false; + for(int i = 0; i < a.length(); i++){ + if(a[i] != b[i]){ + if(found_difference){ + return false; + } + found_difference = true; + } + } + return true; +} +bool one_edit_insert(string a, string b){ + int i1 = 0, i2 = 0; + while(i1 < a.length() && i2 < b.length()){ + if(a[i1] != b[i2]){ + if(i1 != i2){ + return false; + } + i2++; + } + else{ + i1++; + i2++; + } + } + return true; +} +bool is_one_edit_away(string a, string b){ + if(a.length() == b.length()){ + return one_edit_replace(a, b); + } + else if(a.length() + 1 == b.length()){ + return one_edit_insert(a, b); + } + else if(a.length() - 1 == b.length()){ + return one_edit_insert(b, a); + } + return false; +} +void print_ans(bool ans){ + if(ans){ + cout << "YES\n"; + } + else{ + cout << "NO\n"; + } +} +int main(){ + is_one_edit_away("Pale", "Ple") == true ? print_ans(true) : print_ans(false); + is_one_edit_away("Pales", "Pale") == true ? print_ans(true) : print_ans(false); + is_one_edit_away("Pale", "bale") == true ? print_ans(true) : print_ans(false); + is_one_edit_away("Pale", "bae") == true ? print_ans(true) : print_ans(false); + return 0; +} diff --git a/CCTI/arrays_strings_pallindromic_permutations.cpp b/Arrays/arrays_strings_pallindromic_permutations.cpp similarity index 97% rename from CCTI/arrays_strings_pallindromic_permutations.cpp rename to Arrays/arrays_strings_pallindromic_permutations.cpp index cfa3048a..64173ebc 100644 --- a/CCTI/arrays_strings_pallindromic_permutations.cpp +++ b/Arrays/arrays_strings_pallindromic_permutations.cpp @@ -1,62 +1,62 @@ -// Write a function to check if it is a permutation of a pallindrome -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -// TC O(n) n is length of string -bool is_permutation_pallindrome(string s){ - // we built a hash table to count how many times each character appears - // we then iterate through hashtable to find out no more than one character has - // odd count - vector table(26, 0); - bool found_odd = false; - for(int i = 0; i < s.length(); i++){ - table[s[i]-'a']++; - } - for(int x : table){ - if(x&1){ - if(found_odd){ - return false; - } - found_odd = true; - } - } - return true; -} -bool is_permutation_pallindrome_improved(string s){ - // instead of checking oddcounts at end we can check - // as we traverse the chars in string, as soon as we reach end - // we have out answer. - vector table(26, 0); - int count_odd = 0; - for(int i = 0; i < s.length(); i++){ - int x = s[i]-'a'; - table[x]++; - if(table[x] & 1){ - count_odd++; - } - else{ - count_odd--; - } - } - return count_odd <= 1; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -int main(){ - is_permutation_pallindrome("aaabdddcba") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("abab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("abcddeab") == true ? print_ans(true) : print_ans(false); - cout << "**********IMPROVED*********\n"; - is_permutation_pallindrome_improved("a") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("ab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("abcddeab") == true ? print_ans(true) : print_ans(false); - return 0; +// Write a function to check if it is a permutation of a pallindrome +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +// TC O(n) n is length of string +bool is_permutation_pallindrome(string s){ + // we built a hash table to count how many times each character appears + // we then iterate through hashtable to find out no more than one character has + // odd count + vector table(26, 0); + bool found_odd = false; + for(int i = 0; i < s.length(); i++){ + table[s[i]-'a']++; + } + for(int x : table){ + if(x&1){ + if(found_odd){ + return false; + } + found_odd = true; + } + } + return true; +} +bool is_permutation_pallindrome_improved(string s){ + // instead of checking oddcounts at end we can check + // as we traverse the chars in string, as soon as we reach end + // we have out answer. + vector table(26, 0); + int count_odd = 0; + for(int i = 0; i < s.length(); i++){ + int x = s[i]-'a'; + table[x]++; + if(table[x] & 1){ + count_odd++; + } + else{ + count_odd--; + } + } + return count_odd <= 1; +} +void print_ans(bool ans){ + if(ans){ + cout << "YES\n"; + } + else{ + cout << "NO\n"; + } +} +int main(){ + is_permutation_pallindrome("aaabdddcba") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("abab") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("abcddeab") == true ? print_ans(true) : print_ans(false); + cout << "**********IMPROVED*********\n"; + is_permutation_pallindrome_improved("a") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("ab") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("ABA") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("abcddeab") == true ? print_ans(true) : print_ans(false); + return 0; } \ No newline at end of file diff --git a/CCTI/arrays_strings_pallindromic_permutations_effecient.cpp b/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp similarity index 96% rename from CCTI/arrays_strings_pallindromic_permutations_effecient.cpp rename to Arrays/arrays_strings_pallindromic_permutations_effecient.cpp index 166d7b81..61fe4836 100644 --- a/CCTI/arrays_strings_pallindromic_permutations_effecient.cpp +++ b/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp @@ -1,59 +1,59 @@ -// Write a function to check if it is a permutation of a pallindrome using bitvector -// Program Author : Abhisek Kumar Gupta -// Sample Input : aabcb -// Output : Yes -// Sample Input : ab -// Output : No -#include -using namespace std; -bool check_exactly_for_one_set_bit(int bit_vector){ - return (bit_vector & (bit_vector - 1)) == 0; -} -int toggle(int bit_vector, int x){ - if(x < 0) return bit_vector; - int mask = 1 << x; - if((bit_vector & mask) == 0){ - bit_vector |= mask; - } - else{ - bit_vector &= ~mask; - } - return bit_vector; -} - -int create_bit_vector(string a){ - int bit_vector = 0, mask = 0; - for(int i = 0; i < a.length(); i++){ - int x = a[i] - 'a'; - bit_vector = toggle(bit_vector, x); - /* - mask = 1 << x; - if((bit_vector & mask) == 0){ - bit_vector |= mask; - } - else{ - bit_vector &= ~mask; - } - */ - } - return bit_vector; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -bool is_permutation_pallindrome(string a){ - int bit_vector = create_bit_vector(a); - return bit_vector == 0 || check_exactly_for_one_set_bit(bit_vector); -} -int main(){ - is_permutation_pallindrome("aabcb") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("racecarf") == true ? print_ans(true) : print_ans(false); - return 0; +// Write a function to check if it is a permutation of a pallindrome using bitvector +// Program Author : Abhisek Kumar Gupta +// Sample Input : aabcb +// Output : Yes +// Sample Input : ab +// Output : No +#include +using namespace std; +bool check_exactly_for_one_set_bit(int bit_vector){ + return (bit_vector & (bit_vector - 1)) == 0; +} +int toggle(int bit_vector, int x){ + if(x < 0) return bit_vector; + int mask = 1 << x; + if((bit_vector & mask) == 0){ + bit_vector |= mask; + } + else{ + bit_vector &= ~mask; + } + return bit_vector; +} + +int create_bit_vector(string a){ + int bit_vector = 0, mask = 0; + for(int i = 0; i < a.length(); i++){ + int x = a[i] - 'a'; + bit_vector = toggle(bit_vector, x); + /* + mask = 1 << x; + if((bit_vector & mask) == 0){ + bit_vector |= mask; + } + else{ + bit_vector &= ~mask; + } + */ + } + return bit_vector; +} +void print_ans(bool ans){ + if(ans){ + cout << "YES\n"; + } + else{ + cout << "NO\n"; + } +} +bool is_permutation_pallindrome(string a){ + int bit_vector = create_bit_vector(a); + return bit_vector == 0 || check_exactly_for_one_set_bit(bit_vector); +} +int main(){ + is_permutation_pallindrome("aabcb") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ab") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("racecarf") == true ? print_ans(true) : print_ans(false); + return 0; } \ No newline at end of file diff --git a/CCTI/arrays_strings_urlify.cpp b/Arrays/arrays_strings_urlify.cpp similarity index 96% rename from CCTI/arrays_strings_urlify.cpp rename to Arrays/arrays_strings_urlify.cpp index 80403421..c2a66bbe 100644 --- a/CCTI/arrays_strings_urlify.cpp +++ b/Arrays/arrays_strings_urlify.cpp @@ -1,38 +1,38 @@ -// Implement an algorithm to replace all spaces with %20. -// Sample Input : Mr Ashish Lala -// Output: Mr%20Ashish%20Lala -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -void urlify(string s, int length){ - int space_count = 0; - for(int i = 0; i < length; i++){ - if(s[i] == ' '){ - space_count++; - } - } - int index = length + (space_count * 3); - int new_length = index; - for(int i = length - 1; i >= 0; i--){ - if(s[i] == ' '){ - s[index - 1] = '0'; - s[index - 2] = '2'; - s[index - 3] = '%'; - index = index - 3; - } - else{ - s[index - 1] = s[i]; - index--; - } - } - for(int i = index; i < new_length; i++){ - cout << s[i]; - } - -} -int main(){ - string s = "Mr John Smith "; - int length = 13; - urlify(s, 13); - return 0; +// Implement an algorithm to replace all spaces with %20. +// Sample Input : Mr Ashish Lala +// Output: Mr%20Ashish%20Lala +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; +void urlify(string s, int length){ + int space_count = 0; + for(int i = 0; i < length; i++){ + if(s[i] == ' '){ + space_count++; + } + } + int index = length + (space_count * 3); + int new_length = index; + for(int i = length - 1; i >= 0; i--){ + if(s[i] == ' '){ + s[index - 1] = '0'; + s[index - 2] = '2'; + s[index - 3] = '%'; + index = index - 3; + } + else{ + s[index - 1] = s[i]; + index--; + } + } + for(int i = index; i < new_length; i++){ + cout << s[i]; + } + +} +int main(){ + string s = "Mr John Smith "; + int length = 13; + urlify(s, 13); + return 0; } \ No newline at end of file diff --git a/CCTI/urlify.go b/Arrays/urlify.go similarity index 100% rename from CCTI/urlify.go rename to Arrays/urlify.go From 77a3f2ce51842108211c516ae282de6f3080458a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:49:17 +0530 Subject: [PATCH 0345/1894] add optional name Matrix --- {2D Arrays => 2D Arrays (Matrix)}/2d_binary_search.cpp | 0 .../count_negatives_in_sorted_matrix.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/matrix_diagonal_sum.cpp | 0 .../matrix_rotate_90_anti_clockwise.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/matrix_rotate_90_clockwise.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/matrix_search_in_sorted_mat.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/matrix_spiral_print.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/matrix_wave_print.cpp | 0 {2D Arrays => 2D Arrays (Matrix)}/search_element.cpp | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename {2D Arrays => 2D Arrays (Matrix)}/2d_binary_search.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/count_negatives_in_sorted_matrix.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_diagonal_sum.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_rotate_90_anti_clockwise.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_rotate_90_clockwise.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_search_in_sorted_mat.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_spiral_print.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/matrix_wave_print.cpp (100%) rename {2D Arrays => 2D Arrays (Matrix)}/search_element.cpp (100%) diff --git a/2D Arrays/2d_binary_search.cpp b/2D Arrays (Matrix)/2d_binary_search.cpp similarity index 100% rename from 2D Arrays/2d_binary_search.cpp rename to 2D Arrays (Matrix)/2d_binary_search.cpp diff --git a/2D Arrays/count_negatives_in_sorted_matrix.cpp b/2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp similarity index 100% rename from 2D Arrays/count_negatives_in_sorted_matrix.cpp rename to 2D Arrays (Matrix)/count_negatives_in_sorted_matrix.cpp diff --git a/2D Arrays/matrix_diagonal_sum.cpp b/2D Arrays (Matrix)/matrix_diagonal_sum.cpp similarity index 100% rename from 2D Arrays/matrix_diagonal_sum.cpp rename to 2D Arrays (Matrix)/matrix_diagonal_sum.cpp diff --git a/2D Arrays/matrix_rotate_90_anti_clockwise.cpp b/2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp similarity index 100% rename from 2D Arrays/matrix_rotate_90_anti_clockwise.cpp rename to 2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp diff --git a/2D Arrays/matrix_rotate_90_clockwise.cpp b/2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp similarity index 100% rename from 2D Arrays/matrix_rotate_90_clockwise.cpp rename to 2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp diff --git a/2D Arrays/matrix_search_in_sorted_mat.cpp b/2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp similarity index 100% rename from 2D Arrays/matrix_search_in_sorted_mat.cpp rename to 2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp diff --git a/2D Arrays/matrix_spiral_print.cpp b/2D Arrays (Matrix)/matrix_spiral_print.cpp similarity index 100% rename from 2D Arrays/matrix_spiral_print.cpp rename to 2D Arrays (Matrix)/matrix_spiral_print.cpp diff --git a/2D Arrays/matrix_wave_print.cpp b/2D Arrays (Matrix)/matrix_wave_print.cpp similarity index 100% rename from 2D Arrays/matrix_wave_print.cpp rename to 2D Arrays (Matrix)/matrix_wave_print.cpp diff --git a/2D Arrays/search_element.cpp b/2D Arrays (Matrix)/search_element.cpp similarity index 100% rename from 2D Arrays/search_element.cpp rename to 2D Arrays (Matrix)/search_element.cpp From 9acb1909e86ef2d40ff108b1c05b9659bebcc491 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:51:05 +0530 Subject: [PATCH 0346/1894] rename file --- ...arch_sorted_2d_matrix.py => binary_search_sorted_2d_matrix.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary Search/{BinarySearch_sorted_2d_matrix.py => binary_search_sorted_2d_matrix.py} (100%) diff --git a/Binary Search/BinarySearch_sorted_2d_matrix.py b/Binary Search/binary_search_sorted_2d_matrix.py similarity index 100% rename from Binary Search/BinarySearch_sorted_2d_matrix.py rename to Binary Search/binary_search_sorted_2d_matrix.py From 25d70591854903e9f33a23550e4e73ceb77defc6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:55:40 +0530 Subject: [PATCH 0347/1894] rem9ove redundant check --- Arrays/arrays_strings_is_unique.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Arrays/arrays_strings_is_unique.cpp b/Arrays/arrays_strings_is_unique.cpp index de7376ea..6292a3b3 100644 --- a/Arrays/arrays_strings_is_unique.cpp +++ b/Arrays/arrays_strings_is_unique.cpp @@ -48,12 +48,12 @@ int main(){ string s = "ABCDD"; string t = "ABCD"; string u = "AAAAAABCD"; - is_unique_normal(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique_normal(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique_normal(u) == true ? print_ans(true, u) : print_ans(false, u); + is_unique_normal(s) ? print_ans(true, s) : print_ans(false, s); + is_unique_normal(t) ? print_ans(true, t) : print_ans(false, t); + is_unique_normal(u) ? print_ans(true, u) : print_ans(false, u); cout << "\n***********************\n"; - is_unique(s) == true ? print_ans(true, s) : print_ans(false, s); - is_unique(t) == true ? print_ans(true, t) : print_ans(false, t); - is_unique(u) == true ? print_ans(true, u) : print_ans(false, u); + is_unique(s) ? print_ans(true, s) : print_ans(false, s); + is_unique(t) ? print_ans(true, t) : print_ans(false, t); + is_unique(u) ? print_ans(true, u) : print_ans(false, u); return 0; } \ No newline at end of file From 66c4d41163cee081f3e03d079434ace2fccf69d0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:56:18 +0530 Subject: [PATCH 0348/1894] remove redundant check --- Arrays/arrays_strings_one_away.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Arrays/arrays_strings_one_away.cpp b/Arrays/arrays_strings_one_away.cpp index c7332b3a..4715abd4 100644 --- a/Arrays/arrays_strings_one_away.cpp +++ b/Arrays/arrays_strings_one_away.cpp @@ -56,9 +56,9 @@ void print_ans(bool ans){ } } int main(){ - is_one_edit_away("Pale", "Ple") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pales", "Pale") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bale") == true ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bae") == true ? print_ans(true) : print_ans(false); + is_one_edit_away("Pale", "Ple") ? print_ans(true) : print_ans(false); + is_one_edit_away("Pales", "Pale") ? print_ans(true) : print_ans(false); + is_one_edit_away("Pale", "bale") ? print_ans(true) : print_ans(false); + is_one_edit_away("Pale", "bae") ? print_ans(true) : print_ans(false); return 0; } From c100153442eca4c5a26337a6c292aa5bdd221a7f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:56:44 +0530 Subject: [PATCH 0349/1894] remove redundant check --- ...arrays_strings_pallindromic_permutations_effecient.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp b/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp index 61fe4836..94427b1e 100644 --- a/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp +++ b/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp @@ -51,9 +51,9 @@ bool is_permutation_pallindrome(string a){ return bit_vector == 0 || check_exactly_for_one_set_bit(bit_vector); } int main(){ - is_permutation_pallindrome("aabcb") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("racecarf") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("aabcb") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ab") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ABA") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("racecarf") ? print_ans(true) : print_ans(false); return 0; } \ No newline at end of file From 639e049206b1b217b8849129acb3ddb34247456e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:58:23 +0530 Subject: [PATCH 0350/1894] remove redundant check --- .../arrays_strings_pallindromic_permutations.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Arrays/arrays_strings_pallindromic_permutations.cpp b/Arrays/arrays_strings_pallindromic_permutations.cpp index 64173ebc..d3c9bb0f 100644 --- a/Arrays/arrays_strings_pallindromic_permutations.cpp +++ b/Arrays/arrays_strings_pallindromic_permutations.cpp @@ -49,14 +49,14 @@ void print_ans(bool ans){ } } int main(){ - is_permutation_pallindrome("aaabdddcba") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("abab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("abcddeab") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("aaabdddcba") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("abab") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("ABA") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome("abcddeab") ? print_ans(true) : print_ans(false); cout << "**********IMPROVED*********\n"; - is_permutation_pallindrome_improved("a") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("ab") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("ABA") == true ? print_ans(true) : print_ans(false); - is_permutation_pallindrome_improved("abcddeab") == true ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("a") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("ab") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("ABA") ? print_ans(true) : print_ans(false); + is_permutation_pallindrome_improved("abcddeab") ? print_ans(true) : print_ans(false); return 0; } \ No newline at end of file From 2843cc59a88d90f08e4e3f3a4efb9833792b58a7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Mar 2023 22:59:52 +0530 Subject: [PATCH 0351/1894] remove redundant check --- Arrays/arrays_strings_check_permutations.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Arrays/arrays_strings_check_permutations.cpp b/Arrays/arrays_strings_check_permutations.cpp index 52b27a3d..257966bc 100644 --- a/Arrays/arrays_strings_check_permutations.cpp +++ b/Arrays/arrays_strings_check_permutations.cpp @@ -38,9 +38,9 @@ void print_ans(bool ans){ } } int main(){ - check_permutation("ABDE", "DEBA") == true ? print_ans(true) : print_ans(false); - check_permutation("ABCD", "DEFG") == true ? print_ans(true) : print_ans(false); - check_permutation_fast("AA", "DEBA") == true ? print_ans(true) : print_ans(false); - check_permutation_fast("ADEB", "ABED") == true ? print_ans(true) : print_ans(false); + check_permutation("ABDE", "DEBA") ? print_ans(true) : print_ans(false); + check_permutation("ABCD", "DEFG") ? print_ans(true) : print_ans(false); + check_permutation_fast("AA", "DEBA") ? print_ans(true) : print_ans(false); + check_permutation_fast("ADEB", "ABED") ? print_ans(true) : print_ans(false); return 0; } \ No newline at end of file From cc1016ce383b59ca289b8a457c1639a080f9d876 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Wed, 1 Mar 2023 21:37:37 -0500 Subject: [PATCH 0352/1894] Implemented #461 #480 #503 --- .../binary_serach_First_Last_occurence.py | 40 +++++++++++++++++++ Math/Hamming_distance.py | 13 ++++++ Math/unique_digits.py | 16 ++++++++ 3 files changed, 69 insertions(+) create mode 100644 Binary Search/binary_serach_First_Last_occurence.py create mode 100644 Math/Hamming_distance.py create mode 100644 Math/unique_digits.py diff --git a/Binary Search/binary_serach_First_Last_occurence.py b/Binary Search/binary_serach_First_Last_occurence.py new file mode 100644 index 00000000..be1a79d6 --- /dev/null +++ b/Binary Search/binary_serach_First_Last_occurence.py @@ -0,0 +1,40 @@ +class Solution: + def __init__(self): + self.start_index=-1 + self.end_index=-1 + + ''' Time complexity - O(logn), Space complexity - O(1)'''' + '''Once the binary Search is implemented, to find the start_index, we store the current index where we find the target and implement search again on the left side of the array''' + def binarySearchFirst(self,arr,low,high,target): + if(low>high): + return + mid=(low+high)//2 + if(arr[mid]>target): + Solution.binarySearchFirst(self,arr,low,mid-1,target) + elif(arr[mid]high): + return + mid=(low+high)//2 + if(arr[mid]>target): + Solution.binarySearchLast(self,arr,low,mid-1,target) + elif(arr[mid] List[int]: + + #implementing binarySearchLast to populate the self.end_index + Solution.binarySearchLast(self,nums,0,len(nums)-1,target) + + #implementing binarySearchFirst to populate the self.start_index + Solution.binarySearchFirst(self,nums,0,len(nums)-1,target) + return [self.start_index, self.end_index] \ No newline at end of file diff --git a/Math/Hamming_distance.py b/Math/Hamming_distance.py new file mode 100644 index 00000000..6817192f --- /dev/null +++ b/Math/Hamming_distance.py @@ -0,0 +1,13 @@ +class Solution: + def totalHammingDistance(self, nums: List[int]) -> int: + '''By using bit manipulation, as all the array elements are 32-bit array elements, we calculate all the number of set bits and unset bits as we need to consider the permutations, we take setbits*unsetbits.''' + hamming_dist,n = 0,len(nums) + for i in range(32): + count = 0 + for element in nums: + #Right shifting the element by the index and performing &1 lets us know if a bit is set or not + if((element>>i)&1): + count+=1 + #Adding all the combinations where there are set and unset bits. + hamming_dist+=count*(n-count) + return hamming_dist \ No newline at end of file diff --git a/Math/unique_digits.py b/Math/unique_digits.py new file mode 100644 index 00000000..956632b0 --- /dev/null +++ b/Math/unique_digits.py @@ -0,0 +1,16 @@ +class Solution: + def countNumbersWithUniqueDigits(self, n: int) -> int: + '''For n = 0, ans = 1 + For n = 1, ans = 10 + If we take 2 digit number, we have 9 options for first digit (1 - 9) + and 9 options for second digit(0 & all other digits except the one taken as first digit (to keep digits unique)) therefore ans += (9 * 9) + Similarly if we take 3 digit number we have 8 options for third digit, therefore ans += (9 * 9 * 8)''' + if(n==0): return 1 + if(n==1): return 10 + unique = 10 + digits = 9 + for i in range(2,n+1): + digits*=(10-i+1) + unique+=digits + return unique + \ No newline at end of file From 927687573d82316a1a4e324efb718449d7a175d9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:42:52 +0530 Subject: [PATCH 0353/1894] move into recursion --- {Random Problems => Recursion}/bubble_sort_recursive.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Recursion}/bubble_sort_recursive.cpp (100%) diff --git a/Random Problems/bubble_sort_recursive.cpp b/Recursion/bubble_sort_recursive.cpp similarity index 100% rename from Random Problems/bubble_sort_recursive.cpp rename to Recursion/bubble_sort_recursive.cpp From 9fe6bf475849d115344ad9dfd1ccf3f45581473d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:43:01 +0530 Subject: [PATCH 0354/1894] move into searching directory --- {Random Problems => Searching}/linear_search_string.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Searching}/linear_search_string.cpp (100%) diff --git a/Random Problems/linear_search_string.cpp b/Searching/linear_search_string.cpp similarity index 100% rename from Random Problems/linear_search_string.cpp rename to Searching/linear_search_string.cpp From 8c764db90b46088fbf790063de884f7579b09858 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:43:35 +0530 Subject: [PATCH 0355/1894] remove duplicate --- Random Problems/set_bits.cpp | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 Random Problems/set_bits.cpp diff --git a/Random Problems/set_bits.cpp b/Random Problems/set_bits.cpp deleted file mode 100644 index 079fe25d..00000000 --- a/Random Problems/set_bits.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// Count the number of bits that are set in an integer -#include -using namespace std; -short check_set_bits(unsigned int x){ - short num_bits = 0; - while(x){ - num_bits += x & 1; - x >>= 1; - } - return num_bits; -} -int main(){ - cout << check_set_bits(1) << endl; - cout << check_set_bits(7) << endl; - cout << check_set_bits(15) << endl; - return 0; -} \ No newline at end of file From 9f8fc9d180c12adb367f5ad6fbac01f4c232b92b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:44:11 +0530 Subject: [PATCH 0356/1894] move into strings directory --- {Random Problems => Strings}/check_permutations.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Strings}/check_permutations.cpp (100%) diff --git a/Random Problems/check_permutations.cpp b/Strings/check_permutations.cpp similarity index 100% rename from Random Problems/check_permutations.cpp rename to Strings/check_permutations.cpp From 4a1cc755a7b8884ce48f5cebdd7519a3ace612d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:44:31 +0530 Subject: [PATCH 0357/1894] move into arrays directory --- {Random Problems => Arrays}/maximum_subarray.cpp | 0 {Random Problems => Arrays}/maximum_subarray_cumulative.cpp | 0 {Random Problems => Arrays}/maximum_subarray_kadanes.cpp | 0 {Random Problems => Arrays}/move_zeros.cpp | 0 {Random Problems => Arrays}/printing_all_subarrays.cpp | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Arrays}/maximum_subarray.cpp (100%) rename {Random Problems => Arrays}/maximum_subarray_cumulative.cpp (100%) rename {Random Problems => Arrays}/maximum_subarray_kadanes.cpp (100%) rename {Random Problems => Arrays}/move_zeros.cpp (100%) rename {Random Problems => Arrays}/printing_all_subarrays.cpp (100%) diff --git a/Random Problems/maximum_subarray.cpp b/Arrays/maximum_subarray.cpp similarity index 100% rename from Random Problems/maximum_subarray.cpp rename to Arrays/maximum_subarray.cpp diff --git a/Random Problems/maximum_subarray_cumulative.cpp b/Arrays/maximum_subarray_cumulative.cpp similarity index 100% rename from Random Problems/maximum_subarray_cumulative.cpp rename to Arrays/maximum_subarray_cumulative.cpp diff --git a/Random Problems/maximum_subarray_kadanes.cpp b/Arrays/maximum_subarray_kadanes.cpp similarity index 100% rename from Random Problems/maximum_subarray_kadanes.cpp rename to Arrays/maximum_subarray_kadanes.cpp diff --git a/Random Problems/move_zeros.cpp b/Arrays/move_zeros.cpp similarity index 100% rename from Random Problems/move_zeros.cpp rename to Arrays/move_zeros.cpp diff --git a/Random Problems/printing_all_subarrays.cpp b/Arrays/printing_all_subarrays.cpp similarity index 100% rename from Random Problems/printing_all_subarrays.cpp rename to Arrays/printing_all_subarrays.cpp From 852ced33d08ec7c7ff7a0ef92a03df47b943b992 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:45:22 +0530 Subject: [PATCH 0358/1894] remove duplicate --- Random Problems/spiral_print.cpp | 45 -------------------------------- 1 file changed, 45 deletions(-) delete mode 100644 Random Problems/spiral_print.cpp diff --git a/Random Problems/spiral_print.cpp b/Random Problems/spiral_print.cpp deleted file mode 100644 index beaf49ff..00000000 --- a/Random Problems/spiral_print.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include -using namespace std; -int main(){ - int mat[100][100]; - int row, col; - cin >> row >> col; - for(int i = 0; i < row; i++){ - for(int j = 0; j < col; j++){ - cin >> mat[i][j]; - } - } - // spiral print - int start_row = 0; - int start_col = 0; - int end_row = row - 1; - int end_col = col - 1; - while(start_row <= end_row && start_col <= end_col){ - // print first row - for(int i = start_col; i <= end_col; i++){ - cout << mat[start_row][i] << " "; - } - start_row++; - // print last col - for(int i = start_row; i <= end_row; i++){ - cout << mat[i][end_col] << " "; - } - end_col--; - // last row - if(end_row > start_row){ - for(int i = end_col; i >= start_col; i--){ - cout << mat[end_row][i] << " "; - } - end_row--; - } - // start column - if(end_col > start_col){ - for(int i = end_row; i >= start_row; i--){ - cout << mat[i][start_col] << " "; - } - start_col++; - } - } - return 0; -} - \ No newline at end of file From 4a3bbc45dca9798249767cbab9030dc172cb600e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:45:52 +0530 Subject: [PATCH 0359/1894] move into arrays directory --- {Random Problems => Arrays}/unique_occurences.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Arrays}/unique_occurences.cpp (100%) diff --git a/Random Problems/unique_occurences.cpp b/Arrays/unique_occurences.cpp similarity index 100% rename from Random Problems/unique_occurences.cpp rename to Arrays/unique_occurences.cpp From 8bf4aeab520d7b424bc23b0f3ffd5b28c36450d9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:46:12 +0530 Subject: [PATCH 0360/1894] move into strings directory --- {Random Problems => Strings}/rev_string.go | 0 {Random Problems => Strings}/rotate_string.cpp | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Random Problems => Strings}/rev_string.go (100%) rename {Random Problems => Strings}/rotate_string.cpp (100%) diff --git a/Random Problems/rev_string.go b/Strings/rev_string.go similarity index 100% rename from Random Problems/rev_string.go rename to Strings/rev_string.go diff --git a/Random Problems/rotate_string.cpp b/Strings/rotate_string.cpp similarity index 100% rename from Random Problems/rotate_string.cpp rename to Strings/rotate_string.cpp From cdb282d24d343d32029f7fac429a4754b269b316 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 22:58:17 +0530 Subject: [PATCH 0361/1894] add tower of hanoi in go --- Recursion/tower_of_hanoi.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Recursion/tower_of_hanoi.go diff --git a/Recursion/tower_of_hanoi.go b/Recursion/tower_of_hanoi.go new file mode 100644 index 00000000..2f6ebe98 --- /dev/null +++ b/Recursion/tower_of_hanoi.go @@ -0,0 +1,27 @@ +package main + +import "fmt" +func TowerOfHanoiHelper(n int, from, to, temp string) { + // Base case + // If only 1 disk, make the move and return + if n == 1 { + fmt.Println("Move disk ", n, " from peg ", from, " to peg ", to) + return + } + + // Move top n-1 disks from A to B, using C as auxiliary + TowerOfHanoiHelper(n-1, from, temp, to) + + // Move remaining disks from A to C + fmt.Println("Move disk ", n, " from peg ", from, " to peg ", to) + + // Move n-1 disks from B to C using A as auxiliary + TowerOfHanoiHelper(n-1, temp, to, from) +} + +func TowersOfHanoi(n int) { + TowerOfHanoiHelper(n, "A", "C", "B") +} +func main() { + TowersOfHanoi(3) +} \ No newline at end of file From 292ddeafd5b5c002b2dcf060733ed5ad83d7119d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 23:00:32 +0530 Subject: [PATCH 0362/1894] add description --- Recursion/tower_of_hanoi.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Recursion/tower_of_hanoi.go b/Recursion/tower_of_hanoi.go index 2f6ebe98..80f34e0b 100644 --- a/Recursion/tower_of_hanoi.go +++ b/Recursion/tower_of_hanoi.go @@ -1,3 +1,10 @@ +/* + Towers of Hanoi puzzle. + Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) + Object of the game is to move all the disks over to Tower 3. + But you cannot place a larger disk onto a smaller disk. +*/ + package main import "fmt" From 23ff7d1098cb405e3596c743df534b67b0723abd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 23:01:20 +0530 Subject: [PATCH 0363/1894] add approach --- Recursion/tower_of_hanoi.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Recursion/tower_of_hanoi.go b/Recursion/tower_of_hanoi.go index 80f34e0b..ac49e9f7 100644 --- a/Recursion/tower_of_hanoi.go +++ b/Recursion/tower_of_hanoi.go @@ -4,7 +4,12 @@ Object of the game is to move all the disks over to Tower 3. But you cannot place a larger disk onto a smaller disk. */ - +/* +Approach + 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, + 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, + 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. +*/ package main import "fmt" From ab275b23ce2e3c337b5322d47093a6294c05a298 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 23:03:58 +0530 Subject: [PATCH 0364/1894] add question --- Recursion/is_array_sorted.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Recursion/is_array_sorted.go b/Recursion/is_array_sorted.go index fc3353f8..d8f38da5 100644 --- a/Recursion/is_array_sorted.go +++ b/Recursion/is_array_sorted.go @@ -1,3 +1,6 @@ +/* + Given an array, check whether the array is in sorted order with recursion. +*/ package main import "fmt" From f879a7c76930382f116ab5512ec186c9ed899374 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 23:04:34 +0530 Subject: [PATCH 0365/1894] add time and space complexity --- Recursion/is_array_sorted.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Recursion/is_array_sorted.go b/Recursion/is_array_sorted.go index d8f38da5..6dc1a66f 100644 --- a/Recursion/is_array_sorted.go +++ b/Recursion/is_array_sorted.go @@ -1,6 +1,8 @@ /* Given an array, check whether the array is in sorted order with recursion. */ +// Time Complexity: O(n). Space Complexity: O(n) for recursive stack space. + package main import "fmt" From 8fa78936e06b3a2d98bddd6b599749b8b6bdc5cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Mar 2023 23:05:16 +0530 Subject: [PATCH 0366/1894] add comments --- Recursion/is_array_sorted.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Recursion/is_array_sorted.go b/Recursion/is_array_sorted.go index 6dc1a66f..70023259 100644 --- a/Recursion/is_array_sorted.go +++ b/Recursion/is_array_sorted.go @@ -10,12 +10,15 @@ import "fmt" // Time Complexity: O(n). Space Complexity: O(n) for recursive stack space. func isSorted(A []int) bool { n := len(A) + // Base case 1 if n == 1 { return true } + // Base case 2 if A[n - 1] < A[n - 2] { return false } + // recursive case return isSorted(A[:n-1]) } From b8f8c06badf22644fb1dc5fe655964e78f47c21f Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Fri, 3 Mar 2023 18:48:00 -0500 Subject: [PATCH 0367/1894] Issues #435 #813 #627 #430 --- Arrays/squares_sorted_array.py | 16 ++++++++++++++ Backtracking/Generate_Parentheses.py | 17 +++++++++++++++ Binary Search/Search_sorted_rotated_array.py | 22 ++++++++++++++++++++ Recursion/tower_of_hannoi.py | 8 +++++++ 4 files changed, 63 insertions(+) create mode 100644 Arrays/squares_sorted_array.py create mode 100644 Backtracking/Generate_Parentheses.py create mode 100644 Binary Search/Search_sorted_rotated_array.py create mode 100644 Recursion/tower_of_hannoi.py diff --git a/Arrays/squares_sorted_array.py b/Arrays/squares_sorted_array.py new file mode 100644 index 00000000..db108358 --- /dev/null +++ b/Arrays/squares_sorted_array.py @@ -0,0 +1,16 @@ +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + #Considering two pointer approach + i,j=0,len(nums)-1 + final_array=[] + while(i<=j): + #comparing absolute values of the starting and the ending elements + #if the second-pointer element is greateer, we add it to the list. If not, we add the first-pointer element + if(abs(nums[i]) List[str]: + final_arr = [] + Solution.generate(self,n,0,0,"",final_arr) + return final_arr \ No newline at end of file diff --git a/Binary Search/Search_sorted_rotated_array.py b/Binary Search/Search_sorted_rotated_array.py new file mode 100644 index 00000000..d469485b --- /dev/null +++ b/Binary Search/Search_sorted_rotated_array.py @@ -0,0 +1,22 @@ +class Solution: + def binarySearch(nums,low,high,target): + if(low>high): + return -1 + mid = (low+high)//2 + if(nums[mid]target): + return Solution.binarySearch(nums,low,mid-1,target) + else: + return mid + + def search(self, nums: List[int], target: int) -> int: + #Finding the index where the array was rotated and binary searching the first and second parts for the target value. + rotated_index = -1 + for i in range(len(nums)-1): + if(nums[i]>nums[i+1]): + rotated_index = i + break + + return Solution.binarySearch(nums,0,rotated_index,target) & Solution.binarySearch(nums,rotated_index+1,len(nums)-1,target) + \ No newline at end of file diff --git a/Recursion/tower_of_hannoi.py b/Recursion/tower_of_hannoi.py new file mode 100644 index 00000000..fbe62ace --- /dev/null +++ b/Recursion/tower_of_hannoi.py @@ -0,0 +1,8 @@ + +#Tower of Hanoi explanation - https://youtu.be/YstLjLCGmgg +def TowerOfHanoi(n, A,B,C): + if n == 0: + return + TowerOfHanoi(n-1, A,C,B) + print("Move disk", n, "from", A, "to rod", B) + TowerOfHanoi(n-1, C, B, A) \ No newline at end of file From dd716414fbf25b75705e94a4a6a2237ce3a8d8cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:51:35 +0530 Subject: [PATCH 0368/1894] rename file --- Arrays/{squares_sorted_array.py => sorted_square_array.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{squares_sorted_array.py => sorted_square_array.py} (100%) diff --git a/Arrays/squares_sorted_array.py b/Arrays/sorted_square_array.py similarity index 100% rename from Arrays/squares_sorted_array.py rename to Arrays/sorted_square_array.py From cf08a04c653ef0a9fcb8bd57d1c69a404a1681ec Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:52:02 +0530 Subject: [PATCH 0369/1894] add description --- Arrays/sorted_square_array.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Arrays/sorted_square_array.py b/Arrays/sorted_square_array.py index db108358..a2628041 100644 --- a/Arrays/sorted_square_array.py +++ b/Arrays/sorted_square_array.py @@ -1,3 +1,11 @@ +''' + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. + + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] +''' class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: #Considering two pointer approach From 9c9a76ed8253ded971acad1a60f417d50a89fa4b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:53:50 +0530 Subject: [PATCH 0370/1894] add description --- Backtracking/Generate_Parentheses.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Backtracking/Generate_Parentheses.py b/Backtracking/Generate_Parentheses.py index 23e8d336..e2b62a46 100644 --- a/Backtracking/Generate_Parentheses.py +++ b/Backtracking/Generate_Parentheses.py @@ -1,3 +1,15 @@ +''' + Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + Example 1: + Input: n = 3 + Output: ["((()))","(()())","(())()","()(())","()()()"] + + Example 2: + Input: n = 1 + Output: ["()"] + Constraints: + 1 <= n <= 8 +''' class Solution: #reference: GeeksforGeeks for comments '''To form all the sequences of balanced bracket subsequences with n pairs. So there are n opening brackets and n closing brackets. So the subsequence will be of length 2*n. There is a simple idea, the i’th character can be ‘{‘ if and only if the count of ‘{‘ till i’th is less than n and i’th character can be ‘}’ if and only if the count of ‘{‘ is greater than the count of ‘}’ till index i. If these two cases are followed then the resulting subsequence will always be balanced''' From 6788d9cf6fb3d3ce29c022cac6b82e9ed5f694cf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:55:53 +0530 Subject: [PATCH 0371/1894] rename files and add description --- Binary Search/Search_sorted_rotated_array.py | 22 --------- ...cpp => search_in_sorted_rotated_array.cpp} | 0 ...va => search_in_sorted_rotated_array.java} | 0 .../search_in_sorted_rotated_array.py | 46 +++++++++++++++++++ 4 files changed, 46 insertions(+), 22 deletions(-) delete mode 100644 Binary Search/Search_sorted_rotated_array.py rename Binary Search/{search_in_rotated_array.cpp => search_in_sorted_rotated_array.cpp} (100%) rename Binary Search/{search_in_rotated_array.java => search_in_sorted_rotated_array.java} (100%) create mode 100644 Binary Search/search_in_sorted_rotated_array.py diff --git a/Binary Search/Search_sorted_rotated_array.py b/Binary Search/Search_sorted_rotated_array.py deleted file mode 100644 index d469485b..00000000 --- a/Binary Search/Search_sorted_rotated_array.py +++ /dev/null @@ -1,22 +0,0 @@ -class Solution: - def binarySearch(nums,low,high,target): - if(low>high): - return -1 - mid = (low+high)//2 - if(nums[mid]target): - return Solution.binarySearch(nums,low,mid-1,target) - else: - return mid - - def search(self, nums: List[int], target: int) -> int: - #Finding the index where the array was rotated and binary searching the first and second parts for the target value. - rotated_index = -1 - for i in range(len(nums)-1): - if(nums[i]>nums[i+1]): - rotated_index = i - break - - return Solution.binarySearch(nums,0,rotated_index,target) & Solution.binarySearch(nums,rotated_index+1,len(nums)-1,target) - \ No newline at end of file diff --git a/Binary Search/search_in_rotated_array.cpp b/Binary Search/search_in_sorted_rotated_array.cpp similarity index 100% rename from Binary Search/search_in_rotated_array.cpp rename to Binary Search/search_in_sorted_rotated_array.cpp diff --git a/Binary Search/search_in_rotated_array.java b/Binary Search/search_in_sorted_rotated_array.java similarity index 100% rename from Binary Search/search_in_rotated_array.java rename to Binary Search/search_in_sorted_rotated_array.java diff --git a/Binary Search/search_in_sorted_rotated_array.py b/Binary Search/search_in_sorted_rotated_array.py new file mode 100644 index 00000000..028acf4a --- /dev/null +++ b/Binary Search/search_in_sorted_rotated_array.py @@ -0,0 +1,46 @@ +''' + There is an integer array nums sorted in ascending order (with distinct values). + + Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. + + Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + + You must write an algorithm with O(log n) runtime complexity. + + + + Example 1: + Input: nums = [4,5,6,7,0,1,2], target = 0 + Output: 4 + + Example 2: + Input: nums = [4,5,6,7,0,1,2], target = 3 + Output: -1 + + Example 3: + Input: nums = [1], target = 0 + Output: -1 + +''' +class Solution: + def binarySearch(nums,low,high,target): + if(low>high): + return -1 + mid = (low+high)//2 + if(nums[mid]target): + return Solution.binarySearch(nums,low,mid-1,target) + else: + return mid + + def search(self, nums: List[int], target: int) -> int: + #Finding the index where the array was rotated and binary searching the first and second parts for the target value. + rotated_index = -1 + for i in range(len(nums)-1): + if(nums[i]>nums[i+1]): + rotated_index = i + break + + return Solution.binarySearch(nums,0,rotated_index,target) & Solution.binarySearch(nums,rotated_index+1,len(nums)-1,target) + \ No newline at end of file From 2dd123aa6e44652cd626ecd89913d39969c5edae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:56:47 +0530 Subject: [PATCH 0372/1894] rename file --- ...ast_occurence.py => binary_serach_first_and_last_occurence.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary Search/{binary_serach_First_Last_occurence.py => binary_serach_first_and_last_occurence.py} (100%) diff --git a/Binary Search/binary_serach_First_Last_occurence.py b/Binary Search/binary_serach_first_and_last_occurence.py similarity index 100% rename from Binary Search/binary_serach_First_Last_occurence.py rename to Binary Search/binary_serach_first_and_last_occurence.py From 2df54ab4a6de186811be443a361f5ecd6c8f9528 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:57:53 +0530 Subject: [PATCH 0373/1894] add description --- Math/Hamming_distance.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Math/Hamming_distance.py b/Math/Hamming_distance.py index 6817192f..7e800b4f 100644 --- a/Math/Hamming_distance.py +++ b/Math/Hamming_distance.py @@ -1,3 +1,24 @@ +''' + The Hamming distance between two integers is the number of positions at which the corresponding bits are different. + + Given two integers x and y, return the Hamming distance between them. + + Example 1: + Input: x = 1, y = 4 + Output: 2 + Explanation: + 1 (0 0 0 1) + 4 (0 1 0 0) + ↑ ↑ + The above arrows point to positions where the corresponding bits are different. + + Example 2: + Input: x = 3, y = 1 + Output: 1 + + Constraints: + 0 <= x, y <= 231 - 1 +''' class Solution: def totalHammingDistance(self, nums: List[int]) -> int: '''By using bit manipulation, as all the array elements are 32-bit array elements, we calculate all the number of set bits and unset bits as we need to consider the permutations, we take setbits*unsetbits.''' From f95df948d4f55135c200c88e09c9ce9dff6b5ebd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 22:59:25 +0530 Subject: [PATCH 0374/1894] add description --- Math/unique_digits.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Math/unique_digits.py b/Math/unique_digits.py index 956632b0..ef4b25c7 100644 --- a/Math/unique_digits.py +++ b/Math/unique_digits.py @@ -1,3 +1,18 @@ +''' + Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. + + Example 1: + Input: n = 2 + Output: 91 + Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 + + Example 2: + Input: n = 0 + Output: 1 + + Constraints: + 0 <= n <= 8 +''' class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: '''For n = 0, ans = 1 From 37d5b11386f7c6538d507b0ebb65cd42e05157e8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Mar 2023 23:00:11 +0530 Subject: [PATCH 0375/1894] add description --- Recursion/tower_of_hannoi.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Recursion/tower_of_hannoi.py b/Recursion/tower_of_hannoi.py index fbe62ace..8cef5cd0 100644 --- a/Recursion/tower_of_hannoi.py +++ b/Recursion/tower_of_hannoi.py @@ -1,4 +1,15 @@ +''' + Towers of Hanoi puzzle. + Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) + Object of the game is to move all the disks over to Tower 3. + But you cannot place a larger disk onto a smaller disk. + + Approach + 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, + 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, + 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. +''' #Tower of Hanoi explanation - https://youtu.be/YstLjLCGmgg def TowerOfHanoi(n, A,B,C): if n == 0: From 22c46764d0bcadf0fbfd1ef923bf8f7a7e32c12b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:04:51 +0530 Subject: [PATCH 0376/1894] rename file --- Recursion/is_array_sorted.go | 5 +---- Recursion/{Valid_Palindrome_II.py => valid_palindrome_2.py} | 0 2 files changed, 1 insertion(+), 4 deletions(-) rename Recursion/{Valid_Palindrome_II.py => valid_palindrome_2.py} (100%) diff --git a/Recursion/is_array_sorted.go b/Recursion/is_array_sorted.go index 70023259..7a98256e 100644 --- a/Recursion/is_array_sorted.go +++ b/Recursion/is_array_sorted.go @@ -1,7 +1,4 @@ -/* - Given an array, check whether the array is in sorted order with recursion. -*/ -// Time Complexity: O(n). Space Complexity: O(n) for recursive stack space. +// Given an array, check whether the array is in sorted order with recursion. package main diff --git a/Recursion/Valid_Palindrome_II.py b/Recursion/valid_palindrome_2.py similarity index 100% rename from Recursion/Valid_Palindrome_II.py rename to Recursion/valid_palindrome_2.py From 7dbf6783d80e7c7348a017811117f4eefb516c0c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:05:15 +0530 Subject: [PATCH 0377/1894] rename file --- .../{is_sorted.cpp => is_array_sorted.cpp} | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) rename Recursion/{is_sorted.cpp => is_array_sorted.cpp} (96%) diff --git a/Recursion/is_sorted.cpp b/Recursion/is_array_sorted.cpp similarity index 96% rename from Recursion/is_sorted.cpp rename to Recursion/is_array_sorted.cpp index aad9679c..1ce5bb3d 100644 --- a/Recursion/is_sorted.cpp +++ b/Recursion/is_array_sorted.cpp @@ -1,20 +1,20 @@ -// Program to check if an array is alerady sorted -// Sample Input: [1, 2, 3, 4, 4, 5, 3] -// Output: 0 meaning false -// Sample Output: [1, 2, 3, 4, 4, 5, 6] -// Output: 1 meaning true -#include -using namespace std; -bool is_sorted(int A[], int m){ - if(m == 0 || m == 1) - return true; - if(A[0] > A[1]) - return false; - bool small_array = is_sorted(A + 1, m - 1); - return small_array; -} -int main(){ - int A[7] = {1, 2, 3, 4, 4, 5, 3}; - cout << is_sorted(A, 7); - return 0; +// Program to check if an array is alerady sorted +// Sample Input: [1, 2, 3, 4, 4, 5, 3] +// Output: 0 meaning false +// Sample Output: [1, 2, 3, 4, 4, 5, 6] +// Output: 1 meaning true +#include +using namespace std; +bool is_sorted(int A[], int m){ + if(m == 0 || m == 1) + return true; + if(A[0] > A[1]) + return false; + bool small_array = is_sorted(A + 1, m - 1); + return small_array; +} +int main(){ + int A[7] = {1, 2, 3, 4, 4, 5, 3}; + cout << is_sorted(A, 7); + return 0; } \ No newline at end of file From 08811b6bfa66411d1916bf6a8a1475eb0a6bcaea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:09:27 +0530 Subject: [PATCH 0378/1894] remove test file --- Bit Manipulation/count_bits_test.go | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 Bit Manipulation/count_bits_test.go diff --git a/Bit Manipulation/count_bits_test.go b/Bit Manipulation/count_bits_test.go deleted file mode 100644 index 2ee26983..00000000 --- a/Bit Manipulation/count_bits_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package bitmanipulation - -import ( - "testing" - "regexp" -) - -func TestCountBits(t *testing.T) { - msg, err := CountBits(5) - if msg != 2 && err != nil { - t.Fatalf(`CountBits(5) = %q %v, want "", error`, msg, err) - } - -} \ No newline at end of file From 2c1ee23c19ea1c6a55490de269552e0d64572653 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:11:36 +0530 Subject: [PATCH 0379/1894] rename file --- Strings/{rev_string.go => reverse_string.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Strings/{rev_string.go => reverse_string.go} (100%) diff --git a/Strings/rev_string.go b/Strings/reverse_string.go similarity index 100% rename from Strings/rev_string.go rename to Strings/reverse_string.go From 583a513c3d625e928666191972ae3d3f3791a72f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:12:58 +0530 Subject: [PATCH 0380/1894] add sample io --- Strings/check_permutations.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Strings/check_permutations.cpp b/Strings/check_permutations.cpp index 1223ec08..defef319 100644 --- a/Strings/check_permutations.cpp +++ b/Strings/check_permutations.cpp @@ -1,4 +1,6 @@ // Check if a string is a permutation of other +// Sample Input: s1 = abba s2 = baba +// Output: true #include using namespace std; bool check_permutations(string a, string b){ From 3d68bccac206de0762d7d9d1d260cfdeb3476a81 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:13:26 +0530 Subject: [PATCH 0381/1894] add time and space complexity --- Strings/check_permutations.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Strings/check_permutations.cpp b/Strings/check_permutations.cpp index defef319..04d94c10 100644 --- a/Strings/check_permutations.cpp +++ b/Strings/check_permutations.cpp @@ -1,6 +1,7 @@ // Check if a string is a permutation of other // Sample Input: s1 = abba s2 = baba // Output: true +// Time Complexity O(n) Space complexity O(1) #include using namespace std; bool check_permutations(string a, string b){ From f6c0c1b92bf72cab90d694ee3f4a39df2733b253 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Mar 2023 22:15:57 +0530 Subject: [PATCH 0382/1894] add description --- Strings/check_permutations.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Strings/check_permutations.cpp b/Strings/check_permutations.cpp index 04d94c10..6d6b3e6d 100644 --- a/Strings/check_permutations.cpp +++ b/Strings/check_permutations.cpp @@ -5,21 +5,21 @@ #include using namespace std; bool check_permutations(string a, string b){ - vector Freq(26, 0); + vector Freq(26, 0); // assuming only letters for(int i = 0; i < a.length(); i++){ Freq[a[i] - 'a']++; } for(int x : Freq) cout << x << ","; cout << endl; for(int i = 0; i < b.length(); i++){ - if(Freq[b[i] - 'a'] > 0) - Freq[b[i] - 'a']--; + if(Freq[b[i] - 'a'] > 0) // seen a letter + Freq[b[i] - 'a']--; // reduce count else - Freq[b[i] - 'a']++; + Freq[b[i] - 'a']++; // not seen before so increase count } for(int x : Freq) cout << x << ","; cout << endl; - int res = accumulate(Freq.begin(), Freq.end(), 0); + int res = accumulate(Freq.begin(), Freq.end(), 0); // checl of sum of elements in freq is 0 return res == 0 ? true : false; } int main(){ From e8f7a00c1d561d3527b6dae9b780d257a0c750d1 Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Sun, 5 Mar 2023 17:22:17 -0500 Subject: [PATCH 0383/1894] String & Math questions --- ..._substring_without_repeating_characters.py | 36 +++++++++++++++++++ Math/check_if_num_is_palindrome.py | 13 +++++++ Strings/Longest_palindromic_substring.py | 27 ++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 Hash Table/Longest_substring_without_repeating_characters.py create mode 100644 Math/check_if_num_is_palindrome.py create mode 100644 Strings/Longest_palindromic_substring.py diff --git a/Hash Table/Longest_substring_without_repeating_characters.py b/Hash Table/Longest_substring_without_repeating_characters.py new file mode 100644 index 00000000..2fb8a903 --- /dev/null +++ b/Hash Table/Longest_substring_without_repeating_characters.py @@ -0,0 +1,36 @@ +class Solution: + #Approach-1 + #Time Complexity - O(N^2), Space complexity - O(N) + #Adding brute-force values into hash_map and calculating the max_length + def lengthOfLongestSubstring(self, s: str) -> int: + if(len(s)==0 or len(s)==1): + return len(s) + max_length = 0 + for i in range(len(s)): + temp_length,temp = 0,set() + for j in range(i,len(s)): + if(temp_length int: + if(len(s)==0): + return 0 + hash_set = set() + start_ind,end_ind = 0,0 + max_length = -1 + while(end_ind bool: + #check if the number is less than zero. + if(x<0): + return False + #Then, calculating the reverse of the number to see if it is equal to the original number. + rev = 0 + original_value = x + while x != 0: + rev = rev * 10 + x % 10 + x = x// 10 + return rev == original_value \ No newline at end of file diff --git a/Strings/Longest_palindromic_substring.py b/Strings/Longest_palindromic_substring.py new file mode 100644 index 00000000..5295ad22 --- /dev/null +++ b/Strings/Longest_palindromic_substring.py @@ -0,0 +1,27 @@ +class Solution: + #Instead of checking if a value is palindrome from the end, we can consider each index to be the center + #Then, Check if the left and right indexed values to it are different. + #The edge case would to find even lengthed palindrome like the second example + #Reference: https://www.youtube.com/watch?v=XYQecbcd6_c + + def __init__(self): + self.max_length = -1 + self.max_palindrome = "" + def CheckLeftRight(self,s,index,value): + low,high = index,index + if(value=="even"): + high=index+1 + while(low>=0 and highself.max_length): + self.max_length = high-low+1 + self.max_palindrome = s[low:high+1] + low-=1 + high+=1 + + def longestPalindrome(self, s: str) -> str: + for i in range(len(s)): + #odd values + Solution.CheckLeftRight(self,s,i,"odd") + #Even values + Solution.CheckLeftRight(self,s,i,"even") + return self.max_palindrome \ No newline at end of file From eac931870a71a66a3dd70ea078bf38bebaf06788 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 20:45:00 +0530 Subject: [PATCH 0384/1894] add description --- ..._substring_without_repeating_characters.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Hash Table/Longest_substring_without_repeating_characters.py b/Hash Table/Longest_substring_without_repeating_characters.py index 2fb8a903..d23875d1 100644 --- a/Hash Table/Longest_substring_without_repeating_characters.py +++ b/Hash Table/Longest_substring_without_repeating_characters.py @@ -1,3 +1,28 @@ +''' + Given a string s, find the length of the longest + substring + without repeating characters. + + Example 1: + Input: s = "abcabcbb" + Output: 3 + Explanation: The answer is "abc", with the length of 3. + + Example 2: + Input: s = "bbbbb" + Output: 1 + Explanation: The answer is "b", with the length of 1. + + Example 3: + Input: s = "pwwkew" + Output: 3 + Explanation: The answer is "wke", with the length of 3. + Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + + Constraints: + 0 <= s.length <= 5 * 104 + s consists of English letters, digits, symbols and spaces. +''' class Solution: #Approach-1 #Time Complexity - O(N^2), Space complexity - O(N) From 11512be59e33151198713877030b3a6cdfa9010e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 20:46:40 +0530 Subject: [PATCH 0385/1894] add description --- Math/check_if_num_is_palindrome.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Math/check_if_num_is_palindrome.cpp b/Math/check_if_num_is_palindrome.cpp index 621974c9..7cfe4c2f 100644 --- a/Math/check_if_num_is_palindrome.cpp +++ b/Math/check_if_num_is_palindrome.cpp @@ -1,3 +1,27 @@ +/* + Given an integer x, return true if x is a + palindrome + , and false otherwise. + + Example 1: + Input: x = 121 + Output: true + Explanation: 121 reads as 121 from left to right and from right to left. + + Example 2: + Input: x = -121 + Output: false + Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. + + Example 3: + Input: x = 10 + Output: false + Explanation: Reads 01 from right to left. Therefore it is not a palindrome. + Constraints: + -231 <= x <= 231 - 1 + + Follow up: Could you solve it without converting the integer to a string? +*/ class Solution { public: bool isPalindrome(int num) { From c5b58ed49423c6ab9173badd84cc1ac6696f8d59 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 20:46:43 +0530 Subject: [PATCH 0386/1894] add description --- Math/check_if_num_is_palindrome.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Math/check_if_num_is_palindrome.py b/Math/check_if_num_is_palindrome.py index 9cf3157c..b211df50 100644 --- a/Math/check_if_num_is_palindrome.py +++ b/Math/check_if_num_is_palindrome.py @@ -1,4 +1,27 @@ +''' + Given an integer x, return true if x is a + palindrome + , and false otherwise. + Example 1: + Input: x = 121 + Output: true + Explanation: 121 reads as 121 from left to right and from right to left. + + Example 2: + Input: x = -121 + Output: false + Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. + + Example 3: + Input: x = 10 + Output: false + Explanation: Reads 01 from right to left. Therefore it is not a palindrome. + Constraints: + -231 <= x <= 231 - 1 + + Follow up: Could you solve it without converting the integer to a string? +''' class Solution: def isPalindrome(self, x: int) -> bool: #check if the number is less than zero. From 232f9b656bfc05ceb269368ea18a2789380c03b4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 20:48:00 +0530 Subject: [PATCH 0387/1894] add description --- Strings/Longest_palindromic_substring.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Strings/Longest_palindromic_substring.py b/Strings/Longest_palindromic_substring.py index 5295ad22..429e0808 100644 --- a/Strings/Longest_palindromic_substring.py +++ b/Strings/Longest_palindromic_substring.py @@ -1,3 +1,19 @@ +''' + Given a string s, return the longest palindromic substring in s. + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +''' class Solution: #Instead of checking if a value is palindrome from the end, we can consider each index to be the center #Then, Check if the left and right indexed values to it are different. From d0b01c434d2f5b182b72e3f9bcd3f499e287e161 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 22:54:29 +0530 Subject: [PATCH 0388/1894] update description --- Strings/valid_pallindrome2.cpp | 14 ++++++-------- Strings/valid_pallindrome2.go | 14 ++++++-------- Strings/valid_pallindrome2.js | 14 ++++++-------- Strings/valid_pallindrome2.py | 18 ++++++++---------- 4 files changed, 26 insertions(+), 34 deletions(-) diff --git a/Strings/valid_pallindrome2.cpp b/Strings/valid_pallindrome2.cpp index 2d083681..319cdfe9 100644 --- a/Strings/valid_pallindrome2.cpp +++ b/Strings/valid_pallindrome2.cpp @@ -1,15 +1,13 @@ /* -Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. -Constraints: - string.length - The string only consists of English letters + Constraints: string.length The string only consists of English letters -Sample Input : "madame" -Output : True + Sample Input : "madame" + Output : True -Sample Input : "masdasd" -Output : False + Sample Input : "masdasd" + Output : False */ class Solution { public: diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go index f991be31..2079c815 100644 --- a/Strings/valid_pallindrome2.go +++ b/Strings/valid_pallindrome2.go @@ -1,15 +1,13 @@ /* -Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. -Constraints: - string.length - The string only consists of English letters + Constraints: string.length The string only consists of English letters -Sample Input : "madame" -Output : True + Sample Input : "madame" + Output : True -Sample Input : "masdasd" -Output : False + Sample Input : "masdasd" + Output : False */ package main diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js index 892681f5..8fa8be8f 100644 --- a/Strings/valid_pallindrome2.js +++ b/Strings/valid_pallindrome2.js @@ -1,15 +1,13 @@ /* -Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. -Constraints: - string.length - The string only consists of English letters + Constraints: string.length The string only consists of English letters -Sample Input : "madame" -Output : True + Sample Input : "madame" + Output : True -Sample Input : "masdasd" -Output : False + Sample Input : "masdasd" + Output : False */ // using two-pointer Technique diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py index 77c4d275..2e7ecace 100644 --- a/Strings/valid_pallindrome2.py +++ b/Strings/valid_pallindrome2.py @@ -1,16 +1,14 @@ -# Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. +''' + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. -# Constraints: -# string.length -# The string only consists of English letters - -# Sample Input : "madame" -# Output : True - -# Sample Input : "masdasd" -# Output : False + Constraints: string.length The string only consists of English letters + Sample Input : "madame" + Output : True + Sample Input : "masdasd" + Output : False +''' # using two-pointer Technique def valid_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 From 737b17a6f46f4ddd7dc9220de568aecff31bc8a0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 22:54:56 +0530 Subject: [PATCH 0389/1894] update description --- Strings/well_formed_parentheses.cpp | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/Strings/well_formed_parentheses.cpp b/Strings/well_formed_parentheses.cpp index 97b99e0f..f8eca0a6 100644 --- a/Strings/well_formed_parentheses.cpp +++ b/Strings/well_formed_parentheses.cpp @@ -1,21 +1,15 @@ /* -Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. - - -Example 1: - -Input: n = 3 -Output: ["((()))","(()())","(())()","()(())","()()()"] -Example 2: - -Input: n = 1 -Output: ["()"] - - -Constraints: - -1 <= n <= 8 + Example 1: + Input: n = 3 + Output: ["((()))","(()())","(())()","()(())","()()()"] + + Example 2: + Input: n = 1 + Output: ["()"] + + Constraints: 1 <= n <= 8 */ #include class Solution { From 137c7f9528f642517baf6738a14b397e70bdcc69 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Mar 2023 22:55:31 +0530 Subject: [PATCH 0390/1894] update description --- Strings/zigzag_conversion.cpp | 66 ++++++++++++++++------------------- 1 file changed, 30 insertions(+), 36 deletions(-) diff --git a/Strings/zigzag_conversion.cpp b/Strings/zigzag_conversion.cpp index 2dbb6ceb..ec9a6ffc 100644 --- a/Strings/zigzag_conversion.cpp +++ b/Strings/zigzag_conversion.cpp @@ -1,40 +1,34 @@ /* -The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) - -P A H N -A P L S I I G -Y I R -And then read line by line: "PAHNAPLSIIGYIR" - -Write the code that will take a string and make this conversion given a number of rows: - -string convert(string s, int numRows); - - -Example 1: - -Input: s = "PAYPALISHIRING", numRows = 3 -Output: "PAHNAPLSIIGYIR" -Example 2: - -Input: s = "PAYPALISHIRING", numRows = 4 -Output: "PINALSIGYAHRPI" -Explanation: -P I N -A L S I G -Y A H R -P I -Example 3: - -Input: s = "A", numRows = 1 -Output: "A" - - -Constraints: - -1 <= s.length <= 1000 -s consists of English letters (lower-case and upper-case), ',' and '.'. -1 <= numRows <= 1000 + The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) + P A H N + A P L S I I G + Y I R + And then read line by line: "PAHNAPLSIIGYIR" + + Write the code that will take a string and make this conversion given a number of rows: + string convert(string s, int numRows); + + Example 1: + Input: s = "PAYPALISHIRING", numRows = 3 + Output: "PAHNAPLSIIGYIR" + + Example 2: + Input: s = "PAYPALISHIRING", numRows = 4 + Output: "PINALSIGYAHRPI" + Explanation: + P I N + A L S I G + Y A H R + P I + + Example 3: + Input: s = "A", numRows = 1 + Output: "A" + + Constraints:\ + 1 <= s.length <= 1000 + s consists of English letters (lower-case and upper-case), ',' and '.'. + 1 <= numRows <= 1000 */ #include From 15e8226efc8bc8dd548aa768958036e3df7a702c Mon Sep 17 00:00:00 2001 From: Anurag Naren Kallakunta Date: Mon, 6 Mar 2023 17:58:57 -0500 Subject: [PATCH 0391/1894] Math questions and Floyds Algorithm --- .../linked_list_floyds_cycle_detection.py | 17 +++++++++++ Math/Integer_to_roman.py | 12 ++++++++ Math/K_closest_points_to_origin.py | 28 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 Linked List/linked_list_floyds_cycle_detection.py create mode 100644 Math/Integer_to_roman.py create mode 100644 Math/K_closest_points_to_origin.py diff --git a/Linked List/linked_list_floyds_cycle_detection.py b/Linked List/linked_list_floyds_cycle_detection.py new file mode 100644 index 00000000..a1abf506 --- /dev/null +++ b/Linked List/linked_list_floyds_cycle_detection.py @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def hasCycle(self, head: Optional[ListNode]) -> bool: + #Floyd's cycle detection algorithm uses slow and fast points to find the loop + #Reference - https://www.geeksforgeeks.org/floyds-cycle-finding-algorithm/ + slow,fast= head,head + while(slow!=None and fast!=None and fast.next!=None): + slow = slow.next + fast = fast.next.next + if(slow == fast): + return True + return False \ No newline at end of file diff --git a/Math/Integer_to_roman.py b/Math/Integer_to_roman.py new file mode 100644 index 00000000..f7ddfdfa --- /dev/null +++ b/Math/Integer_to_roman.py @@ -0,0 +1,12 @@ +class Solution: + def intToRoman(self, num: int) -> str: + #Based on given rules, we can directly consider the other possibilities + #Then, we can divide it directly as required and take the roman values + arr = [["I",1],["IV",4],["V",5],["IX",9],["X",10],["XL",40],["L",50],["XC",90],["C",100],["CD",400],["D",500],["CM",900],["M",1000]] + + final_string = "" + for i in arr[::-1]: + rev = num//i[1] + final_string += i[0]*rev + num = num%i[1] + return final_string diff --git a/Math/K_closest_points_to_origin.py b/Math/K_closest_points_to_origin.py new file mode 100644 index 00000000..54e49c63 --- /dev/null +++ b/Math/K_closest_points_to_origin.py @@ -0,0 +1,28 @@ +import math +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + distance_arr=[] + #calculating the distance from center + for i in points: + distance_arr.append(math.sqrt(pow(i[0],2)+pow(i[1],2))) + #Mapping the values of distance and point + #Also considering the collision if two points have same distance from origin + hash_map={} + for i in range(len(points)): + if(distance_arr[i] in hash_map): + hash_map[distance_arr[i]].append(points[i]) + else: + hash_map[distance_arr[i]] = [points[i]] + + #sorting distances + distance_arr.sort() + + #Retrieving the values in the order of distance from distance_arr + final_arr,count = [],0 + for i in range(len(points)): + for j in hash_map[distance_arr[i]]: + final_arr.append(j) + count+=1 + if(count>=k): + break + return final_arr \ No newline at end of file From 017fda14b4fb03119a9cc92f3ca6fb5ee69e73d5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:14:19 +0530 Subject: [PATCH 0392/1894] rename file --- ...ked_list_dalete_at_tail.cpp => linked_list_delete_at_tail.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Linked List/{linked_list_dalete_at_tail.cpp => linked_list_delete_at_tail.cpp} (100%) diff --git a/Linked List/linked_list_dalete_at_tail.cpp b/Linked List/linked_list_delete_at_tail.cpp similarity index 100% rename from Linked List/linked_list_dalete_at_tail.cpp rename to Linked List/linked_list_delete_at_tail.cpp From 923f71590ebc0e52464c03b9200bb2a171949ebf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:14:30 +0530 Subject: [PATCH 0393/1894] rename file --- ...cycle_detection.cpp => linked_list_floyds_cycle_detection.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Fast and Slow Pointers/{linked_floyds_cycle_detection.cpp => linked_list_floyds_cycle_detection.cpp} (100%) diff --git a/Fast and Slow Pointers/linked_floyds_cycle_detection.cpp b/Fast and Slow Pointers/linked_list_floyds_cycle_detection.cpp similarity index 100% rename from Fast and Slow Pointers/linked_floyds_cycle_detection.cpp rename to Fast and Slow Pointers/linked_list_floyds_cycle_detection.cpp From eae065a324f5512c1a0a8d2e7517fbe109aaa94c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:14:36 +0530 Subject: [PATCH 0394/1894] add description --- .../linked_list_floyds_cycle_detection.py | 7 +++++++ 1 file changed, 7 insertions(+) rename {Linked List => Fast and Slow Pointers}/linked_list_floyds_cycle_detection.py (64%) diff --git a/Linked List/linked_list_floyds_cycle_detection.py b/Fast and Slow Pointers/linked_list_floyds_cycle_detection.py similarity index 64% rename from Linked List/linked_list_floyds_cycle_detection.py rename to Fast and Slow Pointers/linked_list_floyds_cycle_detection.py index a1abf506..923acd77 100644 --- a/Linked List/linked_list_floyds_cycle_detection.py +++ b/Fast and Slow Pointers/linked_list_floyds_cycle_detection.py @@ -1,3 +1,10 @@ +''' + Floyds Cycle detection and removal + Program Author : Abhisek Kumar Gupta + The cycle detection problem is to find the cycle in a sequence, + and Floyd’s cycle detection algorithm, aka Tortoise and Hare algorithm, + is a two-pointer algorithm to detect the cycle and locate the start of the cycle as well. +''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): From 16bb84a73e981ba467ad01778925dc22b699eeaf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:16:20 +0530 Subject: [PATCH 0395/1894] move to hash table directory and add description --- Hash Table/integer_to_roman.py | 51 ++++++++++++++++++++++++++++++++++ Math/Integer_to_roman.py | 12 -------- 2 files changed, 51 insertions(+), 12 deletions(-) create mode 100644 Hash Table/integer_to_roman.py delete mode 100644 Math/Integer_to_roman.py diff --git a/Hash Table/integer_to_roman.py b/Hash Table/integer_to_roman.py new file mode 100644 index 00000000..70b164c8 --- /dev/null +++ b/Hash Table/integer_to_roman.py @@ -0,0 +1,51 @@ +''' + Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + + Symbol Value + I 1 + V 5 + X 10 + L 50 + C 100 + D 500 + M 1000 + For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. + + Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + + I can be placed before V (5) and X (10) to make 4 and 9. + X can be placed before L (50) and C (100) to make 40 and 90. + C can be placed before D (500) and M (1000) to make 400 and 900. + + Given an integer, convert it to a roman numeral. + + Example 1: + Input: num = 3 + Output: "III" + Explanation: 3 is represented as 3 ones. + + Example 2: + Input: num = 58 + Output: "LVIII" + Explanation: L = 50, V = 5, III = 3. + + Example 3: + Input: num = 1994 + Output: "MCMXCIV" + Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + + Constraints: + 1 <= num <= 3999 +''' +class Solution: + def intToRoman(self, num: int) -> str: + #Based on given rules, we can directly consider the other possibilities + #Then, we can divide it directly as required and take the roman values + arr = [["I",1],["IV",4],["V",5],["IX",9],["X",10],["XL",40],["L",50],["XC",90],["C",100],["CD",400],["D",500],["CM",900],["M",1000]] + + final_string = "" + for i in arr[::-1]: + rev = num//i[1] + final_string += i[0]*rev + num = num%i[1] + return final_string diff --git a/Math/Integer_to_roman.py b/Math/Integer_to_roman.py deleted file mode 100644 index f7ddfdfa..00000000 --- a/Math/Integer_to_roman.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def intToRoman(self, num: int) -> str: - #Based on given rules, we can directly consider the other possibilities - #Then, we can divide it directly as required and take the roman values - arr = [["I",1],["IV",4],["V",5],["IX",9],["X",10],["XL",40],["L",50],["XC",90],["C",100],["CD",400],["D",500],["CM",900],["M",1000]] - - final_string = "" - for i in arr[::-1]: - rev = num//i[1] - final_string += i[0]*rev - num = num%i[1] - return final_string From b02792c38690aa1abd92af971cb05751ea7aa1ea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:17:26 +0530 Subject: [PATCH 0396/1894] add description --- Math/K_closest_points_to_origin.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Math/K_closest_points_to_origin.py b/Math/K_closest_points_to_origin.py index 54e49c63..77aa76b2 100644 --- a/Math/K_closest_points_to_origin.py +++ b/Math/K_closest_points_to_origin.py @@ -1,3 +1,28 @@ +''' + Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + + The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). + + You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + + Example 1: + Input: points = [[1,3],[-2,2]], k = 1 + Output: [[-2,2]] + Explanation: + The distance between (1, 3) and the origin is sqrt(10). + The distance between (-2, 2) and the origin is sqrt(8). + Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. + We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + + Example 2: + Input: points = [[3,3],[5,-1],[-2,4]], k = 2 + Output: [[3,3],[-2,4]] + Explanation: The answer [[-2,4],[3,3]] would also be accepted. + + Constraints: + 1 <= k <= points.length <= 104 + -104 < xi, yi < 104 +''' import math class Solution: def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: From 8142b7d3b0c71fef5ade32f8a82d9892b85f647c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:22:42 +0530 Subject: [PATCH 0397/1894] add description --- Math/num_steps_reduce_to_zero.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Math/num_steps_reduce_to_zero.cpp b/Math/num_steps_reduce_to_zero.cpp index a03b70bc..85618df1 100644 --- a/Math/num_steps_reduce_to_zero.cpp +++ b/Math/num_steps_reduce_to_zero.cpp @@ -1,3 +1,34 @@ +/* + Given an integer num, return the number of steps to reduce it to zero. + + In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + Example 1: + Input: num = 14 + Output: 6 + Explanation: + Step 1) 14 is even; divide by 2 and obtain 7. + Step 2) 7 is odd; subtract 1 and obtain 6. + Step 3) 6 is even; divide by 2 and obtain 3. + Step 4) 3 is odd; subtract 1 and obtain 2. + Step 5) 2 is even; divide by 2 and obtain 1. + Step 6) 1 is odd; subtract 1 and obtain 0. + + Example 2: + Input: num = 8 + Output: 4 + Explanation: + Step 1) 8 is even; divide by 2 and obtain 4. + Step 2) 4 is even; divide by 2 and obtain 2. + Step 3) 2 is even; divide by 2 and obtain 1. + Step 4) 1 is odd; subtract 1 and obtain 0. + + Example 3: + Input: num = 123 + Output: 12 + + Constraints: 0 <= num <= 106 +*/ class Solution { public: int numberOfSteps(int num) { From d319377ad23f313ef682f5a4f05fbe4747a8f8a2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Mar 2023 22:23:41 +0530 Subject: [PATCH 0398/1894] add description --- Math/num_steps_reduce_to_zero.Go | 31 ++++++++++++++ Math/num_steps_reduce_to_zero.java | 31 ++++++++++++++ Math/num_steps_reduce_to_zero.js | 69 ++++++++++++++++++++++-------- Math/num_steps_reduce_to_zero.py | 31 ++++++++++++++ 4 files changed, 143 insertions(+), 19 deletions(-) diff --git a/Math/num_steps_reduce_to_zero.Go b/Math/num_steps_reduce_to_zero.Go index f2fe1689..97c309b9 100644 --- a/Math/num_steps_reduce_to_zero.Go +++ b/Math/num_steps_reduce_to_zero.Go @@ -1,3 +1,34 @@ +/* + Given an integer num, return the number of steps to reduce it to zero. + + In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + Example 1: + Input: num = 14 + Output: 6 + Explanation: + Step 1) 14 is even; divide by 2 and obtain 7. + Step 2) 7 is odd; subtract 1 and obtain 6. + Step 3) 6 is even; divide by 2 and obtain 3. + Step 4) 3 is odd; subtract 1 and obtain 2. + Step 5) 2 is even; divide by 2 and obtain 1. + Step 6) 1 is odd; subtract 1 and obtain 0. + + Example 2: + Input: num = 8 + Output: 4 + Explanation: + Step 1) 8 is even; divide by 2 and obtain 4. + Step 2) 4 is even; divide by 2 and obtain 2. + Step 3) 2 is even; divide by 2 and obtain 1. + Step 4) 1 is odd; subtract 1 and obtain 0. + + Example 3: + Input: num = 123 + Output: 12 + + Constraints: 0 <= num <= 106 +*/ func numberOfSteps(num int) int { var steps = 0 for num != 0 { diff --git a/Math/num_steps_reduce_to_zero.java b/Math/num_steps_reduce_to_zero.java index 9b994762..5630ae9a 100644 --- a/Math/num_steps_reduce_to_zero.java +++ b/Math/num_steps_reduce_to_zero.java @@ -1,3 +1,34 @@ +/* + Given an integer num, return the number of steps to reduce it to zero. + + In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + Example 1: + Input: num = 14 + Output: 6 + Explanation: + Step 1) 14 is even; divide by 2 and obtain 7. + Step 2) 7 is odd; subtract 1 and obtain 6. + Step 3) 6 is even; divide by 2 and obtain 3. + Step 4) 3 is odd; subtract 1 and obtain 2. + Step 5) 2 is even; divide by 2 and obtain 1. + Step 6) 1 is odd; subtract 1 and obtain 0. + + Example 2: + Input: num = 8 + Output: 4 + Explanation: + Step 1) 8 is even; divide by 2 and obtain 4. + Step 2) 4 is even; divide by 2 and obtain 2. + Step 3) 2 is even; divide by 2 and obtain 1. + Step 4) 1 is odd; subtract 1 and obtain 0. + + Example 3: + Input: num = 123 + Output: 12 + + Constraints: 0 <= num <= 106 +*/ class Solution { public int numberOfSteps(int num) { // We initialize the step counter. diff --git a/Math/num_steps_reduce_to_zero.js b/Math/num_steps_reduce_to_zero.js index cb8371c8..28ba8951 100644 --- a/Math/num_steps_reduce_to_zero.js +++ b/Math/num_steps_reduce_to_zero.js @@ -1,25 +1,56 @@ +/* + Given an integer num, return the number of steps to reduce it to zero. + + In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + Example 1: + Input: num = 14 + Output: 6 + Explanation: + Step 1) 14 is even; divide by 2 and obtain 7. + Step 2) 7 is odd; subtract 1 and obtain 6. + Step 3) 6 is even; divide by 2 and obtain 3. + Step 4) 3 is odd; subtract 1 and obtain 2. + Step 5) 2 is even; divide by 2 and obtain 1. + Step 6) 1 is odd; subtract 1 and obtain 0. + + Example 2: + Input: num = 8 + Output: 4 + Explanation: + Step 1) 8 is even; divide by 2 and obtain 4. + Step 2) 4 is even; divide by 2 and obtain 2. + Step 3) 2 is even; divide by 2 and obtain 1. + Step 4) 1 is odd; subtract 1 and obtain 0. + + Example 3: + Input: num = 123 + Output: 12 + + Constraints: 0 <= num <= 106 +*/ /** * @param {number} num * @return {number} */ -var numberOfSteps = function(num) { - // We initialize the step counter. - let steps = 0; - // While the number is still not zero... - while (num != 0) { - // ...we check if it is odd or even. - // If it is even... - if (num % 2 == 0) { - // ...we divide it by 2 and increase the step counter. - num /= 2; - steps++; - // If it is odd... - } else { - // ...we substract 1 and increase the step counter. - num -= 1; - steps++; - } +var numberOfSteps = function (num) { + // We initialize the step counter. + let steps = 0; + // While the number is still not zero... + while (num != 0) { + // ...we check if it is odd or even. + // If it is even... + if (num % 2 == 0) { + // ...we divide it by 2 and increase the step counter. + num /= 2; + steps++; + // If it is odd... + } else { + // ...we substract 1 and increase the step counter. + num -= 1; + steps++; } - // Finally, we return the step counter. - return steps; + } + // Finally, we return the step counter. + return steps; }; diff --git a/Math/num_steps_reduce_to_zero.py b/Math/num_steps_reduce_to_zero.py index 5180507c..2f4c4b70 100644 --- a/Math/num_steps_reduce_to_zero.py +++ b/Math/num_steps_reduce_to_zero.py @@ -1,3 +1,34 @@ +''' + Given an integer num, return the number of steps to reduce it to zero. + + In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. + + Example 1: + Input: num = 14 + Output: 6 + Explanation: + Step 1) 14 is even; divide by 2 and obtain 7. + Step 2) 7 is odd; subtract 1 and obtain 6. + Step 3) 6 is even; divide by 2 and obtain 3. + Step 4) 3 is odd; subtract 1 and obtain 2. + Step 5) 2 is even; divide by 2 and obtain 1. + Step 6) 1 is odd; subtract 1 and obtain 0. + + Example 2: + Input: num = 8 + Output: 4 + Explanation: + Step 1) 8 is even; divide by 2 and obtain 4. + Step 2) 4 is even; divide by 2 and obtain 2. + Step 3) 2 is even; divide by 2 and obtain 1. + Step 4) 1 is odd; subtract 1 and obtain 0. + + Example 3: + Input: num = 123 + Output: 12 + + Constraints: 0 <= num <= 106 +''' class Solution(object): def numberOfSteps(self, num): """ From 11c43cf5bdc36d7d3e40f2cbb7be643974c48d72 Mon Sep 17 00:00:00 2001 From: Wesley Hanauer Date: Wed, 8 Mar 2023 11:54:40 -0300 Subject: [PATCH 0399/1894] Find the majority number in java --- Arrays/majority_number.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Arrays/majority_number.java diff --git a/Arrays/majority_number.java b/Arrays/majority_number.java new file mode 100644 index 00000000..495af235 --- /dev/null +++ b/Arrays/majority_number.java @@ -0,0 +1,19 @@ +class Solution { + public int majorityElement(int[] nums) { + int count = 0; + int target = nums[0]; + for(int i=0; i Date: Wed, 8 Mar 2023 23:15:08 +0530 Subject: [PATCH 0400/1894] add description --- Arrays/majority_number.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Arrays/majority_number.java b/Arrays/majority_number.java index 495af235..23c00bc2 100644 --- a/Arrays/majority_number.java +++ b/Arrays/majority_number.java @@ -1,3 +1,17 @@ +/* + Majority Element + Given an array nums of size n, return the majority element. + The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. + + Example 1: + Input: nums = [3,2,3] + Output: 3 + + Example 2: + Input: nums = [2,2,1,1,1,2,2] + Output: 2 +*/ + class Solution { public int majorityElement(int[] nums) { int count = 0; From 5b2f4e0e8fb8254e65fb19662f3d340abccb30d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:16:33 +0530 Subject: [PATCH 0401/1894] remove duplicate solution --- Arrays/majority_element.java | 47 ------------------------------------ 1 file changed, 47 deletions(-) delete mode 100644 Arrays/majority_element.java diff --git a/Arrays/majority_element.java b/Arrays/majority_element.java deleted file mode 100644 index f3923a7e..00000000 --- a/Arrays/majority_element.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -Majority Element - - -Given an array nums of size n, return the majority element. - -The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. - - - -Example 1: - -Input: nums = [3,2,3] -Output: 3 -Example 2: - -Input: nums = [2,2,1,1,1,2,2] -Output: 2 - --*/ - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -class Solution { - public int majorityElement(int[] nums) { - Set set = new HashSet<>(); - for (int i : nums) { - set.add(i); - } - ArrayList arr = new ArrayList<>(set); - int count = 0; - for (Integer var : arr) { - count = 0; - for (int j = 0; j < nums.length; j++) { - if (var.intValue() == nums[j]) { - count++; - } - } - if (count > nums.length / 2) { - return var.intValue(); - } - } - return 0; - } -} \ No newline at end of file From 90639096ffe2426e7b1704c335a15f34aa537dbe Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:17:43 +0530 Subject: [PATCH 0402/1894] rename file --- Arrays/{majority_number.java => majority_element.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{majority_number.java => majority_element.java} (100%) diff --git a/Arrays/majority_number.java b/Arrays/majority_element.java similarity index 100% rename from Arrays/majority_number.java rename to Arrays/majority_element.java From a7dc1942132a370da10c5d8a084b3623d8f058d3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:18:19 +0530 Subject: [PATCH 0403/1894] modify description --- 2D Arrays (Matrix)/2d_binary_search.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/2D Arrays (Matrix)/2d_binary_search.cpp b/2D Arrays (Matrix)/2d_binary_search.cpp index a8e29950..ad272b50 100644 --- a/2D Arrays (Matrix)/2d_binary_search.cpp +++ b/2D Arrays (Matrix)/2d_binary_search.cpp @@ -1,17 +1,19 @@ -/*You are given an m x n integer matrix matrix with the following two properties: +/* + You are given an m x n integer matrix matrix with the following two properties: -Each row is sorted in non-decreasing order. -The first integer of each row is greater than the last integer of the previous row. -Given an integer target, return true if target is in matrix or false otherwise. + Each row is sorted in non-decreasing order. + The first integer of each row is greater than the last integer of the previous row. + Given an integer target, return true if target is in matrix or false otherwise. -You must write a solution in O(log(m * n)) time complexity. + You must write a solution in O(log(m * n)) time complexity. -1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 -Output: true + 1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 + Output: true -2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 -Output: false*/ + 2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 + Output: false +*/ class Solution { bool costumBinarySearch(const vector>& matrix, int target, int low, int high){ From 6caadc2685331c21062fe791df1296b9e221fc22 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:20:04 +0530 Subject: [PATCH 0404/1894] modify description --- 2D Arrays (Matrix)/search_element.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/2D Arrays (Matrix)/search_element.cpp b/2D Arrays (Matrix)/search_element.cpp index 533fb2bb..7e608a70 100644 --- a/2D Arrays (Matrix)/search_element.cpp +++ b/2D Arrays (Matrix)/search_element.cpp @@ -1,17 +1,19 @@ -/*You are given an m x n integer matrix matrix with the following two properties: +/* + You are given an m x n integer matrix matrix with the following two properties: -Each row is sorted in non-decreasing order. -The first integer of each row is greater than the last integer of the previous row. -Given an integer target, return true if target is in matrix or false otherwise. + Each row is sorted in non-decreasing order. + The first integer of each row is greater than the last integer of the previous row. + Given an integer target, return true if target is in matrix or false otherwise. -You must write a solution in O(log(m * n)) time complexity. + You must write a solution in O(log(m * n)) time complexity. -1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 -Output: true + 1.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 + Output: true -2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 -Output: false*/ + 2.Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 + Output: false +*/ class Solution { public: From 99e718f59f3d6222db30aefe599bbe952888a37f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:21:31 +0530 Subject: [PATCH 0405/1894] modify program --- Recursion/calculatextopowern.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Recursion/calculatextopowern.cpp b/Recursion/calculatextopowern.cpp index 79f2bb1a..891e6686 100644 --- a/Recursion/calculatextopowern.cpp +++ b/Recursion/calculatextopowern.cpp @@ -1,15 +1,16 @@ -#include -using namespace std; // Canculate power of x^n // Sample Input : 3 2 // Output : 9 -/* Method 1 Time complexity O(n) -int power(int x, int n){ + +#include +using namespace std; + +// Method 1 Time complexity O(n) +int power1(int x, int n){ if(n == 0) return 1; - return x * power(x, n-1); + return x * power1(x, n-1); } -*/ // Method 2 : Time complexity O(log n) int power(int x, int n){ From 264a99814d79274b06ad6fba9ee510cff6da2151 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:22:20 +0530 Subject: [PATCH 0406/1894] modify description --- Recursion/factorial.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Recursion/factorial.js b/Recursion/factorial.js index 828bc36c..8a87ee0d 100644 --- a/Recursion/factorial.js +++ b/Recursion/factorial.js @@ -1,12 +1,14 @@ -// Program to find factorial till a given number +// Factorial of an integer +// Sample Input: 5 +// Output: 120 function recursiveFactorial(number) { - //Base case - if (number == 1) { - return 1; - } + //Base case + if (number == 1) { + return 1; + } - //recursively calling function to get factorial result - return number * recursiveFactorial(number - 1); + //recursively calling function to get factorial result + return number * recursiveFactorial(number - 1); } // Driver code From 2b595a20a16cf803d2735ec44ce94468a8a68bff Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Mar 2023 23:22:59 +0530 Subject: [PATCH 0407/1894] modify description --- Recursion/is_array_sorted.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Recursion/is_array_sorted.cpp b/Recursion/is_array_sorted.cpp index 1ce5bb3d..8d10ef0e 100644 --- a/Recursion/is_array_sorted.cpp +++ b/Recursion/is_array_sorted.cpp @@ -1,4 +1,4 @@ -// Program to check if an array is alerady sorted +// Given an array, check whether the array is in sorted order with recursion. // Sample Input: [1, 2, 3, 4, 4, 5, 3] // Output: 0 meaning false // Sample Output: [1, 2, 3, 4, 4, 5, 6] From db30f2c597b5d5d3629754693d996cd5063bf8b2 Mon Sep 17 00:00:00 2001 From: anandv07 Date: Thu, 9 Mar 2023 11:15:08 +0530 Subject: [PATCH 0408/1894] Add InfinityArray problem in java --- Binary_Search/InfinityArray.java | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Binary_Search/InfinityArray.java diff --git a/Binary_Search/InfinityArray.java b/Binary_Search/InfinityArray.java new file mode 100644 index 00000000..322b4b23 --- /dev/null +++ b/Binary_Search/InfinityArray.java @@ -0,0 +1,49 @@ +/*Binary Search in an Infinite array in Java + * Given an array whose size is not fixed,find the index of the target element in the array. + * EXAMPLE: [5,15,34,56,77,87...] (array can be of any size) + * Target = 56; + * Output: 3; + * + * APPROACH: + * The approach will be similar to normal binary search but in reverse order + * ie; For the start and end value, find the range which will be taking the target in the range. + * We will not specify the array length since the array size is infinity. + * Send the start and end value to the search function and return the position of the element. + * + */ + +public class InfinityArray { + public static void main(String[] args){ + int[] nums = {2,5,7,9,14,45,56,77,89,101};// can be of any size + int target = 56; + System.out.println(range(nums,target)); + } + + public static int range(int[] nums,int target){ + int start=0,end=1; + while(target > nums[end]){ + int temp = end +1; + end = end + (end-start)*2; + start = temp; + } + return search(nums,target,start,end); + } + public static int search(int[] nums, int target,int start,int end) { + while(start<=end){ + int mid = start + (end-start)/2; + // if middle value is equal to target return the mid index + if(nums[mid] == target){ + return mid; + } + // if mid value is greater than the target, search the left sub array + else if(nums[mid] > target){ + end = mid - 1; + } + // if mid value is lesser than the target, search the right sub array + else if(nums[mid] < target){ + start = mid + 1; + } + } + return -1; + } +} From 1b2568b6f8733e61e8de5c2974a6a2e35eea1141 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Thu, 9 Mar 2023 16:46:33 +0530 Subject: [PATCH 0409/1894] added TOH problem with java --- ...Demonstrate Tower of Hanoi Problem in Java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Recursion/Demonstrate Tower of Hanoi Problem in Java diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in Java b/Recursion/Demonstrate Tower of Hanoi Problem in Java new file mode 100644 index 00000000..db62146f --- /dev/null +++ b/Recursion/Demonstrate Tower of Hanoi Problem in Java @@ -0,0 +1,56 @@ +The Tower of Hanoi problem is a classic problem in computer science and mathematics that involves moving a stack of disks from one peg to another peg. The problem consists of three pegs and a set of disks of different sizes that can slide onto any peg. The objective of the puzzle is to move the entire stack to another peg, obeying the following simple rules: + +Only one disk can be moved at a time. +Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or an empty peg. +No disk may be placed on top of a smaller disk. +The Tower of Hanoi problem is often used as an example of recursive problem-solving. The solution to the problem can be divided into three parts: + +Move n-1 disks from the starting peg to the auxiliary peg. +Move the largest disk from the starting peg to the destination peg. +Move the n-1 disks from the auxiliary peg to the destination peg. +This process is repeated recursively until all the disks have been moved from the starting peg to the destination peg. The number of moves required to solve the puzzle for n disks can be calculated using the formula 2^n - 1. + + + + + + +Here's an implementation of the Tower of Hanoi problem in Java using recursion: + +public class TowerOfHanoi { + public static void main(String[] args) { + int n = 3; // number of disks + char fromRod = 'A'; + char toRod = 'C'; + char auxRod = 'B'; + + System.out.println("Moves to solve Tower of Hanoi problem with " + n + " disks:"); + solveHanoi(n, fromRod, toRod, auxRod); + } + + public static void solveHanoi(int n, char fromRod, char toRod, char auxRod) { + if (n == 1) { + System.out.println("Move disk 1 from rod " + fromRod + " to rod " + toRod); + return; + } + solveHanoi(n - 1, fromRod, auxRod, toRod); + System.out.println("Move disk " + n + " from rod " + fromRod + " to rod " + toRod); + solveHanoi(n - 1, auxRod, toRod, fromRod); + } +} + + +-----------------------Explanation------------------------------ + +In this implementation, the solveHanoi method is called recursively to move the disks from one rod to another. The method takes in four parameters: + +n: the number of disks +fromRod: the rod from which the disks are to be moved +toRod: the rod to which the disks are to be moved +auxRod: the auxiliary rod which can be used to move the disks +When the number of disks is 1, the method simply prints the move to be made. Otherwise, the method makes the following three recursive calls: + +Move n-1 disks from fromRod to auxRod using toRod as the auxiliary rod. +Move the nth disk from fromRod to toRod. +Move the n-1 disks from auxRod to toRod using fromRod as the auxiliary rod. +This process is repeated recursively until all the disks have been moved from the starting rod to the destination rod. \ No newline at end of file From 5456fc59d1e882399c8d2d273872c1979e15f7f9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:36:13 +0530 Subject: [PATCH 0410/1894] rename file --- Binary_Search/{InfinityArray.java => infinity_array.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Binary_Search/{InfinityArray.java => infinity_array.java} (100%) diff --git a/Binary_Search/InfinityArray.java b/Binary_Search/infinity_array.java similarity index 100% rename from Binary_Search/InfinityArray.java rename to Binary_Search/infinity_array.java From d4f9bdf2ebfd17e8b078c4f5b100afd9e176d3ce Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:36:26 +0530 Subject: [PATCH 0411/1894] move inside Binary Search --- {Binary_Search => Binary Search}/infinity_array.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Binary_Search => Binary Search}/infinity_array.java (100%) diff --git a/Binary_Search/infinity_array.java b/Binary Search/infinity_array.java similarity index 100% rename from Binary_Search/infinity_array.java rename to Binary Search/infinity_array.java From 110998001e3b174ffee6826b4310f7951c8a1385 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:38:21 +0530 Subject: [PATCH 0412/1894] update file name and description --- ...Demonstrate Tower of Hanoi Problem in Java | 56 ------------------- Recursion/tower_of_hannoi.java | 53 ++++++++++++++++++ 2 files changed, 53 insertions(+), 56 deletions(-) delete mode 100644 Recursion/Demonstrate Tower of Hanoi Problem in Java create mode 100644 Recursion/tower_of_hannoi.java diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in Java b/Recursion/Demonstrate Tower of Hanoi Problem in Java deleted file mode 100644 index db62146f..00000000 --- a/Recursion/Demonstrate Tower of Hanoi Problem in Java +++ /dev/null @@ -1,56 +0,0 @@ -The Tower of Hanoi problem is a classic problem in computer science and mathematics that involves moving a stack of disks from one peg to another peg. The problem consists of three pegs and a set of disks of different sizes that can slide onto any peg. The objective of the puzzle is to move the entire stack to another peg, obeying the following simple rules: - -Only one disk can be moved at a time. -Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or an empty peg. -No disk may be placed on top of a smaller disk. -The Tower of Hanoi problem is often used as an example of recursive problem-solving. The solution to the problem can be divided into three parts: - -Move n-1 disks from the starting peg to the auxiliary peg. -Move the largest disk from the starting peg to the destination peg. -Move the n-1 disks from the auxiliary peg to the destination peg. -This process is repeated recursively until all the disks have been moved from the starting peg to the destination peg. The number of moves required to solve the puzzle for n disks can be calculated using the formula 2^n - 1. - - - - - - -Here's an implementation of the Tower of Hanoi problem in Java using recursion: - -public class TowerOfHanoi { - public static void main(String[] args) { - int n = 3; // number of disks - char fromRod = 'A'; - char toRod = 'C'; - char auxRod = 'B'; - - System.out.println("Moves to solve Tower of Hanoi problem with " + n + " disks:"); - solveHanoi(n, fromRod, toRod, auxRod); - } - - public static void solveHanoi(int n, char fromRod, char toRod, char auxRod) { - if (n == 1) { - System.out.println("Move disk 1 from rod " + fromRod + " to rod " + toRod); - return; - } - solveHanoi(n - 1, fromRod, auxRod, toRod); - System.out.println("Move disk " + n + " from rod " + fromRod + " to rod " + toRod); - solveHanoi(n - 1, auxRod, toRod, fromRod); - } -} - - ------------------------Explanation------------------------------ - -In this implementation, the solveHanoi method is called recursively to move the disks from one rod to another. The method takes in four parameters: - -n: the number of disks -fromRod: the rod from which the disks are to be moved -toRod: the rod to which the disks are to be moved -auxRod: the auxiliary rod which can be used to move the disks -When the number of disks is 1, the method simply prints the move to be made. Otherwise, the method makes the following three recursive calls: - -Move n-1 disks from fromRod to auxRod using toRod as the auxiliary rod. -Move the nth disk from fromRod to toRod. -Move the n-1 disks from auxRod to toRod using fromRod as the auxiliary rod. -This process is repeated recursively until all the disks have been moved from the starting rod to the destination rod. \ No newline at end of file diff --git a/Recursion/tower_of_hannoi.java b/Recursion/tower_of_hannoi.java new file mode 100644 index 00000000..dd48350e --- /dev/null +++ b/Recursion/tower_of_hannoi.java @@ -0,0 +1,53 @@ +/* + The Tower of Hanoi problem is a classic problem in computer science and mathematics that involves moving a stack of disks from one peg to another peg. The problem consists of three pegs and a set of disks of different sizes that can slide onto any peg. The objective of the puzzle is to move the entire stack to another peg, obeying the following simple rules: + + Only one disk can be moved at a time. + Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or an empty peg. + No disk may be placed on top of a smaller disk. + The Tower of Hanoi problem is often used as an example of recursive problem-solving. The solution to the problem can be divided into three parts: + + Move n-1 disks from the starting peg to the auxiliary peg. + Move the largest disk from the starting peg to the destination peg. + Move the n-1 disks from the auxiliary peg to the destination peg. + This process is repeated recursively until all the disks have been moved from the starting peg to the destination peg. The number of moves required to solve the puzzle for n disks can be calculated using the formula 2^n - 1. + + Here's an implementation of the Tower of Hanoi problem in Java using recursion: + +*/ +public class TowerOfHanoi { + public static void main(String[] args) { + int n = 3; // number of disks + char fromRod = 'A'; + char toRod = 'C'; + char auxRod = 'B'; + + System.out.println("Moves to solve Tower of Hanoi problem with " + n + " disks:"); + solveHanoi(n, fromRod, toRod, auxRod); + } + + public static void solveHanoi(int n, char fromRod, char toRod, char auxRod) { + if (n == 1) { + System.out.println("Move disk 1 from rod " + fromRod + " to rod " + toRod); + return; + } + solveHanoi(n - 1, fromRod, auxRod, toRod); + System.out.println("Move disk " + n + " from rod " + fromRod + " to rod " + toRod); + solveHanoi(n - 1, auxRod, toRod, fromRod); + } +} + + +// -----------------------Explanation------------------------------ + +// In this implementation, the solveHanoi method is called recursively to move the disks from one rod to another. The method takes in four parameters: + +// n: the number of disks +// fromRod: the rod from which the disks are to be moved +// toRod: the rod to which the disks are to be moved +// auxRod: the auxiliary rod which can be used to move the disks +// When the number of disks is 1, the method simply prints the move to be made. Otherwise, the method makes the following three recursive calls: + +// Move n-1 disks from fromRod to auxRod using toRod as the auxiliary rod. +// Move the nth disk from fromRod to toRod. +// Move the n-1 disks from auxRod to toRod using fromRod as the auxiliary rod. +// This process is repeated recursively until all the disks have been moved from the starting rod to the destination rod. \ No newline at end of file From 8e0a4be2ab5db3a23eb9ca07b0bd608576f82bd3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:40:46 +0530 Subject: [PATCH 0413/1894] update description --- Recursion/valid_palindrome_2.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Recursion/valid_palindrome_2.py b/Recursion/valid_palindrome_2.py index c70a9052..1605db99 100644 --- a/Recursion/valid_palindrome_2.py +++ b/Recursion/valid_palindrome_2.py @@ -1,3 +1,15 @@ +''' + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + + Constraints: string.length The string only consists of English letters + + Sample Input : "madame" + Output : True + + Sample Input : "masdasd" + Output : False + +''' class Solution: def subPalindrome(self,s,low,high,count): if(low>high): From 851334aafcb3cf9fb2b0266ffbadd5f51399417c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:41:56 +0530 Subject: [PATCH 0414/1894] update description --- Fast and Slow Pointers/linked_list_find_middle.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Fast and Slow Pointers/linked_list_find_middle.py b/Fast and Slow Pointers/linked_list_find_middle.py index 2a539422..41c6b9d6 100644 --- a/Fast and Slow Pointers/linked_list_find_middle.py +++ b/Fast and Slow Pointers/linked_list_find_middle.py @@ -1,6 +1,4 @@ -# Python 3 program to find the middle of a -# given linked list - +# Finding Midpoint of a LinkedList # Node class class Node: From 1ba18e0ce34f127718d1200855f2e690731a9b1e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Mar 2023 22:42:32 +0530 Subject: [PATCH 0415/1894] uupdate description --- Arrays/array_of_products.go | 58 +++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/Arrays/array_of_products.go b/Arrays/array_of_products.go index 812c8594..8906b66c 100644 --- a/Arrays/array_of_products.go +++ b/Arrays/array_of_products.go @@ -1,35 +1,37 @@ +/** + * Given an array of integers A, find and return the product array of the same size where the ith element of the product array will be equal to the product of all the elements divided by the ith element of the array. + * + * Note: It is always possible to form the product array with integer (32 bit) values. Solve it without using the division operator. + * + * + * Input Format + * + * The only argument given is the integer array A. + * Output Format + * + * Return the product array. + * Constraints + * + * 2 <= length of the array <= 1000 + * 1 <= A[i] <= 10 + * For Example + * + * Input 1: + * A = [1, 2, 3, 4, 5] + * Output 1: + * [120, 60, 40, 30, 24] + * + * Input 2: + * A = [5, 1, 10, 1] + * Output 2: + * [10, 50, 5, 50] + */ + package main import "fmt" -/** - * Given an array of integers A, find and return the product array of the same size where the ith element of the product array will be equal to the product of all the elements divided by the ith element of the array. - * - * Note: It is always possible to form the product array with integer (32 bit) values. Solve it without using the division operator. - * - * - * Input Format - * - * The only argument given is the integer array A. - * Output Format - * - * Return the product array. - * Constraints - * - * 2 <= length of the array <= 1000 - * 1 <= A[i] <= 10 - * For Example - * - * Input 1: - * A = [1, 2, 3, 4, 5] - * Output 1: - * [120, 60, 40, 30, 24] - * - * Input 2: - * A = [5, 1, 10, 1] - * Output 2: - * [10, 50, 5, 50] - */ + func ArrayOfProducts(Arr[]int) { Result := make([]int, len(Arr)) From 257134c10d696891b8ace375a4861ff3e54b248c Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Fri, 10 Mar 2023 14:37:24 +0530 Subject: [PATCH 0416/1894] feat:I have added TOH using C++ and Javascript --- .../Demonstrate Tower of Hanoi Problem in C++ | 37 +++++++++++++++++++ ...trate Tower of Hanoi Problem in Javascript | 27 ++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 Recursion/Demonstrate Tower of Hanoi Problem in C++ create mode 100644 Recursion/Demonstrate Tower of Hanoi Problem in Javascript diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in C++ b/Recursion/Demonstrate Tower of Hanoi Problem in C++ new file mode 100644 index 00000000..f551efbe --- /dev/null +++ b/Recursion/Demonstrate Tower of Hanoi Problem in C++ @@ -0,0 +1,37 @@ +Here's an implementation of the Tower of Hanoi problem in C++: + +#include + +void towerOfHanoi(int numDisks, char fromPeg, char toPeg, char auxPeg) { + if (numDisks == 1) { + std::cout << "Move disk 1 from peg " << fromPeg << " to peg " << toPeg << std::endl; + } else { + towerOfHanoi(numDisks - 1, fromPeg, auxPeg, toPeg); + std::cout << "Move disk " << numDisks << " from peg " << fromPeg << " to peg " << toPeg << std::endl; + towerOfHanoi(numDisks - 1, auxPeg, toPeg, fromPeg); + } +} + +int main() { + towerOfHanoi(3, 'A', 'C', 'B'); + return 0; +} + +This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). +If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. +The main function simply calls towerOfHanoi with the appropriate arguments (in this case, numDisks is 3 and the pegs are labeled A, B, and C). + +When run, the program outputs the following to the console: + +Move disk 1 from peg A to peg C +Move disk 2 from peg A to peg B +Move disk 1 from peg C to peg B +Move disk 3 from peg A to peg C +Move disk 1 from peg B to peg A +Move disk 2 from peg B to peg C +Move disk 1 from peg A to peg C + + +This output shows the sequence of moves that solve the Tower of Hanoi problem for 3 disks. + + diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in Javascript b/Recursion/Demonstrate Tower of Hanoi Problem in Javascript new file mode 100644 index 00000000..7159f341 --- /dev/null +++ b/Recursion/Demonstrate Tower of Hanoi Problem in Javascript @@ -0,0 +1,27 @@ +Here's an implementation of the Tower of Hanoi problem in JavaScript: + +function towerOfHanoi(numDisks, fromPeg, toPeg, auxPeg) { + if (numDisks === 1) { + console.log(`Move disk 1 from peg ${fromPeg} to peg ${toPeg}`); + } else { + towerOfHanoi(numDisks - 1, fromPeg, auxPeg, toPeg); + console.log(`Move disk ${numDisks} from peg ${fromPeg} to peg ${toPeg}`); + towerOfHanoi(numDisks - 1, auxPeg, toPeg, fromPeg); + } +} + +// Example usage: +towerOfHanoi(3, "A", "C", "B"); // Move disk 1 from peg A to peg C, Move disk 2 from peg A to peg B, Move disk 1 from peg C to peg B, Move disk 3 from peg A to peg C, Move disk 1 from peg B to peg A, Move disk 2 from peg B to peg C, Move disk 1 from peg A to peg C + + +This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). +If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. +The function prints out the moves it makes to the console, so running towerOfHanoi(3, "A", "C", "B") would output: + +Move disk 1 from peg A to peg C +Move disk 2 from peg A to peg B +Move disk 1 from peg C to peg B +Move disk 3 from peg A to peg C +Move disk 1 from peg B to peg A +Move disk 2 from peg B to peg C +Move disk 1 from peg A to peg C From 0980d98a5b2e3e0d40fec86897e1285aa6018a9a Mon Sep 17 00:00:00 2001 From: Brian Date: Fri, 10 Mar 2023 08:31:48 -0600 Subject: [PATCH 0417/1894] add c++ valid palindrome, also updated readme --- README.md | 2 +- Strings/is_palindrome.cpp | 49 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 Strings/is_palindrome.cpp diff --git a/README.md b/README.md index 2baeb2c1..f1950eb5 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) diff --git a/Strings/is_palindrome.cpp b/Strings/is_palindrome.cpp new file mode 100644 index 00000000..50b8483a --- /dev/null +++ b/Strings/is_palindrome.cpp @@ -0,0 +1,49 @@ +/* + is_palindrome in c++ + code by Brian Salkas + */ + +#include +// start l and r at the beginning and end of the string +// each time we loop, we incrament l and decrament r +// and check if the 'lth' char of the string is +// equal to the 'rth' char. +// If they are not equal return false +// we continue looping as long as l is less than r +// if the loop completes without returning false, +// then our string is a palindrome and we return true +bool is_palindrome(std::string const& str) { + size_t l = 0, r = str.size() - 1; + while (l < r) { + if (str[l++] != str[r--]) { + return false; + } + } + return true; +} +// this function contains identical logic to the iterative one above +// notice the second parameter "size_t l=0", this is a default argument +// this means if you do not pass a second parameter, l will be assigned to +// zero. on the next line, we assign r to str.size() - 1 - l, +// which means that each time we incrament l we decrament r! +// base case 1: return true if we get to middle without returning false +// base case 2: return false if not palindrome +// recursive case: call function again incramenting l. +bool is_palindrome_rec(std::string const& str, size_t l=0) { + size_t r = str.size() -1- l; + if (r <= l) { // base case 1 + return true; + } + if (str[l] != str[r]) { // base case 2 + return false; + } + return is_palindrome_rec(str, l+1); // recursive case +} + +// driver function with test cases +int main() { + std::cout << "hello: " << (is_palindrome("hello") ?"true" : "false") << '\n'; + std::cout << "racecar: " << (is_palindrome("racecar") ?"true" : "false") << '\n'; + std::cout << "hello: " << (is_palindrome_rec("hello") ?"true" : "false") << '\n'; + std::cout << "racecar: " << (is_palindrome_rec("racecar") ?"true" : "false") << '\n'; +} From 116fafb97b76e2b91ddf0bef43a66fb84cc2c541 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Mar 2023 22:31:36 +0530 Subject: [PATCH 0418/1894] rename file --- ...onstrate Tower of Hanoi Problem in C++ => tower_of_hannoi.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{Demonstrate Tower of Hanoi Problem in C++ => tower_of_hannoi.cpp} (100%) diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in C++ b/Recursion/tower_of_hannoi.cpp similarity index 100% rename from Recursion/Demonstrate Tower of Hanoi Problem in C++ rename to Recursion/tower_of_hannoi.cpp From 7ecfac0e0c03e56a4b1e1f113d4cb71afa49aae1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Mar 2023 22:31:40 +0530 Subject: [PATCH 0419/1894] rename file --- ...te Tower of Hanoi Problem in Javascript => tower_of_hannoi.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{Demonstrate Tower of Hanoi Problem in Javascript => tower_of_hannoi.js} (100%) diff --git a/Recursion/Demonstrate Tower of Hanoi Problem in Javascript b/Recursion/tower_of_hannoi.js similarity index 100% rename from Recursion/Demonstrate Tower of Hanoi Problem in Javascript rename to Recursion/tower_of_hannoi.js From dad68ebbeaf9c1131e1de08c24905d205b0de9eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Mar 2023 22:32:15 +0530 Subject: [PATCH 0420/1894] update description --- Recursion/tower_of_hannoi.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Recursion/tower_of_hannoi.cpp b/Recursion/tower_of_hannoi.cpp index f551efbe..26c50f9e 100644 --- a/Recursion/tower_of_hannoi.cpp +++ b/Recursion/tower_of_hannoi.cpp @@ -1,5 +1,14 @@ -Here's an implementation of the Tower of Hanoi problem in C++: - +/* + Towers of Hanoi puzzle. + Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) + Object of the game is to move all the disks over to Tower 3. + But you cannot place a larger disk onto a smaller disk. + + Approach + 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, + 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, + 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. +*/ #include void towerOfHanoi(int numDisks, char fromPeg, char toPeg, char auxPeg) { From c3550ec1aa8caf84f66e84ffac7fac8bb3132dc0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Mar 2023 22:32:20 +0530 Subject: [PATCH 0421/1894] update description --- Recursion/tower_of_hannoi.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Recursion/tower_of_hannoi.js b/Recursion/tower_of_hannoi.js index 7159f341..882675cb 100644 --- a/Recursion/tower_of_hannoi.js +++ b/Recursion/tower_of_hannoi.js @@ -1,5 +1,14 @@ -Here's an implementation of the Tower of Hanoi problem in JavaScript: +/* + Towers of Hanoi puzzle. + Source(https://en.wikipedia.org/wiki/Tower_of_Hanoi) + Object of the game is to move all the disks over to Tower 3. + But you cannot place a larger disk onto a smaller disk. + Approach + 1 Move the top 􀝊 − 1 disks from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower, + 2 Move the 􀝊􀯧􀯛 disk from 􀜵􀝋􀝑􀝎􀜿􀝁 to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower, + 3 Move the 􀝊 − 1disks from 􀜣􀝑􀝔􀝅􀝈􀝅􀜽􀝎􀝕 tower to 􀜦􀝁􀝏􀝐􀝅􀝊􀜽􀝐􀝅􀝋􀝊 tower. +*/ function towerOfHanoi(numDisks, fromPeg, toPeg, auxPeg) { if (numDisks === 1) { console.log(`Move disk 1 from peg ${fromPeg} to peg ${toPeg}`); From 1cddf9094b78da1c1d02331e3ddf972534d4d000 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Mar 2023 22:33:50 +0530 Subject: [PATCH 0422/1894] update comments --- Recursion/tower_of_hannoi.cpp | 24 ++++++++++++------------ Recursion/tower_of_hannoi.js | 21 ++++++++++----------- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/Recursion/tower_of_hannoi.cpp b/Recursion/tower_of_hannoi.cpp index 26c50f9e..c172f674 100644 --- a/Recursion/tower_of_hannoi.cpp +++ b/Recursion/tower_of_hannoi.cpp @@ -26,21 +26,21 @@ int main() { return 0; } -This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). -If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. -The main function simply calls towerOfHanoi with the appropriate arguments (in this case, numDisks is 3 and the pegs are labeled A, B, and C). +// This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). +// If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. +// The main function simply calls towerOfHanoi with the appropriate arguments (in this case, numDisks is 3 and the pegs are labeled A, B, and C). -When run, the program outputs the following to the console: +// When run, the program outputs the following to the console: -Move disk 1 from peg A to peg C -Move disk 2 from peg A to peg B -Move disk 1 from peg C to peg B -Move disk 3 from peg A to peg C -Move disk 1 from peg B to peg A -Move disk 2 from peg B to peg C -Move disk 1 from peg A to peg C +// Move disk 1 from peg A to peg C +// Move disk 2 from peg A to peg B +// Move disk 1 from peg C to peg B +// Move disk 3 from peg A to peg C +// Move disk 1 from peg B to peg A +// Move disk 2 from peg B to peg C +// Move disk 1 from peg A to peg C -This output shows the sequence of moves that solve the Tower of Hanoi problem for 3 disks. +// This output shows the sequence of moves that solve the Tower of Hanoi problem for 3 disks. diff --git a/Recursion/tower_of_hannoi.js b/Recursion/tower_of_hannoi.js index 882675cb..9ef6f9b5 100644 --- a/Recursion/tower_of_hannoi.js +++ b/Recursion/tower_of_hannoi.js @@ -22,15 +22,14 @@ function towerOfHanoi(numDisks, fromPeg, toPeg, auxPeg) { // Example usage: towerOfHanoi(3, "A", "C", "B"); // Move disk 1 from peg A to peg C, Move disk 2 from peg A to peg B, Move disk 1 from peg C to peg B, Move disk 3 from peg A to peg C, Move disk 1 from peg B to peg A, Move disk 2 from peg B to peg C, Move disk 1 from peg A to peg C +// This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). +// If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. +// The function prints out the moves it makes to the console, so running towerOfHanoi(3, "A", "C", "B") would output: -This implementation uses recursion to solve the problem. The towerOfHanoi function takes four arguments: numDisks (the number of disks to move), fromPeg (the peg the disks start on), toPeg (the peg the disks should end up on), and auxPeg (the auxiliary peg used for moving the disks). -If numDisks is 1, the function simply moves the single disk from fromPeg to toPeg. Otherwise, it first moves numDisks - 1 disks from fromPeg to auxPeg using toPeg as the auxiliary peg. Then it moves the largest remaining disk from fromPeg to toPeg. Finally, it moves the numDisks - 1 disks from auxPeg to toPeg using fromPeg as the auxiliary peg. -The function prints out the moves it makes to the console, so running towerOfHanoi(3, "A", "C", "B") would output: - -Move disk 1 from peg A to peg C -Move disk 2 from peg A to peg B -Move disk 1 from peg C to peg B -Move disk 3 from peg A to peg C -Move disk 1 from peg B to peg A -Move disk 2 from peg B to peg C -Move disk 1 from peg A to peg C +// Move disk 1 from peg A to peg C +// Move disk 2 from peg A to peg B +// Move disk 1 from peg C to peg B +// Move disk 3 from peg A to peg C +// Move disk 1 from peg B to peg A +// Move disk 2 from peg B to peg C +// Move disk 1 from peg A to peg C From 875556968c70e9e4c7455931888bb6db5ad841d8 Mon Sep 17 00:00:00 2001 From: Brian Date: Fri, 10 Mar 2023 12:21:21 -0600 Subject: [PATCH 0423/1894] add recursive and iterative linked list solutions, also added link in readme --- Linked List/remove_kth_node_from_end.py | 93 +++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 Linked List/remove_kth_node_from_end.py diff --git a/Linked List/remove_kth_node_from_end.py b/Linked List/remove_kth_node_from_end.py new file mode 100644 index 00000000..03790c47 --- /dev/null +++ b/Linked List/remove_kth_node_from_end.py @@ -0,0 +1,93 @@ +# PROBLEM TO SOLVE +""" + Remove the Nth node from the end of the linked list + assume input is always valid and that k will be a non-negative number + that is less than the length of the list +""" + +# define node used in linked list +class node: + def __init__(self,v=0,n=None): + self.val = v + self.next = n + +# function to create list of length n, node values start at 1 and incrament +# this is NOT part of the algorithm, just part of the setup +def create_list(n): + if n <= 0: + raise Exception() + head = node(1) + curr = head + for i in range(2,n+1): + next = node(i) + curr.next = next + curr=curr.next + return head +def print_list(head): + while head: + print(head.val) + head = head.next + +# helper function (used in both recursive and iterative) +def __remove_node(prev,curr): + prev.next = curr.next +# recursive function +def recursive(head, n): + # create nested helper function called rec + # this allows us to keep the function signature of recursive clean and consistant with iterative + # in real life the client does not usually care if your function is iterative or recursive + # so you want both functions to have just two arguments when the client calls them + def rec(lag,lead, k): + # move lead up k nodes before we even start moving lag + if k > 0: + k -= 1 + lead = lead.next + else: + if not lead: # base case 1: remove head if lead goes passed last node + return head.next + elif not lead.next: # base case 2: skip kth node if lead is on last node + lag.next = lag.next.next + return head + else: # move both nodes up until lead is at the last node + lead = lead.next + lag = lag.next + return rec(lag,lead,k) # call the recursive case + # if we did not create a helper function, the client would need to call recursive + # with 3 arguments instead of 2 which is confusing. + return rec(head,head,n) + + +# iterative function +def iterative(head,k): + # start lag and lead at head + lag = lead = head + # lead gets a headstart, it moves up k nodes before lag starts moving + for _ in range(k): + lead = lead.next + # if lead made it passed the end, then lag must still be at head + if not lead: + return lag.next + # we want to keep moving both lead and lag by one until lead is at the last node + # keep in mind that we want to stop lag one bofore the node we want to delete. + # this is because need to skip over the kth node from the end + while lead.next: + lead = lead.next + lag = lag.next + # we skip the kth from end node by assiging lag.next to lag.next.next + # pythons built in garbage collection will recognize that the kth node + # is unreachable and will delete it for us, no need to call del! + lag.next = lag.next.next + return head + +# text functions below main +if __name__ == "__main__": + head = create_list(9) + print("before removal") + print_list(head) + print("after removing 2nd from last node iteratively") + rem_head = iterative(head,2) + print_list(rem_head) + head = create_list(9) + print("after removing 3rd from last recursivly") + rem_head = recursive(head,3) + print_list(rem_head) diff --git a/README.md b/README.md index f1950eb5..54265a17 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ The key idea is that the pointers start at the same location, but they move forw - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) -- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) +- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Lin ked%20List/remove_kth_node_from_end.py) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) # Pattern 3: Sliding Window From a92cbbea6c66673a409531d80ee4b1246b849ce3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 22:45:04 +0530 Subject: [PATCH 0424/1894] update description --- Sliding Window/sliding_window_max.java | 3 +++ Sliding Window/sliding_window_max.js | 3 +++ Sliding Window/sliding_window_max.py | 2 ++ 3 files changed, 8 insertions(+) diff --git a/Sliding Window/sliding_window_max.java b/Sliding Window/sliding_window_max.java index 3c46fecb..7951979a 100644 --- a/Sliding Window/sliding_window_max.java +++ b/Sliding Window/sliding_window_max.java @@ -1,3 +1,6 @@ +/* + Given an integer array and a window of size windowSize, find the current maximum value in the window as it slides through the entire array +*/ import java.util.*; public class SlidingWindowMax { diff --git a/Sliding Window/sliding_window_max.js b/Sliding Window/sliding_window_max.js index 23726651..2724177f 100644 --- a/Sliding Window/sliding_window_max.js +++ b/Sliding Window/sliding_window_max.js @@ -1,3 +1,6 @@ +/* + Given an integer array and a window of size windowSize, find the current maximum value in the window as it slides through the entire array +*/ function findMaxSlidingWindow(nums, windowSize) { if (!nums || windowSize <= 0 || nums.length < windowSize) { return []; diff --git a/Sliding Window/sliding_window_max.py b/Sliding Window/sliding_window_max.py index 213345b6..cb3bfa9c 100644 --- a/Sliding Window/sliding_window_max.py +++ b/Sliding Window/sliding_window_max.py @@ -1,3 +1,5 @@ +# Given an integer array and a window of size windowSize, find the current maximum value in the window as it slides through the entire array + from collections import deque def slidingWindowMax(arr,windowSize) -> list[int]: From 5918b6cf607b4f721fdcce27abbf867e3bed3b1b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 22:51:46 +0530 Subject: [PATCH 0425/1894] add even or odd linkedlist --- Linked List/linked_list_even_or_odd.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Linked List/linked_list_even_or_odd.go diff --git a/Linked List/linked_list_even_or_odd.go b/Linked List/linked_list_even_or_odd.go new file mode 100644 index 00000000..33d1223f --- /dev/null +++ b/Linked List/linked_list_even_or_odd.go @@ -0,0 +1,25 @@ +package main +import "fmt" + +// has two fields [data] of type integer and [next] of type *node (holds the memory address of next node) +type node struct { + data int + next *node +} +//has three fields length, head and tail node +type LinkedList struct { + length int + head *node + tail *node +} + +func (ll *LinkedList) IsLengthEven() bool { + current := ll.head + for current != nil && current.next != nil { + current = current.next.next + } + if current != nil { + return false + } + return true +} \ No newline at end of file From c9481241ef20d0e9529dd4d6ea38751888cf1091 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 22:52:35 +0530 Subject: [PATCH 0426/1894] add description --- Linked List/linked_list_even_or_odd.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Linked List/linked_list_even_or_odd.go b/Linked List/linked_list_even_or_odd.go index 33d1223f..06304e9b 100644 --- a/Linked List/linked_list_even_or_odd.go +++ b/Linked List/linked_list_even_or_odd.go @@ -1,3 +1,10 @@ +/* + Check whether the given Linked List length is even or odd? + + Approach: + Use a 2x pointer. Take a pointer that moves at 2x [two nodes at a time]. At the end, if the length is even, + then the pointer will be nil; otherwise it will point to the last node. +*/ package main import "fmt" From 803a3822abf752db0043dc7ff60d6513d0116098 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 22:52:57 +0530 Subject: [PATCH 0427/1894] add time andd space complexity --- Linked List/linked_list_even_or_odd.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Linked List/linked_list_even_or_odd.go b/Linked List/linked_list_even_or_odd.go index 06304e9b..575ab03e 100644 --- a/Linked List/linked_list_even_or_odd.go +++ b/Linked List/linked_list_even_or_odd.go @@ -5,8 +5,8 @@ Use a 2x pointer. Take a pointer that moves at 2x [two nodes at a time]. At the end, if the length is even, then the pointer will be nil; otherwise it will point to the last node. */ +// Time Complexity: O(⌊n/2⌋) ≈O(n). Space Complexity: O(1). package main -import "fmt" // has two fields [data] of type integer and [next] of type *node (holds the memory address of next node) type node struct { From d8dd253359fb6c0fb4eec57e4719837177c7d411 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 23:15:06 +0530 Subject: [PATCH 0428/1894] add delete node --- Linked List/linked_list_delete_node.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Linked List/linked_list_delete_node.go diff --git a/Linked List/linked_list_delete_node.go b/Linked List/linked_list_delete_node.go new file mode 100644 index 00000000..49518360 --- /dev/null +++ b/Linked List/linked_list_delete_node.go @@ -0,0 +1,12 @@ +/* + We are given a pointer to a node (not the tail node) in a singly linked list. Delete that node from the + linked list. +*/ +package main + +func deleteNode(node *ListNode) { + temp = node.next + node.data = node.next.data + node.next = temp.next + temp = nil +} \ No newline at end of file From 4ae8b55ba4f1ccbe8ad8e5b21662019ad0d1cf14 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 23:17:08 +0530 Subject: [PATCH 0429/1894] add approach --- Linked List/linked_list_delete_node.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Linked List/linked_list_delete_node.go b/Linked List/linked_list_delete_node.go index 49518360..fde555f9 100644 --- a/Linked List/linked_list_delete_node.go +++ b/Linked List/linked_list_delete_node.go @@ -4,6 +4,11 @@ */ package main +/* + Approach: + 1. We can move the data from the next node into the current node + 2. Delete the next node. +*/ func deleteNode(node *ListNode) { temp = node.next node.data = node.next.data From 4f1879c1a1ce71c803d58a1b92bbc89e3dcc4a45 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Mar 2023 23:17:44 +0530 Subject: [PATCH 0430/1894] add time and space complexity --- Linked List/linked_list_delete_node.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Linked List/linked_list_delete_node.go b/Linked List/linked_list_delete_node.go index fde555f9..dbceb40d 100644 --- a/Linked List/linked_list_delete_node.go +++ b/Linked List/linked_list_delete_node.go @@ -8,6 +8,7 @@ package main Approach: 1. We can move the data from the next node into the current node 2. Delete the next node. + Time Complexity: O(1). Space Complexity: O(1). */ func deleteNode(node *ListNode) { temp = node.next From ca8667ede2c0e42bd353e1cc0fdb8969a10c8438 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 21:51:49 +0530 Subject: [PATCH 0431/1894] add bucket sort --- sorting/bucket_sort.go | 56 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 sorting/bucket_sort.go diff --git a/sorting/bucket_sort.go b/sorting/bucket_sort.go new file mode 100644 index 00000000..a61f942a --- /dev/null +++ b/sorting/bucket_sort.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" +) + +func InsertionSort(A []int) { + for i := 0; i < len(A); i++ { + temp := A[i] + j := i - 1 + for ; j >= 0 && A[j] > temp; j-- { + A[j+1] = A[j] + } + A[j+1] = temp + } +} + +func BucketSort(A []int, bucketSize int) []int { + var max, min int + for _, n := range A { + if n < min { + min = n + } + if n > max { + max = n + } + } + nBuckets := int(max-min)/bucketSize + 1 + buckets := make([][]int, nBuckets) + for i := 0; i < nBuckets; i++ { + buckets[i] = make([]int, 0) + } + + for _, n := range A { + idx := int(n-min) / bucketSize + buckets[idx] = append(buckets[idx], n) + } + + sorted := make([]int, 0) + for _, bucket := range buckets { + if len(bucket) > 0 { + InsertionSort(bucket) + sorted = append(sorted, bucket...) + } + } + + return sorted +} + +func main() { + A := []int{3, 4, 5, 2, 1} + A = BucketSort(A, 2) + for _, val := range A { + fmt.Println(val) + } +} \ No newline at end of file From 450c829f8e2471d2da2d078aae9efb3a862a738c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 21:53:36 +0530 Subject: [PATCH 0432/1894] add description --- sorting/bucket_sort.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/sorting/bucket_sort.go b/sorting/bucket_sort.go index a61f942a..aa100f3a 100644 --- a/sorting/bucket_sort.go +++ b/sorting/bucket_sort.go @@ -1,3 +1,25 @@ +/* + Bucket sort, or bin sort, is a sorting algorithm that works by distributing + the elements of an array into a number of buckets. Each bucket is then + sorted individually, either using a different sorting algorithm, + or by recursively applying the bucket sorting algorithm. + It is a distribution sort, a generalization of pigeonhole sort that + allows multiple keys per bucket, and is a cousin of + radix sort in the most-to-least significant digit flavor. + Bucket sort can be implemented with comparisons and therefore can also + be considered a comparison sort algorithm. + The computational complexity depends on the algorithm used to sort + each bucket, the number of buckets to use, + and whether the input is uniformly distributed. + + Bucket sort works as follows: + + Set up an array of initially empty "buckets". + Scatter: Go over the original array, putting each object in its bucket. + Sort each non-empty bucket. + Gather: Visit the buckets in order and put all elements back into the original array. +*/ + package main import ( From 1f6c472465edb024d5ea81c6db70daffc33dfec8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 21:56:50 +0530 Subject: [PATCH 0433/1894] add better naming --- sorting/bucket_sort.go | 46 +++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/sorting/bucket_sort.go b/sorting/bucket_sort.go index aa100f3a..0754da79 100644 --- a/sorting/bucket_sort.go +++ b/sorting/bucket_sort.go @@ -1,15 +1,15 @@ /* - Bucket sort, or bin sort, is a sorting algorithm that works by distributing - the elements of an array into a number of buckets. Each bucket is then - sorted individually, either using a different sorting algorithm, - or by recursively applying the bucket sorting algorithm. - It is a distribution sort, a generalization of pigeonhole sort that - allows multiple keys per bucket, and is a cousin of - radix sort in the most-to-least significant digit flavor. - Bucket sort can be implemented with comparisons and therefore can also - be considered a comparison sort algorithm. - The computational complexity depends on the algorithm used to sort - each bucket, the number of buckets to use, + Bucket sort, or bin sort, is a sorting algorithm that works by distributing + the elements of an array into a number of buckets. Each bucket is then + sorted individually, either using a different sorting algorithm, + or by recursively applying the bucket sorting algorithm. + It is a distribution sort, a generalization of pigeonhole sort that + allows multiple keys per bucket, and is a cousin of + radix sort in the most-to-least significant digit flavor. + Bucket sort can be implemented with comparisons and therefore can also + be considered a comparison sort algorithm. + The computational complexity depends on the algorithm used to sort + each bucket, the number of buckets to use, and whether the input is uniformly distributed. Bucket sort works as follows: @@ -26,20 +26,20 @@ import ( "fmt" ) -func InsertionSort(A []int) { - for i := 0; i < len(A); i++ { - temp := A[i] +func InsertionSort(Array []int) { + for i := 0; i < len(Array); i++ { + temp := Array[i] j := i - 1 - for ; j >= 0 && A[j] > temp; j-- { - A[j+1] = A[j] + for ; j >= 0 && Array[j] > temp; j-- { + Array[j+1] = Array[j] } - A[j+1] = temp + Array[j+1] = temp } } -func BucketSort(A []int, bucketSize int) []int { +func BucketSort(Array []int, bucketSize int) []int { var max, min int - for _, n := range A { + for _, n := range Array { if n < min { min = n } @@ -53,7 +53,7 @@ func BucketSort(A []int, bucketSize int) []int { buckets[i] = make([]int, 0) } - for _, n := range A { + for _, n := range Array { idx := int(n-min) / bucketSize buckets[idx] = append(buckets[idx], n) } @@ -70,9 +70,9 @@ func BucketSort(A []int, bucketSize int) []int { } func main() { - A := []int{3, 4, 5, 2, 1} - A = BucketSort(A, 2) - for _, val := range A { + Array := []int{3, 4, 5, 2, 1} + Array = BucketSort(Array, 2) + for _, val := range Array { fmt.Println(val) } } \ No newline at end of file From 17e1e33a20aab979ad40b94f543879172aa371bc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 21:58:56 +0530 Subject: [PATCH 0434/1894] add time and space complexity --- sorting/bucket_sort.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sorting/bucket_sort.go b/sorting/bucket_sort.go index 0754da79..5eb5752f 100644 --- a/sorting/bucket_sort.go +++ b/sorting/bucket_sort.go @@ -19,7 +19,9 @@ Sort each non-empty bucket. Gather: Visit the buckets in order and put all elements back into the original array. */ - +// The average time complexity for Bucket Sort is O(n + k). +// The worst time complexity is O(n²). +// The space complexity for Bucket Sort is O(n+k). package main import ( From 54088b607b141a0a5567e8614021fbd73289dc78 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 21:59:15 +0530 Subject: [PATCH 0435/1894] add source --- sorting/bucket_sort.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sorting/bucket_sort.go b/sorting/bucket_sort.go index 5eb5752f..03a71b12 100644 --- a/sorting/bucket_sort.go +++ b/sorting/bucket_sort.go @@ -18,6 +18,8 @@ Scatter: Go over the original array, putting each object in its bucket. Sort each non-empty bucket. Gather: Visit the buckets in order and put all elements back into the original array. + + Source(https://en.wikipedia.org/wiki/Bucket_sort) */ // The average time complexity for Bucket Sort is O(n + k). // The worst time complexity is O(n²). From 9ce34e56d56c19dc999039f010f237cc5b99f6e7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 22:02:10 +0530 Subject: [PATCH 0436/1894] remove ap and largest number splution --- sorting/check_arithmetic_progression.java | 76 ---------------- sorting/largest_number.java | 102 ---------------------- 2 files changed, 178 deletions(-) delete mode 100644 sorting/check_arithmetic_progression.java delete mode 100644 sorting/largest_number.java diff --git a/sorting/check_arithmetic_progression.java b/sorting/check_arithmetic_progression.java deleted file mode 100644 index 4d0d823b..00000000 --- a/sorting/check_arithmetic_progression.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Given an integer array A of size N. Return 1 if the array can be arranged to form an arithmetic progression, otherwise return 0. - * - * A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. - * - * - * - * Problem Constraints - * 2 <= N <= 105 - * - * -109 <= A[i] <= 109 - * - * - * - * Input Format - * The first and only argument is an integer array A of size N. - * - * - * - * Output Format - * Return 1 if the array can be rearranged to form an arithmetic progression, otherwise return 0. - * - * - * - * Example Input - * Input 1: - * - * A = [3, 5, 1] - * Input 2: - * - * A = [2, 4, 1] - * - * - * Example Output - * Output 1: - * - * 1 - * Output 2: - * - * 0 - * - * - * Example Explanation - * Explanation 1: - * - * We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. - * Explanation 2: - * - * There is no way to reorder the elements to obtain an arithmetic progression. - */ -package Sorting; - -import java.util.Arrays; - -public class CheckArithmeticProgression { - public static void main(String[] args) { - int[] array = {3, 5, 1}; - int res = solve(array); - System.out.println(res); - } - public static int solve(int[] A) { - // O(NLog(N)) time | O(1) space - where N is the length of the array - - Arrays.sort(A); - - int prevDiff = Math.abs(A[0] - A[1]); - for (int i = 2; i < A.length; i++) { - int prevNum = A[i-1]; - int currentNum = A[i]; - - int currentDiff = Math.abs(prevNum - currentNum); - if (prevDiff != currentDiff) return 0; - } - return 1; - } -} diff --git a/sorting/largest_number.java b/sorting/largest_number.java deleted file mode 100644 index 2f7e77f5..00000000 --- a/sorting/largest_number.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Given an array A of non-negative integers, arrange them such that they form the largest number. - * - * Note: The result may be very large, so you need to return a string instead of an integer. - * - * - * - * Problem Constraints - * 1 <= len(A) <= 100000 - * 0 <= A[i] <= 2*109 - * - * - * - * Input Format - * The first argument is an array of integers. - * - * - * - * Output Format - * Return a string representing the largest number. - * - * - * - * Example Input - * Input 1: - * - * A = [3, 30, 34, 5, 9] - * Input 2: - * - * A = [2, 3, 9, 0] - * - * - * Example Output - * Output 1: - * - * "9534330" - * Output 2: - * - * "9320" - * - * - * Example Explanation - * Explanation 1: - * - * Reorder the numbers to [9, 5, 34, 3, 30] to form the largest number. - * Explanation 2: - * - * Reorder the numbers to [9, 3, 2, 0] to form the largest number 9320. - * - * - * Reference : https://leetcode.com/problems/largest-number/solutions/53158/my-java-solution-to-share/ - */ -package Sorting; - -import java.util.Arrays; -import java.util.Comparator; - -public class LargestNumber { - - public static void main(String[] args) { - int[] array = {3, 30, 34, 5, 9}; - String res = solve(array); - System.out.println(res); - } - - public static String solve(int[] array) { - // O(N(Log(N)) time | O(n) space - if (array == null || array.length == 0) return ""; - - int len = array.length; - //1. Convert int array to String array - String[] stringArray = new String[len]; - for (int i = 0; i < len; i++) - stringArray[i] = String.valueOf(array[i]); - - //2. custom comparator to decide which string should come first. - Comparator comparator = new Comparator() { - @Override - public int compare(String o1, String o2) { // Eg: s1 = "9", s2 = "31" - String s1 = o1 + o2; // "931" - String s2 = o2 + o1; // "319" - - return s2.compareTo(s1); // reverse order - } - }; - - //3. Sort Strings according to custom comparator - Arrays.sort(stringArray, comparator); - - // An extreme edge case by leetcode, say you have only a bunch of 0 in your int array - // If, after being sorted, the largest number is `0`, the entire number - // is zero. - if (stringArray[0].charAt(0) == '0') return "0"; - - StringBuilder stringBuilder = new StringBuilder(); - for (String string : stringArray) { - stringBuilder.append(string); - } - - return stringBuilder.toString(); - } -} From eea25bbc867fea722993460b1ad02ea62b6d5d62 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 22:02:16 +0530 Subject: [PATCH 0437/1894] move to arrays --- .../merge_sorted_arrays.py | 0 .../merge_two_sorted_array.cpp | 98 +++++++++---------- 2 files changed, 49 insertions(+), 49 deletions(-) rename sorting/Merge_sorted_arrays.py => Arrays/merge_sorted_arrays.py (100%) rename {sorting => Arrays}/merge_two_sorted_array.cpp (96%) diff --git a/sorting/Merge_sorted_arrays.py b/Arrays/merge_sorted_arrays.py similarity index 100% rename from sorting/Merge_sorted_arrays.py rename to Arrays/merge_sorted_arrays.py diff --git a/sorting/merge_two_sorted_array.cpp b/Arrays/merge_two_sorted_array.cpp similarity index 96% rename from sorting/merge_two_sorted_array.cpp rename to Arrays/merge_two_sorted_array.cpp index bca55e94..0bd6b08a 100644 --- a/sorting/merge_two_sorted_array.cpp +++ b/Arrays/merge_two_sorted_array.cpp @@ -1,49 +1,49 @@ -// Description: -// You are given two integer arrays nums1 and nums2, -// sorted in non-decreasing order, and two integers -// m and n, representing the number of elements in -// nums1 and nums2 respectively. - -// Merge nums1 and nums2 into a single array sorted -// in non-decreasing order. - -// The final sorted array should not be returned by -// the function, but instead be stored inside the -// array nums1. To accommodate this, nums1 has a -// length of m + n, where the first m elements denote -// the elements that should be merged, and the last -// n elements are set to 0 and should be ignored. -// nums2 has a length of n. - -// Sample Input/Output: - -// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 - -// Output: [1,2,2,3,5,6] - -// Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. - -// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1 - -// Time complexity of this code is O(m+n) -// Space complexity is O(1) - -class Solution { -public: - void merge(vector& nums1, int m, vector& nums2, int n) { - int tar = m + n - 1; // size of nums1 - - int i = m - 1; // index of last element of nums1 - - int j = n - 1; // index of last element of nums2 - - while(j >= 0) { // iterate from last - - if( i >= 0 && nums1[i] > nums2[j]) - nums1[tar--] = nums1[i--]; - else - nums1[tar--] = nums2[j--]; - - } - } -}; +// Description: +// You are given two integer arrays nums1 and nums2, +// sorted in non-decreasing order, and two integers +// m and n, representing the number of elements in +// nums1 and nums2 respectively. + +// Merge nums1 and nums2 into a single array sorted +// in non-decreasing order. + +// The final sorted array should not be returned by +// the function, but instead be stored inside the +// array nums1. To accommodate this, nums1 has a +// length of m + n, where the first m elements denote +// the elements that should be merged, and the last +// n elements are set to 0 and should be ignored. +// nums2 has a length of n. + +// Sample Input/Output: + +// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 + +// Output: [1,2,2,3,5,6] + +// Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. + +// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1 + +// Time complexity of this code is O(m+n) +// Space complexity is O(1) + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int tar = m + n - 1; // size of nums1 + + int i = m - 1; // index of last element of nums1 + + int j = n - 1; // index of last element of nums2 + + while(j >= 0) { // iterate from last + + if( i >= 0 && nums1[i] > nums2[j]) + nums1[tar--] = nums1[i--]; + else + nums1[tar--] = nums2[j--]; + + } + } +}; From f3f63e53c816b6917bd30ec29bef83da1b479a9b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 22:03:09 +0530 Subject: [PATCH 0438/1894] remove solution with no explanation --- sorting/noble_integer.java | 84 ----------------------- sorting/tens_digit_sorting.java | 115 -------------------------------- sorting/three_number_sort.java | 64 ------------------ 3 files changed, 263 deletions(-) delete mode 100644 sorting/noble_integer.java delete mode 100644 sorting/tens_digit_sorting.java delete mode 100644 sorting/three_number_sort.java diff --git a/sorting/noble_integer.java b/sorting/noble_integer.java deleted file mode 100644 index ba26c404..00000000 --- a/sorting/noble_integer.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Given an integer array A, find if an integer p exists in the array such that the number of integers greater than p in the array equals p. - * - * - * - * Problem Constraints - * 1 <= |A| <= 2*105 - * -108 <= A[i] <= 108 - * - * - * Input Format - * First and only argument is an integer array A. - * - * - * - * Output Format - * Return 1 if any such integer p is present else, return -1. - * - * - * - * Example Input - * Input 1: - * - * A = [3, 2, 1, 3] - * Input 2: - * - * A = [1, 1, 3, 3] - * - * - * Example Output - * Output 1: - * - * 1 - * Output 2: - * - * -1 - * - * - * Example Explanation - * Explanation 1: - * - * For integer 2, there are 2 greater elements in the array.. - * Explanation 2: - * - * There exist no integer satisfying the required conditions. - */ - -package Sorting; - -import java.util.Arrays; - -public class NobleInteger { - public static void main(String[] args) { - int[] arr = {3, 2, 1, 3}; - int res = solve(arr); - System.out.println(res); - } - public static int solve(int[] array) { - // O(NLog(N) time | O(1) space - int len = array.length - 1; - Arrays.sort(array); - int count = 0; - - if (array[len] == 0) return 1; - for (int i = len - 1; i > -1; i--) { - int currentNum = array[i], - previousNum = array[i + 1]; - if (currentNum != previousNum) count = len - i; - if (count == currentNum) return 1; - } - return -1; - - // O(N^2) time | O(1) space -// for (int previousNum : array) { -// int count = 0; -// for (int currentNum : array) { -// if (currentNum > previousNum) -// count++; -// } -// if (count == previousNum) return 1; -// } -// return -1; - } -} diff --git a/sorting/tens_digit_sorting.java b/sorting/tens_digit_sorting.java deleted file mode 100644 index 4607f6d3..00000000 --- a/sorting/tens_digit_sorting.java +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Tens Digit Sorting - * - * - * Problem Description - * Given an array A of N integers. Sort the array in increasing order of the value at the tens place digit of every number. - * - * If a number has no tens digit, we can assume value to be 0. - * If 2 numbers have same tens digit, in that case number with max value will come first - * Solution should be based on comparator. - * - * - * Problem Constraints - * 1 <= N <= 105 - * - * 1 <= A[i] <= 109 - * - * - * - * Input Format - * First argument A is an array of integers. - * - * - * - * Output Format - * Return the array after sorting - * - * - * - * Example Input - * Input 1: - * A = [15, 11, 7, 19] - * Input 2: - * A = [2, 24, 22, 19] - * - * - * Example Output - * Output 1: - * [7, 19, 15, 11] - * Output 2: - * [2, 19, 24, 22] - * - * - * Example Explanation - * For Input 1: - * The sorted order is [7, 19, 15, 11]. The tens digit of 7 is 0, - * and that of 19, 15 and 11 is 1. - * For Input 2: - * The sorted order is [2, 19, 24, 22]. The tens digit of 2 is 0, - * that of 19 is 1 and that of 22 and 24 is 2. - */ - -package Sorting; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; - -public class TenDigitSorting { - public static void main(String[] args) { - ArrayList array = new ArrayList<>( - Arrays.asList(908, 903, 809, 801, 700, 608)); - - int[] arr = {7, 19, 15, 11}; - - // Using ArrayList - ArrayList res = solve(array); - System.out.println(res); - - // Using Array -// int[] res = solve(arr); -// System.out.println(Arrays.toString(res)); - } - public static ArrayList solve(ArrayList array) { - // O(N(Log(N)) time | O(1) space - Comparator comparator = new Comparator<>() { - @Override - public int compare(Integer val1, Integer val2) { - int num1 = (val1 / 10) % 10; - int num2 = (val2 / 10) % 10; - - if (num1 == num2) return val2.compareTo(val1); - return num1 - num2; - } - }; - - array.sort(comparator); - - return array; - } - - public static int[] solve(int[] array) { - // O(N(Log(N)) time | O(1) space - - Integer[] arr = new Integer[array.length]; - for (int i = 0; i < arr.length; i++) - arr[i] = array[i]; - Comparator comparator = new Comparator<>() { - @Override - public int compare(Integer val1, Integer val2) { - Integer num1 = val1 / 10; - Integer num2 = val2 / 10; - - return num1.compareTo(num2); - } - }; - - Arrays.sort(arr, comparator); - - for (int i = 0; i < arr.length; i++) - array[i] = arr[i]; - - return array; - } -} diff --git a/sorting/three_number_sort.java b/sorting/three_number_sort.java deleted file mode 100644 index 1071a96c..00000000 --- a/sorting/three_number_sort.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Three Number Sort - * - * You're given an array of integers and another array of three distinct integers. The first array is guaranteed to only contain integers that are in the second array, and the second array represents a desired order for the integers in the first array. For example, a second array of [x, y, z] represents a desired order of [x, x, ..., x, y, y, ..., y, z, z, ..., z] in the first array. - * - * Write a function that sorts the first array according to the desired order in the second array. - * - * The function should perform this in place (i.e., it should mutate the input array), and it shouldn't use any auxiliary space (i.e., it should run with constant space: O(1) space). - * - * Note that the desired order won't necessarily be ascending or descending and that the first array won't necessarily contain all three integers found in the second array—it might only contain one or two. - * Sample Input - * - * array = [1, 0, 0, -1, -1, 0, 1, 1] - * order = [0, 1, -1] - * - * Sample Output - * - * [0, 0, 0, 1, 1, 1, -1, -1] - */ - -package Sorting; - -import java.util.Arrays; - -public class ThreeNumberSort { - public static void main(String[] args) { - int[] array = {1, 0, 0, -1, -1, 0, 1, 1}; - int[] order = {0, 1, -1}; - - int[] res = solve(array, order); - System.out.println(Arrays.toString(res)); - } - public static int[] solve(int[] array, int[] order) { - // O(n) time | O(1) space - where n is the length of the array - - int firstValue = order[0]; - int secondValue = order[1]; - - int firstIdx = 0; - int secondIdx = 0; - int thirdIdx = array.length - 1; - - while (secondIdx <= thirdIdx) { - int value = array[secondIdx]; - - if (value == firstValue) { - swap(firstIdx, secondIdx, array); - firstIdx += 1; - secondIdx += 1; - } else if (value == secondValue) - secondIdx++; - else { - swap(secondIdx, thirdIdx, array); - thirdIdx -= 1; - } - } - return array; - } - public static void swap(int i, int j, int[] array) { - int temp = array[j]; - array[j] = array[i]; - array[i] = temp; - } -} From d22cfb1374d426a71b2edc4b62a741cc6f0520bd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Mar 2023 22:03:30 +0530 Subject: [PATCH 0439/1894] remove solution with no explanation --- sorting/dutch_national_flag.java | 87 -------------------------------- 1 file changed, 87 deletions(-) delete mode 100644 sorting/dutch_national_flag.java diff --git a/sorting/dutch_national_flag.java b/sorting/dutch_national_flag.java deleted file mode 100644 index 98e66c4a..00000000 --- a/sorting/dutch_national_flag.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Given an array with N objects colored red, white, or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white, and blue. - * - * We will use the integers 0, 1, and 2 to represent red, white, and blue, respectively. - * - * Note: Using the library sort function is not allowed. - * - * - * - * Problem Constraints - * 1 <= N <= 1000000 - * 0 <= A[i] <= 2 - * - * - * Input Format - * First and only argument of input contains an integer array A. - * - * - * Output Format - * Return an integer array in asked order - * - * - * Example Input - * Input 1 : - * A = [0 1 2 0 1 2] - * Input 2: - * - * A = [0] - * - * - * Example Output - * Output 1: - * [0 0 1 1 2 2] - * Output 2: - * - * [0] - * - * - * Example Explanation - * Explanation 1: - * [0 0 1 1 2 2] is the required order. - */ - -package Sorting; - -import java.util.Arrays; - -public class DutchNationalFlag { - - public static void main(String[] args) { - int[] array = {0, 0, 1, 1, 2, 2}; - - int[] res = solve(array); - System.out.println(Arrays.toString(res)); - } - public static int[] solve(int[] array) { - // O(n) time | O(1) space - where n is the length of the array - - int firstValue = 0; - int secondValue = 1; - - int firstIdx = 0; - int secondIdx = 0; - int thirdIdx = array.length - 1; - - while (secondIdx <= thirdIdx) { - int value = array[secondIdx]; - - if (value == firstValue) { - swap(firstIdx, secondIdx, array); - firstIdx += 1; - secondIdx += 1; - } else if (value == secondValue) - secondIdx++; - else { - swap(secondIdx, thirdIdx, array); - thirdIdx -= 1; - } - } - return array; - } - public static void swap(int i, int j, int[] array) { - int temp = array[j]; - array[j] = array[i]; - array[i] = temp; - } -} From 829b0fd8509fda28ec864357f3d5494c02548bad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:27:44 +0530 Subject: [PATCH 0440/1894] remove solution with no explanation --- Arrays/array_of_products.java | 59 ----------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 Arrays/array_of_products.java diff --git a/Arrays/array_of_products.java b/Arrays/array_of_products.java deleted file mode 100644 index 65bfe30e..00000000 --- a/Arrays/array_of_products.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Given an array of integers A, find and return the product array of the same size where the ith element of the product array will be equal to the product of all the elements divided by the ith element of the array. - * - * Note: It is always possible to form the product array with integer (32 bit) values. Solve it without using the division operator. - * - * - * Input Format - * - * The only argument given is the integer array A. - * Output Format - * - * Return the product array. - * Constraints - * - * 2 <= length of the array <= 1000 - * 1 <= A[i] <= 10 - * For Example - * - * Input 1: - * A = [1, 2, 3, 4, 5] - * Output 1: - * [120, 60, 40, 30, 24] - * - * Input 2: - * A = [5, 1, 10, 1] - * Output 2: - * [10, 50, 5, 50] - */ -package PrefixSum; - -import java.util.Arrays; - -public class ArrayOfProducts { - public static void main(String[] args) { - int[] array = {5, 1, 4, 2}; - int[] ans = solve(array); - System.out.println(Arrays.toString(ans)); - } - public static int[] solve(int[] array) { - // O(n) time | O(n) space - int length = array.length; - int products[] = new int[length]; - - int leftRunningProduct = 1; - for (int i = 0; i < length; i++) { - int currentNum = array[i]; - products[i] = leftRunningProduct; - leftRunningProduct *= currentNum; - } - - int rightRunningProduct = 1; - for (int i = length - 1; i > -1; i--) { - int currentNum = array[i]; - products[i] *= rightRunningProduct; - rightRunningProduct *= currentNum; - } - return products; - } -} From ae4c1b6a07ce6ae3d669a17ef3c4e06fd3822969 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:28:04 +0530 Subject: [PATCH 0441/1894] remove solution with no explanation --- Arrays/alternating_subarrays.java | 101 ------------------------------ 1 file changed, 101 deletions(-) delete mode 100644 Arrays/alternating_subarrays.java diff --git a/Arrays/alternating_subarrays.java b/Arrays/alternating_subarrays.java deleted file mode 100644 index 05b5c8fc..00000000 --- a/Arrays/alternating_subarrays.java +++ /dev/null @@ -1,101 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; - -/** - * You are given an integer array A of length N comprising of 0's & 1's, and an integer B. - * - * You have to tell all the indices of array A that can act as a center of 2 * B + 1 length 0-1 alternating subarray. - * - * A 0-1 alternating array is an array containing only 0's & 1's, and having no adjacent 0's or 1's. For e.g. arrays [0, 1, 0, 1], [1, 0] and [1] are 0-1 alternating, while [1, 1] and [0, 1, 0, 0, 1] are not. - * - * - * - * Problem Constraints - * 1 <= N <= 103 - * - * A[i] equals to 0 or 1. - * - * 0 <= B <= (N - 1) / 2 - * - * - * - * Input Format - * First argument is an integer array A. - * - * Second argument is an integer B. - * - * - * - * Output Format - * Return an integer array containing indices(0-based) in sorted order. If no such index exists, return an empty integer array. - * - * - * - * Example Input - * Input 1: - * - * A = [1, 0, 1, 0, 1] - * B = 1 - * Input 2: - * - * A = [0, 0, 0, 1, 1, 0, 1] - * B = 0 - * - * - * Example Output - * Output 1: - * - * [1, 2, 3] - * Output 2: - * - * [0, 1, 2, 3, 4, 5, 6] - * - * - * Example Explanation - * Explanation 1: - * - * Index 1 acts as a centre of alternating sequence: [A0, A1, A2] - * Index 2 acts as a centre of alternating sequence: [A1, A2, A3] - * Index 3 acts as a centre of alternating sequence: [A2, A3, A4] - * Explanation 2: - * - * Each index in the array acts as the center of alternating sequences of lengths 1. - */ -public class AlternatingSubarrays { - - public static void main(String[] args) { - ArrayList array = new ArrayList<>( - Arrays.asList(1, 0, 1, 0, 1) - ); - int b = 1; - ArrayList ans = solve(array, b); - System.out.println(ans); - - } - public static ArrayList solve(ArrayList array, int b) { - /** - * len = 2*b + 1 --> time --> O(b) - * (b*(n-b)) time | O(n) space - */ - - ArrayList result = new ArrayList<>(); - int n = array.size(); - int len = 2 * b + 1; - int subArrays = n - len + 1; - - for (int i = 0; i < subArrays; i++) { - int prevNum = array.get(i); - int flag = 1; - for (int j = i + 1; j < i + len; j++) { - int currentNum = array.get(j); - if (prevNum == currentNum) { - flag = 0; - break; - } - prevNum = currentNum; - } - if (flag == 1) result.add(i + b); // add center of subarray - } - return result; - } -} From 705173250a482557c698b623d0819fcb785d4797 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:28:24 +0530 Subject: [PATCH 0442/1894] remove solution with no explanation --- Arrays/transpose_matrix.java | 90 ------------------------------------ 1 file changed, 90 deletions(-) delete mode 100644 Arrays/transpose_matrix.java diff --git a/Arrays/transpose_matrix.java b/Arrays/transpose_matrix.java deleted file mode 100644 index 26eb1335..00000000 --- a/Arrays/transpose_matrix.java +++ /dev/null @@ -1,90 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * You are given a matrix A, you have to return another matrix which is the transpose of A. - * - * NOTE: Transpose of a matrix A is defined as - AT[i][j] = A[j][i] ; Where 1 ≤ i ≤ col and 1 ≤ j ≤ row. The tranpose of a matrix switches the element at (i, j)th index to (j, i)th index, and the element at (j, i)th index to (i, j)th index. - * - * - * Problem Constraints - * - * 1 <= A.size() <= 1000 - * - * 1 <= A[i].size() <= 1000 - * - * 1 <= A[i][j] <= 1000 - * - * - * - * Input Format - * - * First argument is a 2D matrix of integers. - * - * - * - * Output Format - * - * You have to return the Transpose of this 2D matrix. - * - * - * - * Example Input - * - * Input 1: - * - * A = [[1, 2, 3],[4, 5, 6],[7, 8, 9]] - * Input 2: - * - * A = [[1, 2],[1, 2],[1, 2]] - * - * - * Example Output - * - * Output 1: - * - * [[1, 4, 7], [2, 5, 8], [3, 6, 9]] - * Output 2: - * - * [[1, 1, 1], [2, 2, 2]] - * - * - * Example Explanation - * - * Explanation 1: - * - * Clearly after converting rows to column and columns to rows of [[1, 2, 3],[4, 5, 6],[7, 8, 9]] - * we will get - * [[1, 4, 7], - * [2, 5, 8], - * [3, 6, 9]]. - */ -public class TransposeMatrix { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, 4, 7)); - array.add(Arrays.asList(2, 5, 8)); - array.add(Arrays.asList(3 ,6, 9)); - - List> result = solve(array); - for (List list: result) { - System.out.println(list); - } - } - public static List> solve(List> array) { -// O(N *M) time | O(N * M) space - List> result = new ArrayList<>(); - int row = array.size(); - int col = array.get(0).size(); - for (int i = 0; i < col; i++) { - List currentRow = new ArrayList<>(); - for (int j = 0; j < row; j++) { - int currentNum = array.get(j).get(i); - currentRow.add(currentNum); - } - result.add(currentRow); - } - return result; - } -} From 2a7456110a06af9a4ab601338cebdaf29b2c1225 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:31:25 +0530 Subject: [PATCH 0443/1894] clean up arrays folder --- Arrays/christmas_trees.java | 88 -------------- Arrays/find_number_of_good_pairs_in_array.cpp | 64 ---------- Arrays/number_with_even_number_of_digits.cpp | 41 ------- Arrays/printing_all_subarrays.cpp | 19 --- Arrays/richest_customer_wealth.cpp | 51 -------- Arrays/rotate_matrix_90degrees.java | 112 ------------------ Arrays/spiral_order_2.java | 107 ----------------- Arrays/stock_trading.java | 57 --------- Arrays/subarray_sums.java | 92 -------------- Arrays/two_sum.js | 19 --- Arrays/unique_occurences.cpp | 36 ------ 11 files changed, 686 deletions(-) delete mode 100644 Arrays/christmas_trees.java delete mode 100644 Arrays/find_number_of_good_pairs_in_array.cpp delete mode 100644 Arrays/number_with_even_number_of_digits.cpp delete mode 100644 Arrays/printing_all_subarrays.cpp delete mode 100644 Arrays/richest_customer_wealth.cpp delete mode 100644 Arrays/rotate_matrix_90degrees.java delete mode 100644 Arrays/spiral_order_2.java delete mode 100644 Arrays/stock_trading.java delete mode 100644 Arrays/subarray_sums.java delete mode 100644 Arrays/two_sum.js delete mode 100644 Arrays/unique_occurences.cpp diff --git a/Arrays/christmas_trees.java b/Arrays/christmas_trees.java deleted file mode 100644 index e1bb8991..00000000 --- a/Arrays/christmas_trees.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * You are given an array A consisting of heights of Christmas trees and an array B of the same size consisting of the cost of each of the trees (Bi is the cost of tree Ai, where 1 ≤ i ≤ size(A)), and you are supposed to choose 3 trees (let's say, indices p, q, and r), such that Ap < Aq < Ar, where p < q < r. - * The cost of these trees is Bp + Bq + Br. - * - * You are to choose 3 trees such that their total cost is minimum. Return that cost. - * - * If it is not possible to choose 3 such trees return -1. - * - * - * - * Problem Constraints - * 1 <= A[i], B[i] <= 109 - * 3 <= size(A) = size(B) <= 3000 - * - * - * - * Input Format - * First argument is an integer array A. - * Second argument is an integer array B. - * - * - * - * Output Format - * Return an integer denoting the minimum cost of choosing 3 trees whose heights are strictly in increasing order, if not possible, -1. - * - * - * - * Example Input - * Input 1: - * - * A = [1, 3, 5] - * B = [1, 2, 3] - * Input 2: - * - * A = [1, 6, 4, 2, 6, 9] - * B = [2, 5, 7, 3, 2, 7] - * - * - * Example Output - * Output 1: - * - * 6 - * Output 2: - * - * 7 - * - * - * Example Explanation - * Explanation 1: - * - * We can choose the trees with indices 1, 2 and 3, and the cost is 1 + 2 + 3 = 6. - * Explanation 2: - * - * We can choose the trees with indices 1, 4 and 5, and the cost is 2 + 3 + 2 = 7. - * This is the minimum cost that we can get. - */ - -package InterviewProblems; - -public class ChristmasTrees { - public static void main(String[] args) { - int[] a = {1, 6, 4, 2, 6, 9}; - int[] b = {2, 5, 7, 3, 2, 7}; - - int ans = solve(a, b); - System.out.println(ans); - } - - public static int solve(int[] a, int[] b) { - // O(N^2) time | O(1) space - int ans = Integer.MAX_VALUE; - int len = a.length; - for (int j = 1; j < len; j++) { - int tempSum = b[j], iVal = Integer.MAX_VALUE, kVal = Integer.MAX_VALUE; - for (int i = j - 1; i > -1; i--) { - if (a[i] < a[j] && b[i] < iVal) iVal = b[i]; - } - for (int k = j + 1; k < len; k++) { - if (a[k] > a[j] && b[k] < kVal) kVal = b[k]; - } - if (iVal != Integer.MAX_VALUE && kVal != Integer.MAX_VALUE) { - tempSum = tempSum + iVal + kVal; - ans = Math.min(tempSum, ans); - } - } - return (ans == Integer.MAX_VALUE) ? -1 : ans; - } -} diff --git a/Arrays/find_number_of_good_pairs_in_array.cpp b/Arrays/find_number_of_good_pairs_in_array.cpp deleted file mode 100644 index 9f740ee2..00000000 --- a/Arrays/find_number_of_good_pairs_in_array.cpp +++ /dev/null @@ -1,64 +0,0 @@ -//Given an array of integers nums,we have to return the number of good pairs. - -//A pair (i, j) is called good if nums[i] == nums[j] and i < j. means our search space will start from i+1 for nums[i] as it is mentioned that i -using namespace std; - -//function to solve this problem -int solve(int arr[],int n){ - int count = 0; - for(int i = 0; i < n; i++){ - for(int j = i + 1; j < n; j++){ - if(arr[i] == arr[j]){ - count++; - } - } - } - return count; -} - - -int main() -{ - int n;//number of elements in array - cin >> n; - int arr[n];//defining array - - //inputs i.e. array elements-- - for(int i = 0; i < n; i++){ - cin >> arr[i]; - } - - //printing ans-- - cout << solve(arr,n); - - - return 0; -} diff --git a/Arrays/number_with_even_number_of_digits.cpp b/Arrays/number_with_even_number_of_digits.cpp deleted file mode 100644 index 5e37926c..00000000 --- a/Arrays/number_with_even_number_of_digits.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - Given an array nums of integers, return how many of them contain an even number of digits. - - Example 1: - Input: nums = [12,345,2,6,7896] - Output: 2 - - Explanation: - 12 contains 2 digits (even number of digits). - 345 contains 3 digits (odd number of digits). - 2 contains 1 digit (odd number of digits). - 6 contains 1 digit (odd number of digits). - 7896 contains 4 digits (even number of digits). - Therefore only 12 and 7896 contain an even number of digits. - - Example 2: - Input: nums = [555,901,482,1771] - Output: 1 - - Explanation: - Only 1771 contains an even number of digits. - - Constraints: - - 1 <= nums.length <= 500 - 1 <= nums[i] <= 105 -*/ - -class Solution { -public: - int findNumbers(vector& nums) { - int count = 0; - for(int num : nums){ - if(num > 9 && num < 100 ) - count++; - else if(num > 999 && num < 10000) - count++; - } - return count; - } -}; \ No newline at end of file diff --git a/Arrays/printing_all_subarrays.cpp b/Arrays/printing_all_subarrays.cpp deleted file mode 100644 index 5fc18e33..00000000 --- a/Arrays/printing_all_subarrays.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Printing all subarrays of an array -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - for(int k = i; k <= j; k++){ - cout << V[k] << ","; - } - cout << endl; - } - } -} \ No newline at end of file diff --git a/Arrays/richest_customer_wealth.cpp b/Arrays/richest_customer_wealth.cpp deleted file mode 100644 index 77d1c467..00000000 --- a/Arrays/richest_customer_wealth.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. - -A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. - - - -Example 1: - -Input: accounts = [[1,2,3],[3,2,1]] -Output: 6 -Explanation: -1st customer has wealth = 1 + 2 + 3 = 6 -2nd customer has wealth = 3 + 2 + 1 = 6 -Both customers are considered the richest with a wealth of 6 each, so return 6. -Example 2: - -Input: accounts = [[1,5],[7,3],[3,5]] -Output: 10 -Explanation: -1st customer has wealth = 6 -2nd customer has wealth = 10 -3rd customer has wealth = 8 -The 2nd customer is the richest with a wealth of 10. -Example 3: - -Input: accounts = [[2,8,7],[7,1,3],[1,9,5]] -Output: 17 - - -Constraints: - -m == accounts.length -n == accounts[i].length -1 <= m, n <= 50 -1 <= accounts[i][j] <= 100 -*/ -class Solution { -public: - int maximumWealth(vector>& accounts) { - int result = 0; - for(int i = 0; i < accounts.size(); i++){ - int temp = 0; - for(int j = 0; j < accounts[i].size(); j++){ - temp += accounts[i][j]; - } - result = max(temp, result); - } - return result; - } -}; \ No newline at end of file diff --git a/Arrays/rotate_matrix_90degrees.java b/Arrays/rotate_matrix_90degrees.java deleted file mode 100644 index 2400dcca..00000000 --- a/Arrays/rotate_matrix_90degrees.java +++ /dev/null @@ -1,112 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * You are given a n x n 2D matrix A representing an image. - * - * Rotate the image by 90 degrees (clockwise). - * - * You need to do this in place. - * - * Note: If you end up using an additional array, you will only receive partial score. - * - * - * - * Problem Constraints - * 1 <= n <= 1000 - * - * - * - * Input Format - * First argument is a 2D matrix A of integers - * - * - * - * Output Format - * Return the 2D rotated matrix. - * - * - * - * Example Input - * Input 1: - * - * [ - * [1, 2], - * [3, 4] - * ] - * Input 2: - * - * [ - * [1] - * ] - * - * - * Example Output - * Output 1: - * - * [ - * [3, 1], - * [4, 2] - * ] - * Output 2: - * - * [ - * [1] - * ] - * - * - * Example Explanation - * Explanation 1: - * - * After rotating the matrix by 90 degree: - * 1 goes to 2, 2 goes to 4 - * 4 goes to 3, 3 goes to 1 - * Explanation 2: - * - * 2D array remains the ssame as there is only element. - */ -public class RotateMatrix90Degrees { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, 3, 4, 2)); - array.add(Arrays.asList(2, 9, 6, -1)); - array.add(Arrays.asList(-3, 12, 8, 7)); - array.add(Arrays.asList(10, -2, 0, -9)); - - System.out.println(array); - solve(array); - System.out.println(array); - } - - public static void solve(List> array) { - // O(N *M) time | O(1) space - int rows = array.size(); - int cols = array.get(0).size(); - Integer temp = 0; - - // transpose - for (int i = 0; i < rows; i++) { - List currentRow = array.get(i); - for (int j = i + 1; j < cols; j++) { - temp = array.get(i).get(j); - array.get(i).set(j, array.get(j).get(i)); - array.get(j).set(i, temp); - } - } - - // reverse - for (int i = 0; i < array.size(); i++) { - List currentRow = array.get(i); - int start = 0; - int end = array.get(i).size() - 1; - int midIdx = (int) end / 2; - while (start <= midIdx) swap(start++, end--, currentRow); - } - } - public static void swap(int i, int j, List array) { - int temp = (int) array.get(i); - array.set(i, array.get(j)); - array.set(j, temp); - } -} diff --git a/Arrays/spiral_order_2.java b/Arrays/spiral_order_2.java deleted file mode 100644 index f7607527..00000000 --- a/Arrays/spiral_order_2.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order and return the generated square matrix. - * - * - * - * Problem Constraints - * 1 <= A <= 1000 - * - * - * - * Input Format - * First and only argument is integer A - * - * - * Output Format - * Return a 2-D matrix which consists of the elements added in spiral order. - * - * - * - * Example Input - * Input 1: - * - * 1 - * Input 2: - * - * 2 - * Input 3: - * - * 5 - * - * - * Example Output - * Output 1: - * - * [ [1] ] - * Output 2: - * - * [ [1, 2], [4, 3] ] - * Output 2: - * - * [ [1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9] ] - * - * - * Example Explanation - * Explanation 1: - * - * Only 1 is to be arranged. - * Explanation 2: - * - * 1 --> 2 - * | - * | - * 4<--- 3 - * Explanation 3: - */ - -package Matrices; - -import java.util.Arrays; - -public class SpiralOrder2 { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - - int size = 5; - int[][] matrix = solve(size); - System.out.println(Arrays.deepToString(matrix)); - - final long endTime = System.currentTimeMillis(); - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - - public static int[][] solve(int size) { - // O(N^2) | time O(N^2) space where N is size. - int[][] matrix = new int[size][size]; - int startRow = 0, - startCol = 0, - endRow = size - 1, - endCol = size - 1; - int currentNum =1; - - while (startRow <= endRow && startCol <= endCol) { - - for (int col = startCol; col <= endCol; col++) - matrix[startRow][col] = currentNum++; - - for (int row = startRow + 1; row <= endRow; row++) - matrix[row][endCol] = currentNum++; - - for (int col = endCol - 1; col >= startCol; col--) - matrix[endRow][col] = currentNum++; - - for (int row = endRow - 1; row > startRow; row--) - matrix[row][startCol] = currentNum++; - - startRow++; - startCol++; - endRow--; - endCol--; - } - return matrix; - } -} diff --git a/Arrays/stock_trading.java b/Arrays/stock_trading.java deleted file mode 100644 index f5ac112f..00000000 --- a/Arrays/stock_trading.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -Best Time to Buy and Sell Stoks 2 - -You are given an integer array prices where prices[i] is the price of a given stock on the ith day. - -On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. - -Find and return the maximum profit you can achieve. - - - -Example 1: - -Input: prices = [7,1,5,3,6,4] -Output: 7 -Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. -Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. -Total profit is 4 + 3 = 7. -Example 2: - -Input: prices = [1,2,3,4,5] -Output: 4 -Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. -Total profit is 4. -Example 3: - -Input: prices = [7,6,4,3,1] -Output: 0 -Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. - - -Constraints: - -1 <= prices.length <= 3 * 104 -0 <= prices[i] <= 104 -*/ -class Solution { - public int maxProfit(int[] prices) { - - int n=prices.length; - int sum=0; - - for(int i=0;i array = new ArrayList<>( - Arrays.asList(2, 9, 5 ) - ); - System.out.println(solve(array)); - } - public static long solve(ArrayList array) { - long totalSubarraysSum = 0; - - // Build prefix array : O(n) time | O(n) space -// ArrayList prefixSum = new ArrayList<>(); -// prefixSum.add(array.get(0)); -// for (int i = 1; i < array.size(); i++) { -// int currentNum = array.get(i); -// int currentPrefixSum = prefixSum.get(i - 1) + currentNum; -// prefixSum.add(currentPrefixSum); -// } - // Sum all subArrays -// for (int i = 0; i < array.size(); i++) { -// for (int j = i; j < array.size(); j++) { -// if (i == 0) totalSubarraysSum += prefixSum.get(j); -// else totalSubarraysSum += prefixSum.get(j) - prefixSum.get(i - 1); -// } -// } - // Without prefix array O(n) time | O(1) space -// long totalSubarraySum = 0; -// for (int i = 0; i < array.size(); i++) { -// int currentSum = 0; -// for (int j = i; j < array.size(); j++) { -// currentSum += array.get(j); -// totalSubarraysSum += currentSum; -// } -// } - - // No.of subarrays = (i + 1) * (N - i); i is starting index. - // Optimal O(n) time | O(1) space solution - for (int i = 0; i < array.size(); i++) { - long currentSubarraySum = (long) (i + 1) * (array.size() - i) * array.get(i); - totalSubarraysSum += currentSubarraySum; - } - return totalSubarraysSum; - } -} diff --git a/Arrays/two_sum.js b/Arrays/two_sum.js deleted file mode 100644 index 07459185..00000000 --- a/Arrays/two_sum.js +++ /dev/null @@ -1,19 +0,0 @@ -//Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. -// https://leetcode.com/problems/two-sum/ - -function twoSum(nums, target) { - for (i = 0; i < nums.length; i++) { - for (j = 0; j < nums.length; j++) { - if (i == j) { - continue; - } - if (nums[i] + nums[j] == target) { - return [i, j]; - break; - } - } - } -} - -// Driver code -console.log(twoSum([3, 2, 4], 6)); diff --git a/Arrays/unique_occurences.cpp b/Arrays/unique_occurences.cpp deleted file mode 100644 index d7bc8f2f..00000000 --- a/Arrays/unique_occurences.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - Given an array of integers arr, write a function that returns true - if and only if the number of occurrences of each value in the array is unique. - Input: arr = [1,2,2,1,1,3] - Output: true - Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. -*/ -#include -using namespace std; -bool check_unique(vector& V, int n){ - map M; - for(int x : V){ - M[x]++; - } - map second_map; - for(auto x : M){ - if(second_map[x.second] > 0) // if same map value encountered then return false - return false; - else - second_map[x.second]++; - } - return true; -} -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - if(check_unique(V, n)) - cout << "True"; - else - cout << "False"; - return 0; -} From 3d63114cd411da1304a0606cb2bafe12d32b269b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:34:42 +0530 Subject: [PATCH 0444/1894] clean up arrays folder --- Arrays/arrays_strings_urlify.cpp | 38 ------- Arrays/bulbs.go | 40 ------- Arrays/container_with_most_water.java | 53 --------- Arrays/count_matches.cpp | 52 --------- Arrays/counting_subarrays.java | 94 ---------------- Arrays/diagonal_sum.java | 71 ------------ Arrays/equilibrium_index.java | 92 --------------- Arrays/even_indices_sum.java | 84 -------------- Arrays/find_majority_element.cpp | 47 -------- Arrays/good_subarrays.java | 88 --------------- Arrays/josephus_problem.java | 58 ---------- Arrays/max_subarray_sum_with_length_k.java | 37 ------ Arrays/maximum_positivity.java | 113 ------------------- Arrays/special_index.java | 124 --------------------- 14 files changed, 991 deletions(-) delete mode 100644 Arrays/arrays_strings_urlify.cpp delete mode 100644 Arrays/bulbs.go delete mode 100644 Arrays/container_with_most_water.java delete mode 100644 Arrays/count_matches.cpp delete mode 100644 Arrays/counting_subarrays.java delete mode 100644 Arrays/diagonal_sum.java delete mode 100644 Arrays/equilibrium_index.java delete mode 100644 Arrays/even_indices_sum.java delete mode 100644 Arrays/find_majority_element.cpp delete mode 100644 Arrays/good_subarrays.java delete mode 100644 Arrays/josephus_problem.java delete mode 100644 Arrays/max_subarray_sum_with_length_k.java delete mode 100644 Arrays/maximum_positivity.java delete mode 100644 Arrays/special_index.java diff --git a/Arrays/arrays_strings_urlify.cpp b/Arrays/arrays_strings_urlify.cpp deleted file mode 100644 index c2a66bbe..00000000 --- a/Arrays/arrays_strings_urlify.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Implement an algorithm to replace all spaces with %20. -// Sample Input : Mr Ashish Lala -// Output: Mr%20Ashish%20Lala -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -void urlify(string s, int length){ - int space_count = 0; - for(int i = 0; i < length; i++){ - if(s[i] == ' '){ - space_count++; - } - } - int index = length + (space_count * 3); - int new_length = index; - for(int i = length - 1; i >= 0; i--){ - if(s[i] == ' '){ - s[index - 1] = '0'; - s[index - 2] = '2'; - s[index - 3] = '%'; - index = index - 3; - } - else{ - s[index - 1] = s[i]; - index--; - } - } - for(int i = index; i < new_length; i++){ - cout << s[i]; - } - -} -int main(){ - string s = "Mr John Smith "; - int length = 13; - urlify(s, 13); - return 0; -} \ No newline at end of file diff --git a/Arrays/bulbs.go b/Arrays/bulbs.go deleted file mode 100644 index 7abebd0f..00000000 --- a/Arrays/bulbs.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - N light bulbs are connected by a wire. - Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. - Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs. - You can press the same switch multiple times. - Note : 0 represents the bulb is off and 1 represents the bulb is on. - - Input: A = [0 1 0 1] - Output: 4 -*/ -package main - -import "fmt" - -func FindMinSwitch(Arr []int) int { - cost := 0 - for i := 0; i < len(Arr); i++ { - if cost & 1 != 1 { - } else { - Arr[i] = 1 - Arr[i] - } - if Arr[i] & 1 == 1 { - continue - } else { - cost += 1 - } - } - return cost -} - -func main() { - Arr := []int{1, 0, 1, 0} - fmt.Println("-->",FindMinSwitch(Arr)) - Arr = []int{0, 1, 0, 1} - fmt.Println("-->",FindMinSwitch(Arr)) - Arr = []int{1, 1, 1, 1} - fmt.Println("-->",FindMinSwitch(Arr)) - Arr = []int{1, 0, 1, 0, 1, 0, 1, 0, 0} - fmt.Println("-->",FindMinSwitch(Arr)) -} \ No newline at end of file diff --git a/Arrays/container_with_most_water.java b/Arrays/container_with_most_water.java deleted file mode 100644 index fa6e57b5..00000000 --- a/Arrays/container_with_most_water.java +++ /dev/null @@ -1,53 +0,0 @@ -/*You are given an integer array height of length n. - There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). - -Find two lines that together with the x-axis form a container, such that the container contains the most water. - -Return the maximum amount of water a container can store. -Example 1: - - -Input: height = [1,8,6,2,5,4,8,3,7] -Output: 49 -Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. - In this case, the max area of water the container can contain is 49. - - -Example 2: - -Input: height = [1,1] -Output: 1 - - -Constraints: - -n == height.length -2 <= n <= 105 -0 <= height[i] <= 104 -*/ - -class Solution { - public int maxArea(int[] height) { - int left=0,right=height.length-1; - int maxArea=Integer.MIN_VALUE; - while(left<=right) - { - int minLine=Math.min(height[left],height[right]); - maxArea=Math.max(maxArea,minLine*(right-left)); - if(height[left] < height[right]) - left++; - else - right--; - - } - return maxArea; - - } -} -class ContainerWithMostWater { - public static void main(String[] args) { - Solution s=new Solution(); - int height[] = {1,8,6,2,5,4,8,3,7}; - System.out.println(s.maxArea(height)); - } -} \ No newline at end of file diff --git a/Arrays/count_matches.cpp b/Arrays/count_matches.cpp deleted file mode 100644 index 1ede90b7..00000000 --- a/Arrays/count_matches.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* -You are given an integer n, the number of teams in a tournament that has strange rules: - -If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. -If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. -Return the number of matches played in the tournament until a winner is decided. - - - -Example 1: - -Input: n = 7 -Output: 6 -Explanation: Details of the tournament: -- 1st Round: Teams = 7, Matches = 3, and 4 teams advance. -- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. -- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. -Total number of matches = 3 + 2 + 1 = 6. -Example 2: - -Input: n = 14 -Output: 13 -Explanation: Details of the tournament: -- 1st Round: Teams = 14, Matches = 7, and 7 teams advance. -- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. -- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. -- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. -Total number of matches = 7 + 3 + 2 + 1 = 13. - - -Constraints: - -1 <= n <= 200 -*/ -class Solution { -public: - int numberOfMatches(int n) { - int res = 0; - while(n > 1){ - if(n % 2 == 0){ - n = n / 2; - res += n; - } - if(n % 2 == 1){ - n = n / 2; - res += n; - n++; - } - } - return res; - } -}; \ No newline at end of file diff --git a/Arrays/counting_subarrays.java b/Arrays/counting_subarrays.java deleted file mode 100644 index fbd442c3..00000000 --- a/Arrays/counting_subarrays.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Given an array A of N non-negative numbers and a non-negative number B, - * you need to find the number of subarrays in A with a sum less than B. - * We may assume that there is no overflow. - * - * - * - * Problem Constraints - * 1 <= N <= 103 - * - * 1 <= A[i] <= 1000 - * - * 1 <= B <= 107 - * - * - * - * Input Format - * First argument is an integer array A. - * - * Second argument is an integer B. - * - * - * - * Output Format - * Return an integer denoting the number of subarrays in A having sum less than B. - * - * - * - * Example Input - * Input 1: - * - * A = [2, 5, 6] - * B = 10 - * Input 2: - * - * A = [1, 11, 2, 3, 15] - * B = 10 - * - * - * Example Output - * Output 1: - * - * 4 - * Output 2: - * - * 4 - * - * - * Example Explanation - * Explanation 1: - * - * The subarrays with sum less than B are {2}, {5}, {6} and {2, 5}, - * Explanation 2: - * - * The subarrays with sum less than B are {1}, {2}, {3} and {2, 3} - */ -public class CountingSubArrays { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long endTime = System.currentTimeMillis(); - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - - int[] array = {1, 11, 2, 3, 15}; - int b = 10; - int ans = solve(array, b); - System.out.println(ans); - - - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - public static int solve(int[] array, int b) { - // O(n^2) time | O(n) space - int ans = 0; - int len = array.length; - int[] prefixSum = new int[len]; - prefixSum[0] = array[0]; - - for (int i = 1; i < len; i++) prefixSum[i] = prefixSum[i - 1] + array[i]; - - for(int i = 0; i < len; i++) { - for (int j = i; j < len; j++) { - int currentSubArraySum = prefixSum[j]; - if (i > 0) currentSubArraySum -= prefixSum[i - 1]; - - if (currentSubArraySum < b) ans++; - } - } - return ans; - } - -} diff --git a/Arrays/diagonal_sum.java b/Arrays/diagonal_sum.java deleted file mode 100644 index 8826cd91..00000000 --- a/Arrays/diagonal_sum.java +++ /dev/null @@ -1,71 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * You are given a N X N integer matrix. You have to find the sum of all the main diagonal elements of A. - * - * Main diagonal of a matrix A is a collection of elements A[i, j] such that i = j. - * - * - * Problem Constraints - * 1 <= N <= 103 - * - * -1000 <= A[i][j] <= 1000 - * - * - * - * Input Format - * There are 1 lines in the input. First 2 integers R, C are the number of rows and columns. Then R * C integers follow corresponding to the rowwise numbers in the 2D array A. - * - * - * - * Output Format - * Return an integer denoting the sum of main diagonal elements. - * - * - * - * Example Input - * Input 1: - * - * 3 3 1 -2 -3 -4 5 -6 -7 -8 9 - * Input 2: - * - * 2 2 3 2 2 3 - * - * - * Example Output - * Output 1: - * - * 15 - * Output 2: - * - * 6 - * - * - * Example Explanation - * Explanation 1: - * - * A[1][1] + A[2][2] + A[3][3] = 1 + 5 + 9 = 15 - * Explanation 2: - * - * A[1][1] + A[2][2] = 3 + 3 = 6 - */ -public class DiagonalSum { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, -2, -3)); - array.add(Arrays.asList(-4, 5, -6)); - array.add(Arrays.asList(-7 ,-8, 9)); - - System.out.println(solve(array)); - } - public static int solve(final List> A) { - // O(row) time | O(1) space - int ans = 0; - for (int i = 0; i < A.size(); i++) { - ans += A.get(i).get(i); - } - return ans; - } -} diff --git a/Arrays/equilibrium_index.java b/Arrays/equilibrium_index.java deleted file mode 100644 index 226dccad..00000000 --- a/Arrays/equilibrium_index.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * You are given an array A of integers of size N. - * - * Your task is to find the equilibrium index of the given array - * - * The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. - * - * NOTE: - * - * Array indexing starts from 0. - * If there is no equilibrium index then return -1. - * If there are more than one equilibrium indexes then return the minimum index. - * - * - * - * Problem Constraints - * 1 <= N <= 105 - * -105 <= A[i] <= 105 - * - * - * Input Format - * First arugment is an array A . - * - * - * Output Format - * Return the equilibrium index of the given array. If no such index is found then return -1. - * - * - * Example Input - * Input 1: - * A=[-7, 1, 5, 2, -4, 3, 0] - * Input 2: - * - * A=[1,2,3] - * - * - * Example Output - * Output 1: - * 3 - * Output 2: - * - * -1 - * - * - * Example Explanation - * Explanation 1: - * 3 is an equilibrium index, because: - * A[0] + A[1] + A[2] = A[4] + A[5] + A[6] - * Explanation 1: - * - * There is no such index. - */ - -package InterviewProblems; - -import java.util.stream.IntStream; - -public class EquilibriumIndex { - public static void main(String[] args) { - int[] arr = {-7, 1, 5, 2, -4, 3, 0}; - int ans = solve(arr); - System.out.println(ans); - } - public static int solve(int[] arr) { - // O(N) | O(1) space - int len = arr.length; - int rightSum = IntStream.of(arr).sum(); - int leftSum = 0; - for (int i = 0; i < len; i++) { - int currentNum = arr[i]; - rightSum -= currentNum; - if (leftSum == rightSum) return i; - leftSum += currentNum; - - } - // Without prefix sum - // Using Prefix sum | O(N) time | O(N) space - -// int len = arr.length; -// int[] prefixSum = new int[len]; -// prefixSum[0] = arr[0]; -// for (int i = 1; i < len; i++) -// prefixSum[i] = prefixSum[i-1] + arr[i]; - - // find equilibrium index -// if (prefixSum[len - 1] - prefixSum[0] == 0) return 0; -// for (int i = 1; i < len; i++) { -// if (prefixSum[i - 1] == prefixSum[ len - 1] - prefixSum[i]) return i; -// } - return -1; - } -} diff --git a/Arrays/even_indices_sum.java b/Arrays/even_indices_sum.java deleted file mode 100644 index 40c11ecd..00000000 --- a/Arrays/even_indices_sum.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * You are given an array A of length N and Q queries given by the 2D array B of size Q*2. Each query consists of two integers B[i][0] and B[i][1]. - * For every query, the task is to calculate the sum of all even indices in the range A[B[i][0]…B[i][1]]. - * - * Note : Use 0-based indexing - * - * - * Problem Constraints - * 1 <= N <= 105 - * 1 <= Q <= 105 - * 1 <= A[i] <= 100 - * 0 <= B[i][0] <= B[i][1] < N - * - * - * Input Format - * First argument A is an array of integers. - * Second argument B is a 2D array of integers. - * - * - * Output Format - * Return an array of integers. - * - * - * Example Input - * Input 1: - * A = [1, 2, 3, 4, 5] - * B = [ [0,2] - * [1,4] ] - * Input 2: - * A = [2, 1, 8, 3, 9] - * B = [ [0,3] - * [2,4] ] - * - * - * Example Output - * Output 1: - * [4, 8] - * Output 2: - * [10, 17] - * - * - * Example Explanation - * For Input 1: - * The subarray for the first query is [1, 2, 3] whose sum of even indices is 4. - * The subarray for the second query is [2, 3, 4, 5] whose sum of even indices is 8. - * For Input 2: - * The subarray for the first query is [2, 1, 8, 3] whose sum of even indices is 10. - * The subarray for the second query is [8, 3, 9] whose sum of even indices is 17. - */ -package InterviewProblems; - -import java.util.Arrays; - -public class evenIndicesSum { - public static void main(String[] args) { - int[] arr = {2, 1, 8, 3, 9}; - int[][] b = { {0, 3}, {2, 4}}; - int[] ans = solve(arr, b); - System.out.println(Arrays.toString(ans)); - } - public static int[] solve(int[] arr, int[][] b) { - // (Q*N) time | (N) space where Q is no.of queries and N is length of arr. - int len = arr.length; - int[] evenPrefixSum = new int[len]; - int[] ans = new int[b.length]; - - //even prefix - evenPrefixSum[0] = arr[0]; - for (int i = 1; i < len; i++) { - int currentNum = arr[i]; - evenPrefixSum[i] = i % 2 == 0 ? - evenPrefixSum[i - 1] + - currentNum : evenPrefixSum[i - 1]; - } - for (int i = 0; i < b.length; i++) { - int[] currentQuery = b[i]; - int startIdx = currentQuery[0]; - int endIdx = currentQuery[1]; - ans[i] = startIdx == 0 ? evenPrefixSum[endIdx] : - evenPrefixSum[endIdx] - evenPrefixSum[startIdx - 1]; - } - return ans; - } -} diff --git a/Arrays/find_majority_element.cpp b/Arrays/find_majority_element.cpp deleted file mode 100644 index 561a2daa..00000000 --- a/Arrays/find_majority_element.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -Given an array nums of size n, return the majority element. - -The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. - - - -Example 1: - -Input: nums = [3,2,3] -Output: 3 -Example 2: - -Input: nums = [2,2,1,1,1,2,2] -Output: 2 - - -Constraints: - -n == nums.length -1 <= n <= 5 * 104 --109 <= nums[i] <= 109 - - -Follow-up: Could you solve the problem in linear time and in O(1) space? -*/ - -//approach---- -//here we make a map which maintain the frequency of each array element while traversing through the element. -//and also check the frequency at the same time..if frequency(occurence) of any element is greater than (n/2) at anytime we will return that element. -// suppose if no such element exist return simply -1. - -// Find Majority Element in C++ - -class Solution { -public: - int majorityElement(vector& nums) { - - unordered_mapmp; - for(int i : nums){ - if(++mp[i] > nums.size() / 2) { - return i; - } - } - return -1; - } -}; diff --git a/Arrays/good_subarrays.java b/Arrays/good_subarrays.java deleted file mode 100644 index 44baf980..00000000 --- a/Arrays/good_subarrays.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Given an array of integers A, a subarray of an array is said to be good if it fulfills any one of the criteria: - * 1. Length of the subarray is be even, and the sum of all the elements of the subarray must be less than B. - * 2. Length of the subarray is be odd, and the sum of all the elements of the subarray must be greater than B. - * Your task is to find the count of good subarrays in A. - * - * - * Problem Constraints - * 1 <= len(A) <= 103 - * 1 <= A[i] <= 103 - * 1 <= B <= 107 - * - * - * Input Format - * The first argument given is the integer array A. - * The second argument given is an integer B. - * - * - * Output Format - * Return the count of good subarrays in A. - * - * - * Example Input - * Input 1: - * A = [1, 2, 3, 4, 5] - * B = 4 - * Input 2: - * - * A = [13, 16, 16, 15, 9, 16, 2, 7, 6, 17, 3, 9] - * B = 65 - * - * - * Example Output - * Output 1: - * 6 - * Output 2: - * - * 36 - * - * - * Example Explanation - * Explanation 1: - * Even length good subarrays = {1, 2} - * Odd length good subarrays = {1, 2, 3}, {1, 2, 3, 4, 5}, {2, 3, 4}, {3, 4, 5}, {5} - */ - -public class GoodSubArrays { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - int[] array = {13, 16, 16, 15, 9, 16, 2, 7, 6, 17, 3, 9}; - int b = 65; - int ans = solve(array, b); - System.out.println(ans); - final long endTime = System.currentTimeMillis(); - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - public static int solve(int[] array, int b) { - // O(n^2) time | O(n) space - int len = array.length; - int[] prefixArray = new int[len]; - int ans = 0; - - prefixArray[0] = array[0]; - for (int i = 1; i < len; i++) { // O(n) time | O(n) space for prefix array - int currentNum = array[i]; - prefixArray[i] = prefixArray[i - 1] + currentNum; - } - - for (int i = 0; i < len; i++) { - for (int j = i; j < len; j++) { - int currentSubArraySize = j - i + 1; - int currentSubArraySum; - - if (i == 0) currentSubArraySum = prefixArray[j]; - else currentSubArraySum = prefixArray[j] - prefixArray[i - 1]; - - if (currentSubArraySize % 2 == 0 && currentSubArraySum < b) ans += 1; //for even - if (currentSubArraySize % 2 > 0 && currentSubArraySum > b) ans += 1; //for odd - - } - } - return ans; - } -} diff --git a/Arrays/josephus_problem.java b/Arrays/josephus_problem.java deleted file mode 100644 index cbd808c6..00000000 --- a/Arrays/josephus_problem.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * There are A people standing in a circle. Person 1 kills their immediate clockwise neighbour and pass the knife to the next person standing in circle. This process continues till there is only 1 person remaining. Find the last person standing in the circle. - * - * - * Problem Constraints - * 1 <= A <= 105 - * - * - * Input Format - * First argument A is an integer. - * - * - * Output Format - * Return an integer. - * - * - * Example Input - * Input 1: - * A = 4 - * Input 2: - * A = 5 - * - * - * Example Output - * Output 1: - * 1 - * Output 2: - * 3 - * - * - * Example Explanation - * For Input 1: - * Firstly, the person at position 2 is killed, then the person at position 4 is killed, - * then the person at position 3 is killed. So the person at position 1 survives. - * For Input 2: - * - * Firstly, the person at position 2 is killed, then the person at position 4 is killed, - * then the person at position 1 is killed. Finally, the person at position 5 is killed. - * So the person at position 3 survives. - */ - -package InterviewProblems; - -public class JosephusProblem { - public static void main(String[] args) { - int numOfPeople = 5; - int ans = solve(numOfPeople); - System.out.println(ans); - } - public static int solve(int numOfPeople) { - // O(Log(N)) time | O(1) space - int num = (int) (Math.log (numOfPeople) / Math.log(2)); - - int kills = numOfPeople - (int) Math.pow(2, num); - - return (2 * kills) + 1; - } -} diff --git a/Arrays/max_subarray_sum_with_length_k.java b/Arrays/max_subarray_sum_with_length_k.java deleted file mode 100644 index 1f55299d..00000000 --- a/Arrays/max_subarray_sum_with_length_k.java +++ /dev/null @@ -1,37 +0,0 @@ -package SlidingWindow; - -public class MaxSubarraySumWithLengthK { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - - int[] array = {-3, 4, -2, 5, 3, -2, 8, 2, -1, 4}; - int targetLength = 5; - int ans = solve(array, targetLength); - System.out.println(ans); - - final long endTime = System.currentTimeMillis(); - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - public static int solve(int[] array, int targetLength) { - // O(n) time | O(1) space - int maxSubarraySum = 0; - int currentSum = 0; - int length = array.length; - - for (int i = 0; i < targetLength; i++) - currentSum += array[i]; - - int startIdx = 1; - int endIdx = targetLength; - - while (endIdx < length) { - currentSum = currentSum + array[endIdx++] - array[startIdx++ - 1]; - maxSubarraySum = Math.max (maxSubarraySum, currentSum); - } - return maxSubarraySum; - } -} diff --git a/Arrays/maximum_positivity.java b/Arrays/maximum_positivity.java deleted file mode 100644 index 2328a8c4..00000000 --- a/Arrays/maximum_positivity.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Given an array of integers A, of size N. - * - * Return the maximum size subarray of A having only non-negative elements. If there are more than one such subarray, return the one having the smallest starting index in A. - * - * NOTE: It is guaranteed that an answer always exists. - * - * - * - * Problem Constraints - * 1 <= N <= 105 - * - * -109 <= A[i] <= 109 - * - * - * - * Input Format - * The first and only argument given is the integer array A. - * - * - * - * Output Format - * Return maximum size subarray of A having only non-negative elements. If there are more than one such subarrays, return the one having earliest starting index in A. - * - * - * - * Example Input - * Input 1: - * - * A = [5, 6, -1, 7, 8] - * Input 2: - * - * A = [1, 2, 3, 4, 5, 6] - * - * - * Example Output - * Output 1: - * - * [5, 6] - * Output 2: - * - * [1, 2, 3, 4, 5, 6] - * - * - * Example Explanation - * Explanation 1: - * - * There are two subarrays of size 2 having only non-negative elements. - * 1. [5, 6] starting point = 0 - * 2. [7, 8] starting point = 3 - * As starting point of 1 is smaller, return [5, 6] - * Explanation 2: - * - * There is only one subarray of size 6 having only non-negative elements: - * [1, 2, 3, 4, 5, 6] - */ -package InterviewProblems; - -import java.util.Arrays; - -public class MaximumPositivity { - - public static void main(String[] args) { -// int[] array = {3341620, -7399236, 5207903, -1729033, 7603748, -3283659, 4646901, 9983066, -1239862, -2196498}; - int[] array = {9, 3, -2, 11, 1, 2}; -// int[] array = {1, 2, 3, 4, 5}; - int[] ans = solve(array); - System.out.println(Arrays.toString(ans)); - } - - public static int[] solve(int[] array) { - // O(N) time | O(1) space - int size = 0, leftIdx = 0, rightIdx = 0, len = array.length; - for (int currentLeftIdx = -1, currentRightIdx = 0; currentRightIdx < len; currentRightIdx++) { - int currentRightNum = array[currentRightIdx]; - if (currentRightNum > -1) { - if (size < currentRightIdx - currentLeftIdx) { - size = currentRightIdx - currentLeftIdx; - leftIdx = currentLeftIdx; - rightIdx = currentRightIdx; - } - } else currentLeftIdx = currentRightIdx; - } - return Arrays.copyOfRange(array, leftIdx + 1, rightIdx + 1); - } - - - public static int[] solveUsingBruteForce(int[] A) { - // O(N^2) time | O(1) space - int maxLen = 0; - int startIdx = 0; - int currentLen = 0; -// int endIdx = 0; - for (int i = 0; i < A.length; i++) { - currentLen = 0; - int currentNum = A[i]; - int j = i; - if (currentNum > -1) { - while (j < A.length && A[j] > -1) { - j++; - currentLen++; - } - if (currentLen > maxLen) { - maxLen = currentLen; - startIdx = i; -// endIdx = j; - } - } - i = j; - } - return Arrays.copyOfRange(A, startIdx, startIdx + maxLen); - } -} diff --git a/Arrays/special_index.java b/Arrays/special_index.java deleted file mode 100644 index e53507c6..00000000 --- a/Arrays/special_index.java +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Given an array, arr[] of size N, the task is to find the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. - * - * - * - * Problem Constraints - * 1 <= n <= 105 - * -105 <= A[i] <= 105 - * - * - * Input Format - * First argument contains an array A of integers of size N - * - * - * Output Format - * Return the count of array indices such that removing an element from these indices makes the sum of even-indexed and odd-indexed array elements equal. - * - * - * - * Example Input - * Input 1: - * A=[2, 1, 6, 4] - * Input 2: - * - * A=[1, 1, 1] - * - * - * Example Output - * Output 1: - * 1 - * Output 2: - * - * 3 - * - * - * Example Explanation - * Explanation 1: - * Removing arr[1] from the array modifies arr[] to { 2, 6, 4 } such that, arr[0] + arr[2] = arr[1]. - * Therefore, the required output is 1. - * Explanation 2: - * - * Removing arr[0] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] - * Removing arr[1] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] - * Removing arr[2] from the given array modifies arr[] to { 1, 1 } such that arr[0] = arr[1] - * Therefore, the required output is 3. - */ - -package InterviewProblems; - -public class SpecialIndex { - public static void main(String[] args) { - int a[] = {1, 1, 1}; - int ans = solve(a); - System.out.println(ans); - } - public static int solve(int[] arr) { - // O(N) time | O(1) space - - // Without using extra space - int len = arr.length; - if (len == 1) return 1; - if (len == 2) return 0; - - int totalEvenSum = 0; - int totalOddSum = 0; - for (int i = 0; i < len; i++) { - if (i % 2 == 0) totalEvenSum += arr[i]; - else totalOddSum += arr[i]; - } - - int prevEvenSum = 0; - int prevOddSum = 0; - int currentEvenSum = 0; - int currentOldSum = 0; - int temp1; - int temp2; - int ans = 0; - - for (int i = 0; i < len; i++) { - - if (i % 2 == 0) currentEvenSum = prevEvenSum + arr[i]; - else currentOldSum = prevOddSum + arr[i]; - - temp1 = prevEvenSum + (totalOddSum - currentOldSum); - temp2 = prevOddSum + (totalEvenSum - currentEvenSum); - if (temp1 == temp2) ans++; - - prevEvenSum = currentEvenSum; - prevOddSum = currentOldSum; - - } - return ans; - } - // Using Prefix Sum -// // even prefix sum | O(N) time -// int[] evenPrefixSum = new int[len]; -// evenPrefixSum[0] = arr[0]; -// -// for (int i = 1; i < len; i++) { -// int currentNum = arr[i]; -// evenPrefixSum[i] = i % 2 != 0 ? evenPrefixSum[i-1] : evenPrefixSum[i-1] + currentNum; -// } -// -// // odd prefix sum | O(N) time -// int[] oddPrefixSum = new int[len]; -// oddPrefixSum[0] = 0; -// -// for (int i = 1; i < len; i++) { -// int currentNum = arr[i]; -// oddPrefixSum[i] = i % 2 == 0 ? oddPrefixSum[i-1] : oddPrefixSum[i-1] + currentNum; -// } -// -// // find special index/s -// if (oddPrefixSum[len-1] == evenPrefixSum[len-1] - evenPrefixSum[0]) ans++; // 0th Index -// for (int i = 1; i < len; i++) { -// int currentEvenSum = evenPrefixSum[i-1] + (oddPrefixSum[len-1] - oddPrefixSum[i]); -// int currentOddSum = oddPrefixSum[i-1] + (evenPrefixSum[len-1] - evenPrefixSum[i]); -// -// if (currentEvenSum == currentOddSum) ans++; -// } - -// return ans; -// } -} From e171aaa3a77334af3d4fe9a7181cf890d111205b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:37:44 +0530 Subject: [PATCH 0445/1894] clean up arrays folder, solution with no explanation --- Arrays/anti_diagonals.java | 102 ------------------ Arrays/arrays_strings_check_permutations.cpp | 46 -------- Arrays/arrays_strings_is_unique.cpp | 59 ---------- Arrays/arrays_strings_one_away.cpp | 64 ----------- ...gs_pallindromic_permutations_effecient.cpp | 59 ---------- Arrays/count_increasing_pairs.java | 97 ----------------- Arrays/find_number_of_good_pairs_in_array.py | 39 ------- Arrays/longest_consecutive_nums_subarray.cpp | 35 ------ Arrays/majority_element.cpp | 29 ----- Arrays/majority_element_2.java | 66 ------------ ...f_concatenated_string_with_unique_char.cpp | 67 ------------ Arrays/maximum_subarray_cumulative.cpp | 36 ------- Arrays/merge_overlapping_intervals.java | 68 ------------ Arrays/min_rewards.java | 47 -------- Arrays/multiple_left_rotations.java | 92 ---------------- Arrays/next_greater_element.cpp | 57 ---------- Arrays/non_constructable_change.java | 37 ------- Arrays/subarray_with_zero_sum.go | 23 ---- Arrays/validate_subsequence.go | 37 ------- Arrays/validate_subsequence.java | 34 ------ 20 files changed, 1094 deletions(-) delete mode 100644 Arrays/anti_diagonals.java delete mode 100644 Arrays/arrays_strings_check_permutations.cpp delete mode 100644 Arrays/arrays_strings_is_unique.cpp delete mode 100644 Arrays/arrays_strings_one_away.cpp delete mode 100644 Arrays/arrays_strings_pallindromic_permutations_effecient.cpp delete mode 100644 Arrays/count_increasing_pairs.java delete mode 100644 Arrays/find_number_of_good_pairs_in_array.py delete mode 100644 Arrays/longest_consecutive_nums_subarray.cpp delete mode 100644 Arrays/majority_element.cpp delete mode 100644 Arrays/majority_element_2.java delete mode 100644 Arrays/max_len_of_concatenated_string_with_unique_char.cpp delete mode 100644 Arrays/maximum_subarray_cumulative.cpp delete mode 100644 Arrays/merge_overlapping_intervals.java delete mode 100644 Arrays/min_rewards.java delete mode 100644 Arrays/multiple_left_rotations.java delete mode 100644 Arrays/next_greater_element.cpp delete mode 100644 Arrays/non_constructable_change.java delete mode 100644 Arrays/subarray_with_zero_sum.go delete mode 100644 Arrays/validate_subsequence.go delete mode 100644 Arrays/validate_subsequence.java diff --git a/Arrays/anti_diagonals.java b/Arrays/anti_diagonals.java deleted file mode 100644 index 2fe6e90e..00000000 --- a/Arrays/anti_diagonals.java +++ /dev/null @@ -1,102 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Give a N * N square matrix A, return an array of its anti-diagonals. Look at the example for more details. - * - * - * Problem Constraints - * 1<= N <= 1000 - * 1<= A[i][j] <= 1e9 - * - * - * Input Format - * Only argument is a 2D array A of size N * N. - * - * - * Output Format - * Return a 2D integer array of size (2 * N-1) * N, representing the anti-diagonals of input array A. - * The vacant spaces in the grid should be assigned to 0. - * - * - * Example Input - * Input 1: - * 1 2 3 - * 4 5 6 - * 7 8 9 - * Input 2: - * - * 1 2 - * 3 4 - * - * - * Example Output - * Output 1: - * 1 0 0 - * 2 4 0 - * 3 5 7 - * 6 8 0 - * 9 0 0 - * Output 2: - * - * 1 0 - * 2 3 - * 4 0 - * - * - * Example Explanation - * For input 1: - * The first anti diagonal of the matrix is [1 ], the rest spaces shoud be filled with 0 making the row as [1, 0, 0]. - * The second anti diagonal of the matrix is [2, 4 ], the rest spaces shoud be filled with 0 making the row as [2, 4, 0]. - * The third anti diagonal of the matrix is [3, 5, 7 ], the rest spaces shoud be filled with 0 making the row as [3, 5, 7]. - * The fourth anti diagonal of the matrix is [6, 8 ], the rest spaces shoud be filled with 0 making the row as [6, 8, 0]. - * The fifth anti diagonal of the matrix is [9 ], the rest spaces shoud be filled with 0 making the row as [9, 0, 0]. - * For input 2: - * - * The first anti diagonal of the matrix is [1 ], the rest spaces shoud be filled with 0 making the row as [1, 0, 0]. - * The second anti diagonal of the matrix is [2, 4 ], the rest spaces shoud be filled with 0 making the row as [2, 4, 0]. - * The third anti diagonal of the matrix is [3, 0, 0 ], the rest spaces shoud be filled with 0 making the row as [3, 0, 0]. - */ -public class AntiDiagonals { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, 2, 3)); - array.add(Arrays.asList(4, 5, 6)); - array.add(Arrays.asList(7 ,8, 9)); - - List> result = solve(array); - for (List list: result) { - System.out.println(list); - } - } - public static List> solve(List> array) { - // O(row * col) time | (row * col) space - List> result = new ArrayList<>(); - int row = array.size(); - - // 0th row - for (int col = 0; col < array.get(0).size(); col++) { - printDiagonal(0, col, array, result); //row is fixed - } - - // last col - int col = array.get(0).size() - 1; - for (int i = 1; i < row; i++) { - printDiagonal(i, col, array, result); //col is fixed - } - return result; - } - public static void printDiagonal(int row, int col, List> array, List> result) { - List ans = new ArrayList<>(); - for (var num : array) { - ans.add(0); - } - int i = 0; - while (row < array.size() && col > -1) { - int currentNum = array.get(row++).get(col--); - ans.set(i++, currentNum); - } - result.add(ans); - } -} diff --git a/Arrays/arrays_strings_check_permutations.cpp b/Arrays/arrays_strings_check_permutations.cpp deleted file mode 100644 index 257966bc..00000000 --- a/Arrays/arrays_strings_check_permutations.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Implement an algorithm to determine if a string is permutation of other. -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; -bool check_permutation(string s, string t){ - // Time complexity O(n log (n)) n = len of string - // but its clean simple and easy to understand - if(s.length() != t.length()) - return false; - sort(s.begin(), s.end()); - sort(t.begin(), t.end()); - if(s.compare(t) == 0) - return true; - return false; -} -bool check_permutation_fast(string s, string t){ - // TC O(n) - if(s.length() != t.length()) - return false; - map letters; - for(char c : s){ - letters[c]++; - } - for(char c : t){ - letters[c]--; - if(letters[c] < 0){ - return false; - } - } - return true; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -int main(){ - check_permutation("ABDE", "DEBA") ? print_ans(true) : print_ans(false); - check_permutation("ABCD", "DEFG") ? print_ans(true) : print_ans(false); - check_permutation_fast("AA", "DEBA") ? print_ans(true) : print_ans(false); - check_permutation_fast("ADEB", "ABED") ? print_ans(true) : print_ans(false); - return 0; -} \ No newline at end of file diff --git a/Arrays/arrays_strings_is_unique.cpp b/Arrays/arrays_strings_is_unique.cpp deleted file mode 100644 index 6292a3b3..00000000 --- a/Arrays/arrays_strings_is_unique.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Implement an algorithm to determine if a string has all unique characters. -// what if you cannot use additional data structures? -// Program Author : Abhisek Kumar Gupta -// Approach 1 : compare every character of string with other character TC O(n^2) -// Approach 2 : Sort the string and compare neighbouring character for dups -// TC of approach 2 : O(n log(n)) -#include -using namespace std; -bool is_unique_normal(string s){ - // using additional data structure - // TC O(min(c, n)) c being size of character set n = len of string - // SC is O(1) here - if(s.length() > 128) - return false; - bool visited[128]; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(visited[val]){ - return false; - } - visited[val] = true; - } - return true; -} -bool is_unique(string s){ - // without using additional data structures - // here we reduce our space usage - if(s.length() > 128) - return false; - int checker = 0; - for(int i = 0; i < s.length(); i++){ - int val = s[i] - 'a'; - if(checker & (1 << val)) - return false; - checker |= (1 << val); - } - return true; -} -void print_ans(bool ans, string s){ - if(ans){ - cout << s << " is unique\n"; - } - else{ - cout << s << " is not unique\n"; - } -} -int main(){ - string s = "ABCDD"; - string t = "ABCD"; - string u = "AAAAAABCD"; - is_unique_normal(s) ? print_ans(true, s) : print_ans(false, s); - is_unique_normal(t) ? print_ans(true, t) : print_ans(false, t); - is_unique_normal(u) ? print_ans(true, u) : print_ans(false, u); - cout << "\n***********************\n"; - is_unique(s) ? print_ans(true, s) : print_ans(false, s); - is_unique(t) ? print_ans(true, t) : print_ans(false, t); - is_unique(u) ? print_ans(true, u) : print_ans(false, u); - return 0; -} \ No newline at end of file diff --git a/Arrays/arrays_strings_one_away.cpp b/Arrays/arrays_strings_one_away.cpp deleted file mode 100644 index 4715abd4..00000000 --- a/Arrays/arrays_strings_one_away.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// Given two strings write a function to check if they are one edit(or zero edits) away -// Program Author : Abhisek Kumar Gupta - -// Sample Input : Pale Ple -// Output : Yes Pale -// Sample Input : Pale bae -// Output : No -#include -using namespace std; -bool one_edit_replace(string a, string b){ - bool found_difference = false; - for(int i = 0; i < a.length(); i++){ - if(a[i] != b[i]){ - if(found_difference){ - return false; - } - found_difference = true; - } - } - return true; -} -bool one_edit_insert(string a, string b){ - int i1 = 0, i2 = 0; - while(i1 < a.length() && i2 < b.length()){ - if(a[i1] != b[i2]){ - if(i1 != i2){ - return false; - } - i2++; - } - else{ - i1++; - i2++; - } - } - return true; -} -bool is_one_edit_away(string a, string b){ - if(a.length() == b.length()){ - return one_edit_replace(a, b); - } - else if(a.length() + 1 == b.length()){ - return one_edit_insert(a, b); - } - else if(a.length() - 1 == b.length()){ - return one_edit_insert(b, a); - } - return false; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -int main(){ - is_one_edit_away("Pale", "Ple") ? print_ans(true) : print_ans(false); - is_one_edit_away("Pales", "Pale") ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bale") ? print_ans(true) : print_ans(false); - is_one_edit_away("Pale", "bae") ? print_ans(true) : print_ans(false); - return 0; -} diff --git a/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp b/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp deleted file mode 100644 index 94427b1e..00000000 --- a/Arrays/arrays_strings_pallindromic_permutations_effecient.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Write a function to check if it is a permutation of a pallindrome using bitvector -// Program Author : Abhisek Kumar Gupta -// Sample Input : aabcb -// Output : Yes -// Sample Input : ab -// Output : No -#include -using namespace std; -bool check_exactly_for_one_set_bit(int bit_vector){ - return (bit_vector & (bit_vector - 1)) == 0; -} -int toggle(int bit_vector, int x){ - if(x < 0) return bit_vector; - int mask = 1 << x; - if((bit_vector & mask) == 0){ - bit_vector |= mask; - } - else{ - bit_vector &= ~mask; - } - return bit_vector; -} - -int create_bit_vector(string a){ - int bit_vector = 0, mask = 0; - for(int i = 0; i < a.length(); i++){ - int x = a[i] - 'a'; - bit_vector = toggle(bit_vector, x); - /* - mask = 1 << x; - if((bit_vector & mask) == 0){ - bit_vector |= mask; - } - else{ - bit_vector &= ~mask; - } - */ - } - return bit_vector; -} -void print_ans(bool ans){ - if(ans){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } -} -bool is_permutation_pallindrome(string a){ - int bit_vector = create_bit_vector(a); - return bit_vector == 0 || check_exactly_for_one_set_bit(bit_vector); -} -int main(){ - is_permutation_pallindrome("aabcb") ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ab") ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("ABA") ? print_ans(true) : print_ans(false); - is_permutation_pallindrome("racecarf") ? print_ans(true) : print_ans(false); - return 0; -} \ No newline at end of file diff --git a/Arrays/count_increasing_pairs.java b/Arrays/count_increasing_pairs.java deleted file mode 100644 index 367e2880..00000000 --- a/Arrays/count_increasing_pairs.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * You are given an array A of N elements. Find the number of triplets i,j and k such that i -1; leftIdx--) { - int leftNum = array[leftIdx]; - if (leftNum < midNum) leftCount++; - } - int rightCount = 0; - for (int rightIdx = midIdx + 1; rightIdx < len; rightIdx++) { - int rightNum = array[rightIdx]; - if (rightNum > midNum) rightCount++; - } - int currentPairs = leftCount * rightCount; - totalPairs += currentPairs; - } - return totalPairs; - } - public static int solveUsingBruteForce(int[] array) { - // O(N^3) time | O(1) space - int ans = 0; - int len = array.length; - for (int leftIdx = 0; leftIdx < len; leftIdx++) { - int lefNum = array[leftIdx]; - for (int midIdx = leftIdx + 1; midIdx < len; midIdx++) { - int middleNum = array[midIdx]; - if (lefNum >= middleNum) continue; - for (int rightIdx = midIdx + 1; rightIdx < len; rightIdx++) { - int rightNum = array[rightIdx]; - if (middleNum < rightNum) { - ans++; - } - } - } - } - return ans; - } -} diff --git a/Arrays/find_number_of_good_pairs_in_array.py b/Arrays/find_number_of_good_pairs_in_array.py deleted file mode 100644 index 83e79083..00000000 --- a/Arrays/find_number_of_good_pairs_in_array.py +++ /dev/null @@ -1,39 +0,0 @@ -''' -Given an array of integers nums,we have to return the number of good pairs. - -A pair (i, j) is called good if nums[i] == nums[j] and i < j. means our search space will start from i+1 for nums[i] as it is mentioned that i -using namespace std; -const int Nmax = 100001; -int a[Nmax], n; -bool fr[Nmax]; - -int longest_consecutive_nums_subarray(){ - int ans = 0; - for(int left = 1; left <= n; left++){ - for(int i = 1; i <= n; i++){ - fr[i] = false; - } - int mini = a[left], maxi = a[left]; - for(int right = left; right <= n; right++){ - if(fr[a[right]]) - break; - fr[a[right]] = true; - mini = min(mini, a[right]); - maxi = max(maxi, a[right]); - if(right - left == maxi - mini){ - ans = max(ans, right - left + 1); - } - } - } - return ans; -} -int main(){ - cin >> n; - for(int i = 1; i <= n; i++){ - cin >> a[i]; - } - cout << longest_consecutive_nums_subarray(); - return 0; -} \ No newline at end of file diff --git a/Arrays/majority_element.cpp b/Arrays/majority_element.cpp deleted file mode 100644 index 18a1c699..00000000 --- a/Arrays/majority_element.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/*Given an array nums of size n, return the majority element. - -The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. - -Example 1: - -Input: nums = [3,2,3] -Output: 3 - -Example 2: - -Input: nums = [2,2,1,1,1,2,2] -Output: 2 */ - - - - -class Solution { -public: - int majorityElement(vector& arr) { - int ele = arr[0]; - int count = 0; - for(int i = 0;i < arr.size();i++){ - if(count == 0) ele = arr[i]; - count += (ele == arr[i]) ? 1 : -1; - } - return ele; - } -}; \ No newline at end of file diff --git a/Arrays/majority_element_2.java b/Arrays/majority_element_2.java deleted file mode 100644 index 9fd05047..00000000 --- a/Arrays/majority_element_2.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. - * - * - * - * Example 1: - * - * Input: nums = [3,2,3] - * Output: [3] - * Example 2: - * - * Input: nums = [1] - * Output: [1] - * Example 3: - * - * Input: nums = [1,2] - * Output: [1,2] - * - * - * Constraints: - * - * 1 <= nums.length <= 5 * 104 - * -109 <= nums[i] <= 109 - */ -package InterviewProblems; - -import java.util.ArrayList; -import java.util.List; - -public class MajorityElement2 { - public static void main(String[] args) { - int[] nums = {1,2}; - List ans = solve(nums); - System.out.println(ans); - } - public static List solve(int[] nums) { - // O(N) time | O(1) space - int num1 = -1, num2 = -1, count1 = 0, count2 = 0, len = nums.length; - - for (int num : nums) { - if (num == num1) count1++; - else if (num == num2) count2++; - else if (count1 == 0) { - num1 = num; - count1++; - } else if (count2 == 0) { - num2 = num; - count2++; - } else { - count1--; - count2--; - } - } - - List ans = new ArrayList<>(); - count1 = 0; count2 = 0; - for (int num : nums) { - if (num == num1) count1++; - else if (num == num2) count2++; - } - if (count1 > len / 3) ans.add(num1); - if (count2 > len / 3) ans.add(num2); - - return ans; - } -} diff --git a/Arrays/max_len_of_concatenated_string_with_unique_char.cpp b/Arrays/max_len_of_concatenated_string_with_unique_char.cpp deleted file mode 100644 index 4a129590..00000000 --- a/Arrays/max_len_of_concatenated_string_with_unique_char.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* -You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. - -Return the maximum possible length of s. - -A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. - - - -Example 1: - -Input: arr = ["un","iq","ue"] -Output: 4 -Explanation: All the valid concatenations are: -- "" -- "un" -- "iq" -- "ue" -- "uniq" ("un" + "iq") -- "ique" ("iq" + "ue") -Maximum length is 4. -Example 2: - -Input: arr = ["cha","r","act","ers"] -Output: 6 -Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). -Example 3: - -Input: arr = ["abcdefghijklmnopqrstuvwxyz"] -Output: 26 -Explanation: The only string in arr has all 26 characters. - - -Constraints: - -1 <= arr.length <= 16 -1 <= arr[i].length <= 26 -arr[i] contains only lowercase English letters. - -*/ - -class Solution { -public: - int check(vector& arr, int i, string s){ - if(i == arr.size()){ - int freq[26] = {0}; - for(int k = 0; k < s.length(); k++){ - if(freq[s[k]-'a'] == 1) - return 0; - freq[s[k]-'a']++; - } - return s.length(); - } - int op1, op2; - op1 = op2 = INT_MIN; - // include the string - if(s.length() + arr[i].length() <= 26){ - op1 = check(arr, i+1, s + arr[i]); - } - // exclude it - op2 = check(arr, i+1, s); - return max(op1, op2); - } - int maxLength(vector& arr) { - return check(arr, 0, ""); - } -}; \ No newline at end of file diff --git a/Arrays/maximum_subarray_cumulative.cpp b/Arrays/maximum_subarray_cumulative.cpp deleted file mode 100644 index d6d1b295..00000000 --- a/Arrays/maximum_subarray_cumulative.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// Subarray with maximum sum using cumulative sum O(n^2) -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - vector W(n); - for(int i = 0; i < n; i++) W[i] = 0; - cin >> V[0]; - W[0] = V[0]; - for(int i = 1; i < n; i++){ - cin >> V[i]; - W[i] = W[i-1] + V[i]; - } - for(int i = 0; i < n; i++) cout << W[i] << " "; - cout << endl; - int current_sum = 0, left = 0, right = 0; - int maximum_sum = INT_MIN; - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - current_sum = 0; - current_sum = W[j] - W[i - 1]; - if(current_sum > maximum_sum){ - maximum_sum = current_sum; - left = i; - right = j; - } - //maximum_sum = max(maximum_sum, current_sum); - } - } - cout << maximum_sum << endl; - for(int i = left; i <= right; i++) - cout << V[i]; - return 0; -} \ No newline at end of file diff --git a/Arrays/merge_overlapping_intervals.java b/Arrays/merge_overlapping_intervals.java deleted file mode 100644 index 4be10132..00000000 --- a/Arrays/merge_overlapping_intervals.java +++ /dev/null @@ -1,68 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * - - Write a function that takes in a non-empty array of arbitrary intervals, merges any overlapping intervals, and returns the new intervals in no particular order. - - Each interval interval is an array of two integers, with interval[0] as the start of the interval and interval[1] as the end of the interval. - - Note that back-to-back intervals aren't considered to be overlapping. For example, [1, 5] and [6, 7] aren't overlapping; however, [1, 6] and [6, 7] are indeed overlapping. - - Also note that the start of any particular interval will always be less than or equal to the end of that interval. - Sample Input - - intervals = [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]] - - Sample Output - - [[1, 2], [3, 8], [9, 10]] - // Merge the intervals [3, 5], [4, 7], and [6, 8]. - // The intervals could be ordered differently. - - - */ -public class MergeOverlappingIntervals { - public static void main(String[] args) { - int[][] intervals = {{1, 2}, - {3, 7}, - {4, 7}, - {6, 8}, - {9, 10}}; - int[][] result = solve(intervals); - System.out.println(Arrays.deepToString(result)); - } - - public static int[][] solve(int[][] intervals) { - // O(nlog(n)) time | O(n) space - //Sort the intervals by starting value. - int[][] sortedIntervals = intervals.clone(); - Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0])); - - List mergedIntervals = new ArrayList<>(); - int[] currentInterval = sortedIntervals[0]; - mergedIntervals.add(currentInterval); - - for (int[] nextInterval : sortedIntervals) { - int currentIntervalEnd = currentInterval[0]; - int nextIntervalStart = nextInterval[0]; - int nextIntervalEnd = nextInterval[1]; - - if (currentIntervalEnd >= nextIntervalStart) { - currentInterval[1] = Math.max(currentIntervalEnd, nextIntervalEnd); - } else { - currentInterval = nextInterval; - mergedIntervals.add(currentInterval); - } - } - return mergedIntervals.toArray(new int[mergedIntervals.size()][]); - } - -} - - - - - diff --git a/Arrays/min_rewards.java b/Arrays/min_rewards.java deleted file mode 100644 index d676040a..00000000 --- a/Arrays/min_rewards.java +++ /dev/null @@ -1,47 +0,0 @@ -import java.util.Arrays; -import java.util.stream.IntStream; - -/** - * - - Imagine that you're a teacher who's just graded the final exam in a class. You have a list of student scores on the final exam in a particular order (not necessarily sorted), and you want to reward your students. You decide to do so fairly by giving them arbitrary rewards following two rules: - - All students must receive at least one reward. - Any given student must receive strictly more rewards than an adjacent student (a student immediately to the left or to the right) with a lower score and must receive strictly fewer rewards than an adjacent student with a higher score. - - Write a function that takes in a list of scores and returns the minimum number of rewards that you must give out to students to satisfy the two rules. - - You can assume that all students have different scores; in other words, the scores are all unique. - Sample Input - - scores = [8, 4, 2, 1, 3, 6, 7, 9, 5] - - Sample Output - - 25 // you would give out the following rewards: [4, 3, 2, 1, 2, 3, 4, 5, 1] - - - */ -public class MinRewards { - - public static void main(String[] args) { - int[] scores = {8, 4, 2, 1, 3, 6, 7, 9, 5}; - System.out.println(solve(scores)); - } - - public static int solve(int[] scores) { - // O(n) time | O(n) space - int[] rewards = new int[scores.length]; - Arrays.fill(rewards, 1); - - for (int i = 1; i < scores.length; i++) { - if (scores[i] > scores[i - 1]) rewards[i] = rewards[i - 1] + 1; - } - for (int i = scores.length - 2; i > -1; i--) { - if (scores[i] > scores[i + 1]) rewards[i] = Math.max(rewards[i], rewards[i + 1] + 1); - } - - return IntStream.of(rewards).sum(); - } - -} diff --git a/Arrays/multiple_left_rotations.java b/Arrays/multiple_left_rotations.java deleted file mode 100644 index 066b3507..00000000 --- a/Arrays/multiple_left_rotations.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Given an array of integers A and multiple values in B, which represents the number of times array A needs to be left rotated. - * - * Find the rotated array for each value and return the result in the from of a matrix where ith row represents the rotated array for the ith value in B. - * - * - * - * Problem Constraints - * 1 <= length of both arrays <= 2000 -10^9 <= A[i] <= 10^9 0 <= B[i] <= 2000 - * - * - * Input Format - * The first argument given is the integer array A. - * The second argument given is the integer array B. - * - * - * Output Format - * Return the resultant matrix. - * - * - * Example Input - * Input 1: - * - * A = [1, 2, 3, 4, 5] - * B = [2, 3] - * - * Input 2: - * - * - * A = [5, 17, 100, 11] - * B = [1] - * - * - * - * - * Example Output - * Output 1: - * - * [ [3, 4, 5, 1, 2] - * [4, 5, 1, 2, 3] ] - * - * - * Output 2: - * - * - * [ [17, 100, 11, 5] ] - * - * - * - * Example Explanation - * for input 1 -> B[0] = 2 which requires 2 times left rotations - * - * 1: [2, 3, 4, 5, 1] - * - * 2: [3, 4, 5, 1, 2] - * - * B[1] = 3 which requires 3 times left rotation - * - * 1: [2, 3, 4, 5, 1] - * - * 2: [3, 4, 5, 1, 2] - * - * 2: [4, 5, 1, 2, 4] - */ - -package InterviewProblems; - -import java.util.Arrays; - -public class MultipleLeftRotationsOfArray { - public static void main(String[] args) { - int[] A = {1, 2, 3, 4, 5}; - int[] B = {2, 3}; - int[][] ans = solve(A, B); - System.out.println(Arrays.deepToString(ans)); - } - public static int[][] solve(int[] arr, int[] b) { - // O(N * K) time | O(N * K) space where K is size of b && N is length of arr. - int n = arr.length; - int [][] ans = new int[b.length][n]; - - for (int i = 0; i < b.length; i++) { - int num =b[i]; - int[] temp = new int[n]; - for (int j = 0; j < n; j++) { - temp[j] = arr[(num + j) % n]; - } - ans[i] = temp; - } - return ans; - } -} diff --git a/Arrays/next_greater_element.cpp b/Arrays/next_greater_element.cpp deleted file mode 100644 index 953fe916..00000000 --- a/Arrays/next_greater_element.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. - -You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. - -For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1. - -Return an array ans of length nums1.length such that ans[i] is the next greater element as described above. - - - -Example 1: - -Input: nums1 = [4,1,2], nums2 = [1,3,4,2] -Output: [-1,3,-1] -Explanation: The next greater element for each value of nums1 is as follows: -- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. -- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. -- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. -Example 2: - -Input: nums1 = [2,4], nums2 = [1,2,3,4] -Output: [3,-1] -Explanation: The next greater element for each value of nums1 is as follows: -- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. -- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. - - -Constraints: - -1 <= nums1.length <= nums2.length <= 1000 -0 <= nums1[i], nums2[i] <= 104 -All integers in nums1 and nums2 are unique. -All the integers of nums1 also appear in nums2. -*/ - -class Solution { -public: - vector nextGreaterElement(vector& nums1, vector& nums2) { - vector result(nums1.size(), -1); - stack st; - unordered_map umap; - for(auto element : nums2){ - while(!st.empty() && element > st.top()){ - umap[st.top()] = element; - st.pop(); - } - st.push(element); - } - for(int i = 0; i < nums1.size(); i++){ - if(umap.find(nums1[i]) != umap.end()){ - result[i] = umap[nums1[i]]; - } - } - return result; - } -}; \ No newline at end of file diff --git a/Arrays/non_constructable_change.java b/Arrays/non_constructable_change.java deleted file mode 100644 index 2e6d37f0..00000000 --- a/Arrays/non_constructable_change.java +++ /dev/null @@ -1,37 +0,0 @@ -import java.util.*; - -/** - * - - Given an array of positive integers representing the values of coins in your possession, write a function that returns the minimum amount of change (the minimum sum of money) that you cannot create. The given coins can have any positive integer value and aren't necessarily unique (i.e., you can have multiple coins of the same value). - - For example, if you're given coins = [1, 2, 5], the minimum amount of change that you can't create is 4. If you're given no coins, the minimum amount of change that you can't create is 1. - Sample Input - - coins = [5, 7, 1, 1, 2, 3, 22] - - Sample Output - - 20 - - - */ - -public class NonConstructibleChange { - public static void main(String[] args) { - int[] coins = {5, 7, 1, 1, 2, 3, 22}; - System.out.println(solve(coins)); - } - public static int solve(int[] coins) { - - Arrays.sort(coins); - int currentChangeCreated = 0; - - for(int coin: coins) { - if(coin > currentChangeCreated + 1) return currentChangeCreated + 1; - currentChangeCreated += coin; - } - return currentChangeCreated + 1; - } - -} diff --git a/Arrays/subarray_with_zero_sum.go b/Arrays/subarray_with_zero_sum.go deleted file mode 100644 index aa3da454..00000000 --- a/Arrays/subarray_with_zero_sum.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "fmt" - -func IsSubArrayWithZeroSum(Arr []int) bool { - prefixSum := make(map[int]bool) - sum := 0 - for i := 0; i < len(Arr); i++ { - sum += Arr[i] - if sum == 0 || prefixSum[sum] == true { - return true - } - prefixSum[sum] = true - } - return false -} - -func main() { - Arr := []int{1, 2, 3, 4, -7, 1} - fmt.Println(IsSubArrayWithZeroSum(Arr)) - Arr = []int{1, 2, 3, 4, 5, 6, 7} - fmt.Println(IsSubArrayWithZeroSum(Arr)) -} \ No newline at end of file diff --git a/Arrays/validate_subsequence.go b/Arrays/validate_subsequence.go deleted file mode 100644 index 9876e048..00000000 --- a/Arrays/validate_subsequence.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - Given two non-empty arrays of integers, write a function that determines - whether the second array is a subsequence of the first one. - - A subsequence of an array is a set of numbers that aren't necessarily adjacent - in the array but that are in the same order as they appear in the array. For - instance, the numbers - - Sample Input : Array [1, 2, 3, 4, 5,] Seq [2, 4, 5] - Output : True - Sample Input : Array [77, 2, 3, 4, 5,] Seq [2, 77, 5] - Output : False - - -*/ -package main - -import "fmt" - - -func IsValidSubsequence(array []int, sequence []int) bool { - // Write your code here. - index := 0 - for i := 0; i < len(array) && index < len(sequence); i++ { - if array[i] == sequence[index] { - index++ - } - } - return index == len(sequence) -} - -func main() { - arr := []int{1, 2, 3, 4, 5, 6} - seq := []int{2, 4, 6} - msg := IsValidSubsequence(arr, seq) - fmt.Println(msg) -} \ No newline at end of file diff --git a/Arrays/validate_subsequence.java b/Arrays/validate_subsequence.java deleted file mode 100644 index c74bbe47..00000000 --- a/Arrays/validate_subsequence.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * - - Given two non-empty arrays of integers, write a function that determines whether the second array is a subsequence of the first one. - - A subsequence of an array is a set of numbers that aren't necessarily adjacent in the array but that are in the same order as they appear in the array. For instance, the numbers [1, 3, 4] form a subsequence of the array [1, 2, 3, 4], and so do the numbers [2, 4]. Note that a single number in an array and the array itself are both valid subsequences of the array. - Sample Input - - array = [5, 1, 22, 25, 6, -1, 8, 10] - sequence = [1, 6, -1, 10] - - Sample Output - - true - - - */ -public class ValidateSubsequence { - public static void main(String[] args){ - int[] array = {5, 1, 22, 25, 6, -1, 8, 10}; - int[] sequence = {1, 6, -1, 19}; - - System.out.println(solve(array, sequence)); - } - public static boolean solve(int[] array, int[] sequence) { - - int seqIdx = 0; - for(var num: array) { - if(seqIdx == sequence.length) break; - if(sequence[seqIdx] == num ) seqIdx++; - } - return seqIdx == sequence.length; - } -} \ No newline at end of file From cc8a2fb217dc9ffe5f94f7a98961ffbb0caa41b0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Mar 2023 22:40:27 +0530 Subject: [PATCH 0446/1894] remove solution with no explanation --- Arrays/longest_consecutive_ones.java | 73 ---------------- Arrays/minimum_swaps.java | 116 -------------------------- Arrays/non_constructible_change.go | 43 ---------- Arrays/odd_indices_sum.java | 82 ------------------ Arrays/quilibruim_index.java | 86 ------------------- Arrays/remove_adjacant_duplicates.cpp | 74 ---------------- Arrays/remove_duplicates.java | 53 ------------ Arrays/remove_duplicates.js | 41 --------- Arrays/set_matrix_zeroes.java | 82 ------------------ Arrays/smallest_difference.java | 55 ------------ Arrays/subarray_with_least_avg.java | 89 -------------------- 11 files changed, 794 deletions(-) delete mode 100644 Arrays/longest_consecutive_ones.java delete mode 100644 Arrays/minimum_swaps.java delete mode 100644 Arrays/non_constructible_change.go delete mode 100644 Arrays/odd_indices_sum.java delete mode 100644 Arrays/quilibruim_index.java delete mode 100644 Arrays/remove_adjacant_duplicates.cpp delete mode 100644 Arrays/remove_duplicates.java delete mode 100644 Arrays/remove_duplicates.js delete mode 100644 Arrays/set_matrix_zeroes.java delete mode 100644 Arrays/smallest_difference.java delete mode 100644 Arrays/subarray_with_least_avg.java diff --git a/Arrays/longest_consecutive_ones.java b/Arrays/longest_consecutive_ones.java deleted file mode 100644 index e914f568..00000000 --- a/Arrays/longest_consecutive_ones.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Given a binary string A. It is allowed to do at most one swap between any 0 and 1. Find and return the length of the longest consecutive 1’s that can be achieved. - * - * - * Input Format - * - * The only argument given is string A. - * Output Format - * - * Return the length of the longest consecutive 1’s that can be achieved. - * Constraints - * - * 1 <= length of string <= 1000000 - * A contains only characters 0 and 1. - * For Example - * - * Input 1: - * A = "111000" - * Output 1: - * 3 - * - * Input 2: - * A = "111011101" - * Output 2: - * 7 - */ - -package InterviewProblems; - -public class longestConsecutiveOnes { - public static void main(String[] args) { - String str = "11010110000000000"; - int ans = solve(str); - System.out.println(ans); - } - public static int solve(String str) { - // O(N) time | O(1) space - int ans = 0; - int len = str.length(); - int totalOnes = 0; - - // first count total one's - for (int i = 0; i < len; i++) { // 1110111 - char currentChar = str.charAt(i); - if (currentChar == '1') totalOnes++; - } - - if (totalOnes == 0) return 0; - for (int i = 0; i < len; i++) { - char currentChar = str.charAt(i); - if (currentChar == '0') { - int leftIdx = i - 1, leftOnes = 0; - while (leftIdx > -1 && str.charAt(leftIdx) == '1') { - leftIdx--; - leftOnes++; - } - - int rightIdx = i + 1, rightOnes = 0; - while (rightIdx < len && str.charAt(rightIdx) == '1') { - rightIdx++; - rightOnes++; - } - - if (leftOnes + rightOnes == totalOnes) { - ans = Math.max(ans, leftOnes + rightOnes); - } else { - ans = Math.max(ans, leftOnes + rightOnes + 1); - } - } - } - return ans; - } -} diff --git a/Arrays/minimum_swaps.java b/Arrays/minimum_swaps.java deleted file mode 100644 index 091c2445..00000000 --- a/Arrays/minimum_swaps.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Given an array of integers A and an integer B, find and return the minimum number of swaps required to bring all the numbers less than or equal to B together. - * - * Note: It is possible to swap any two elements, not necessarily consecutive. - * - * - * - * Problem Constraints - * - * 1 <= length of the array <= 100000 - * -109 <= A[i], B <= 109 - * - * - * - * Input Format - * - * The first argument given is the integer array A. - * The second argument given is the integer B. - * - * - * - * Output Format - * - * Return the minimum number of swaps. - * - * - * - * Example Input - * - * Input 1: - * - * A = [1, 12, 10, 3, 14, 10, 5] - * B = 8 - * Input 2: - * - * A = [5, 17, 100, 11] - * B = 20 - * - * - * Example Output - * - * Output 1: - * - * 2 - * Output 2: - * - * 1 - * - * - * Example Explanation - * - * Explanation 1: - * - * A = [1, 12, 10, 3, 14, 10, 5] - * After swapping 12 and 3, A => [1, 3, 10, 12, 14, 10, 5]. - * After swapping the first occurence of 10 and 5, A => [1, 3, 5, 12, 14, 10, 10]. - * Now, all elements less than or equal to 8 are together. - * Explanation 2: - * - * A = [5, 17, 100, 11] - * After swapping 100 and 11, A => [5, 17, 11, 100]. - * Now, all elements less than or equal to 20 are together. - * - */ - -package SlidingWindow; - -public class MinimumSwaps { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long endTime = System.currentTimeMillis(); - - - int[] array = {1, 12, 10, 3, 14, 10, 5}; - int b = 8; - int ans = solve(array, b); - System.out.println(ans); - - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - public static int solve(int[] array, int b) { - //O(n) time | O(1) space - - int minSwaps; - int length = array.length; - - // Find count of all the elements <= b - int k = 0; - for (int i = 0; i < length; i++) - if (array[i] <= b) k++; - - // Calculate the count of elements > b for the first window (i.e k length) - int count = 0; - for (int i = 0; i < k; i++) { - if (array[i] > b) count++; - } - minSwaps = count; - - // Consider remaining windows - int startIdx = 1; - int endIdx = k; - while (endIdx < length) { - if (array[endIdx] > b) count++; - if (array[startIdx - 1] > b) count--; - minSwaps = Math.min(count, minSwaps); - startIdx++; - endIdx++; - } - - return minSwaps; - } -} diff --git a/Arrays/non_constructible_change.go b/Arrays/non_constructible_change.go deleted file mode 100644 index caf40ab9..00000000 --- a/Arrays/non_constructible_change.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Given an array of positive integers representing the values of coins in your - possession, write a function that returns the minimum amount of change (the - minimum sum of money) that you - - For example, if you're given coins = [1, 2, 5] , the minimum - amount of change that you can't create is 4, . If you're given no - coins, the minimum amount of change that you can't create is 1 - - Sample Input: [1, 5, 1, 1, 1, 10, 15, 20, 100] - Output: 55 -*/ -package main - -import ( - "fmt" - "sort" -) - - -func NonConstructibleChange(coins []int) int { - // Write your code here. - result := 0 - sort.Ints(coins) - - for i := 0; i < len(coins); i++ { - nextGreaterCoin := result + 1 - if coins[i] > nextGreaterCoin { - return nextGreaterCoin - } else if coins[i] <= nextGreaterCoin { - result += coins[i] - } - } - return result + 1 -} - - -func main() { - coins := []int{1, 5, 1, 1, 1, 10, 15, 20, 100} - - msg := NonConstructibleChange(coins) - fmt.Println(msg) -} \ No newline at end of file diff --git a/Arrays/odd_indices_sum.java b/Arrays/odd_indices_sum.java deleted file mode 100644 index 9101ea18..00000000 --- a/Arrays/odd_indices_sum.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * You are given an array A of length N and Q queries given by the 2D array B of size Q*2. Each query consists of two integers B[i][0] and B[i][1]. - * For every query, the task is to calculate the sum of all odd indices in the range A[B[i][0]…B[i][1]]. - * - * Note : Use 0-based indexing - * - * - * Problem Constraints - * 1 <= N <= 105 - * 1 <= Q <= 105 - * 1 <= A[i] <= 100 - * 0 <= B[i][0] <= B[i][1] < N - * - * - * Input Format - * First argument A is an array of integers. - * Second argument B is a 2D array of integers. - * - * - * Output Format - * Return an array of integers. - * - * - * Example Input - * Input 1: - * A = [1, 2, 3, 4, 5] - * B = [ [0,2] - * [1,4] ] - * Input 2: - * A = [2, 1, 8, 3, 9] - * B = [ [0,3] - * [2,4] ] - * - * - * Example Output - * Output 1: - * [2, 6] - * Output 2: - * [4, 3] - * - * - * Example Explanation - * For Input 1: - * The subarray for the first query is [1, 2, 3] whose sum of odd indices is 2. - * The subarray for the second query is [2, 3, 4, 5] whose sum of odd indices is 6. - * For Input 2: - * The subarray for the first query is [2, 1, 8, 3] whose sum of odd indices is 4. - * The subarray for the second query is [8, 3, 9] whose sum of odd indices is 3. - */ -package InterviewProblems; - -import java.util.Arrays; - -public class oddIndicesSum { - public static void main(String[] args) { - int[] a = {2, 1, 8, 3, 9}; - int[][] b = { {0, 3}, {2, 4} }; - int[] ans = solve(a, b); - System.out.println(Arrays.toString(ans)); - } - public static int[] solve(int[] a, int[][] b) { - // O(Q*N) time | O(N) space - int len = a.length; - int[] ans = new int[b.length]; - int[] oddIndicesSum = new int[len]; - - oddIndicesSum[0] = 0; - for (int i = 1; i < len; i++) { - int currentNum = a[i]; - oddIndicesSum[i] = i % 2 != 0 ? oddIndicesSum[i - 1] + currentNum : oddIndicesSum[i - 1]; - } - - for (int i = 0; i < b.length; i++) { - int[] currentQuery = b[i]; - int startIdx = currentQuery[0]; - int endIdx = currentQuery[1]; - - ans[i] = startIdx == 0 ? oddIndicesSum[endIdx] : oddIndicesSum[endIdx] - oddIndicesSum[startIdx - 1]; - } - return ans; - } -} diff --git a/Arrays/quilibruim_index.java b/Arrays/quilibruim_index.java deleted file mode 100644 index 1b07b30e..00000000 --- a/Arrays/quilibruim_index.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * You are given an array A of integers of size N. - * - * Your task is to find the equilibrium index of the given array - * - * The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. - * - * NOTE: - * - * Array indexing starts from 0. - * If there is no equilibrium index then return -1. - * If there are more than one equilibrium indexes then return the minimum index. - * - * - * - * Problem Constraints - * 1 <= N <= 105 - * -105 <= A[i] <= 105 - * - * - * Input Format - * First arugment is an array A . - * - * - * Output Format - * Return the equilibrium index of the given array. If no such index is found then return -1. - * - * - * Example Input - * Input 1: - * A=[-7, 1, 5, 2, -4, 3, 0] - * Input 2: - * - * A=[1,2,3] - * - * - * Example Output - * Output 1: - * 3 - * Output 2: - * - * -1 - * - * - * Example Explanation - * Explanation 1: - * 3 is an equilibrium index, because: - * A[0] + A[1] + A[2] = A[4] + A[5] + A[6] - * Explanation 1: - * - * There is no such index. - */ - -package PrefixSum; - -import java.util.ArrayList; -import java.util.Arrays; - -public class EquilibriumIndex { - public static void main(String[] args) { - ArrayList arr = new ArrayList<>( - Arrays.asList(-7, 1, 5, 2, -4, 3, 0)); - int ans = solve(arr); - System.out.println(ans); - } - public static int solve(ArrayList array) { - // O(N) time | O(N) space - ArrayList prefixSum = new ArrayList<>(); - - prefixSum.add(array.get(0)); - for (int i = 1; i < array.size(); i++) { - int currentPrefixSum = prefixSum.get(i - 1) + array.get(i); - prefixSum.add(currentPrefixSum); - } - - for (int i = 0; i < array.size(); i++) { - if (i == 0 ) { - if (prefixSum.get(prefixSum.size() - 1) - prefixSum.get(i) == 0) return i; - continue; - } - if (prefixSum.get(i - 1) == prefixSum.get(prefixSum.size() - 1) - prefixSum.get(i)) - return i; - } - return -1; - } -} diff --git a/Arrays/remove_adjacant_duplicates.cpp b/Arrays/remove_adjacant_duplicates.cpp deleted file mode 100644 index cfad981a..00000000 --- a/Arrays/remove_adjacant_duplicates.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* -You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. - -We repeatedly make k duplicate removals on s until we no longer can. - -Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. - - - -Example 1: - -Input: s = "abcd", k = 2 -Output: "abcd" -Explanation: There's nothing to delete. -Example 2: - -Input: s = "deeedbbcccbdaa", k = 3 -Output: "aa" -Explanation: -First delete "eee" and "ccc", get "ddbbbdaa" -Then delete "bbb", get "dddaa" -Finally delete "ddd", get "aa" -Example 3: - -Input: s = "pbbcggttciiippooaais", k = 2 -Output: "ps" - - -Constraints: - -1 <= s.length <= 105 -2 <= k <= 104 -s only contains lowercase English letters. -*/ - -class Solution { -public: - /* class Pair{ - public: - char first; - int second; - - Pair(char f, int s){ - first = f; - second = s; - } - }; - */ - string removeDuplicates(string s, int k) { - stack > St; - for(int i = 0; i < s.size(); i++){ - if(St.empty() || s[i] != St.top().first){ - St.push(make_pair(s[i], 1)); - } - else{ - St.top().second++; - int count = St.top().second; - if(count == k){ - St.pop(); - } - } - } - string ans = ""; - while(!St.empty()){ - int count = St.top().second; - while(count--){ - ans += St.top().first; - } - St.pop(); - } - reverse(ans.begin(), ans.end()); - return ans; - } -}; \ No newline at end of file diff --git a/Arrays/remove_duplicates.java b/Arrays/remove_duplicates.java deleted file mode 100644 index a2936bbb..00000000 --- a/Arrays/remove_duplicates.java +++ /dev/null @@ -1,53 +0,0 @@ -/* -Given an integer array nums sorted in non-decreasing order, -remove the duplicates in-place such that each unique element appears only once. - The relative order of the elements should be kept the same. -Since it is impossible to change the length of the array in some languages, -you must instead have the result be placed in the first part of the array nums. -More formally, if there are k elements after removing the duplicates, -then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. -Return k after placing the final result in the first k slots of nums. -Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. - -Example 1: - -Input: nums = [1,1,2] -Output: 2, nums = [1,2,_] -Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. -It does not matter what you leave beyond the returned k (hence they are underscores). -Example 2: - -Input: nums = [0,0,1,1,1,2,2,3,3,4] -Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] -Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. -It does not matter what you leave beyond the returned k (hence they are underscores). - - */ - -class Solution { - public int removeDuplicates(int[] nums) { - int n = nums.length; - - int j = 0; - if(n == 0 || n == 1 ) - return n; - - for (int i = 0; i < n-1; i++) - { - if(nums[i] != nums[i+1]) - nums[j++]= nums[i]; - } - nums[j++]=nums[n-1]; - return j; - } -} -class RemoveDuplicates { - - public static void main(String[] args) { - - Solution s = new Solution(); - int nums [] = {1 ,2 ,2 ,2 ,45 ,67 ,89 ,89 ,89 }; - - System.out.println( s.removeDuplicates(nums)); - } -} \ No newline at end of file diff --git a/Arrays/remove_duplicates.js b/Arrays/remove_duplicates.js deleted file mode 100644 index 54d21f5f..00000000 --- a/Arrays/remove_duplicates.js +++ /dev/null @@ -1,41 +0,0 @@ - -/* -Given an integer array nums sorted in non-decreasing order, -remove the duplicates in-place such that each unique element appears only once. - The relative order of the elements should be kept the same. -Since it is impossible to change the length of the array in some languages, -you must instead have the result be placed in the first part of the array nums. -More formally, if there are k elements after removing the duplicates, -then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. -Return k after placing the final result in the first k slots of nums. -Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. - -Example 1: - -Input: nums = [1,1,2] -Output: 2, nums = [1,2,_] -Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. -It does not matter what you leave beyond the returned k (hence they are underscores). -Example 2: - -Input: nums = [0,0,1,1,1,2,2,3,3,4] -Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] -Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. -It does not matter what you leave beyond the returned k (hence they are underscores). - - */ -let nums=[1 ,2 ,2 ,2 ,45 ,67 ,89 ,89 ,89]; - -const removeDuplicates = (nums) => { - let count = 0; - for (let i = 0; i < nums.length; i++) { - if (i < nums.length - 1 && nums[i] == nums[i + 1]) { - continue; - } - nums[count] = nums[i]; - count++; - } - return count; -}; - -console.log(removeDuplicates(nums)); \ No newline at end of file diff --git a/Arrays/set_matrix_zeroes.java b/Arrays/set_matrix_zeroes.java deleted file mode 100644 index f456cac8..00000000 --- a/Arrays/set_matrix_zeroes.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * You are given a 2D integer matrix A, make all the elements in a row or column zero if the A[i][j] = 0. Specifically, make entire ith row and jth column zero. - * - * - * - * Problem Constraints - * 1 <= A.size() <= 103 - * - * 1 <= A[i].size() <= 103 - * - * 0 <= A[i][j] <= 103 - * - * - * - * Input Format - * First argument is a vector of vector of integers.(2D matrix). - * - * - * - * Output Format - * Return a vector of vector after doing required operations. - * - * - * - * Example Input - * Input 1: - * - * [1,2,3,4] - * [5,6,7,0] - * [9,2,0,4] - * - * - * Example Output - * Output 1: - * - * [1,2,0,0] - * [0,0,0,0] - * [0,0,0,0] - * - * - * Example Explanation - * Explanation 1: - * - * A[2][4] = A[3][3] = 0, so make 2nd row, 3rd row, 3rd column and 4th column zero. - */ - -import java.util.*; -public class SetMatrixZeroes { - public static void main(String[] args) { - List> matrix = new ArrayList<>(); - matrix.add(Arrays.asList(1, 2, 3, 4)); - matrix.add(Arrays.asList(5, 6, 7, 0)); - matrix.add(Arrays.asList(9, 2, 0, 4)); - - solve(matrix); - System.out.println(matrix); - } - public static void solve(List> matrix) { - // O(N*M) time | O(1) space - int col0 = 1, rows = matrix.size(), cols = matrix.get(0).size(); - - for (int i = 0; i < rows; i++) { - if (matrix.get(i).get(0) == 0) col0 = 0; - for (int j = 1; j < cols; j++) { - if (matrix.get(i).get(j) == 0) { - matrix.get(i).set(0, 0); - matrix.get(0).set(j, 0); - } - } - } - //traverse reverse order to avoid override of values - for (int i = rows - 1; i > -1; i--) { - for (int j = cols - 1; j > 0; j--) { - if (matrix.get(i).get(0) == 0 || matrix.get(0).get(j) == 0) { - matrix.get(i).set(j, 0); - } - } - if (col0 == 0) matrix.get(rows).set(0, 0); - } - - } -} diff --git a/Arrays/smallest_difference.java b/Arrays/smallest_difference.java deleted file mode 100644 index 4c2a21c5..00000000 --- a/Arrays/smallest_difference.java +++ /dev/null @@ -1,55 +0,0 @@ -import java.util.Arrays; - -/** - * - - Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from the first array in the first position. - - Note that the absolute difference of two integers is the distance between them on the real number line. For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. - - You can assume that there will only be one pair of numbers with the smallest difference. - Sample Input - - arrayOne = [-1, 5, 10, 20, 28, 3] - arrayTwo = [26, 134, 135, 15, 17] - - Sample Output - - [28, 26] - - - */ -public class SmallestDifference { - public static void main(String[] args) { - int[] arrayOne = {-1, 5, 10, 20, 28, 3}; - int[] arrayTwo = {26, 134, 135, 15, 17}; - int[] result = solve(arrayOne, arrayTwo); - System.out.println(Arrays.toString(result)); - } - public static int[] solve(int[] arrayOne, int[] arrayTwo) { - // O(n(log(n) + m(log(m)) time | O(1) space - Arrays.sort(arrayOne); - Arrays.sort(arrayTwo); - int idxOne = 0; - int idxTwo = 0; - int smallest = Integer.MAX_VALUE; - int current; - int[] smallestPair = new int[2]; - while (idxOne < arrayOne.length && idxTwo < arrayTwo.length) { - int firstNum = arrayOne[idxOne]; - int secondNum = arrayTwo[idxTwo]; - if (firstNum < secondNum) { - current = secondNum - firstNum; - idxOne++; - } else if (secondNum < firstNum) { - current = firstNum - secondNum; - idxTwo++; - } else return new int[]{firstNum, secondNum}; - if (current < smallest) { - smallest = current; - smallestPair = new int[]{firstNum, secondNum}; - } - } - return smallestPair; - } -} diff --git a/Arrays/subarray_with_least_avg.java b/Arrays/subarray_with_least_avg.java deleted file mode 100644 index 48ae6199..00000000 --- a/Arrays/subarray_with_least_avg.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Given an array of size N, find the subarray of size K with the least average. - * - * - * - * Problem Constraints - * 1<=k<=N<=1e5 - * -1e5<=A[i]<=1e5 - * - * - * Input Format - * First argument contains an array A of integers of size N. - * Second argument contains integer k. - * - * - * Output Format - * Return the index of the first element of the subarray of size k that has least average. - * Array indexing starts from 0. - * - * - * Example Input - * Input 1: - * A=[3, 7, 90, 20, 10, 50, 40] - * B=3 - * Input 2: - * - * A=[3, 7, 5, 20, -10, 0, 12] - * B=2 - * - * - * Example Output - * Output 1: - * 3 - * Output 2: - * - * 4 - * - * - * Example Explanation - * Explanation 1: - * Subarray between indexes 3 and 5 - * The subarray {20, 10, 50} has the least average - * among all subarrays of size 3. - * Explanation 2: - * - * Subarray between [4, 5] has minimum average - */ - -package SlidingWindow; - -public class SubArrayWithLeastAverage { - public static void main(String[] args) { -// int[] arr = {3, 7, 90, 20, -10, 0, 12}; - int[] arr = {431, 313, 53, 251, 105, 423, 326, 297, - 218, 89, 394, 365, 348, 474, 157, 262, 33, 187, - 67, 79, 495, 199, 175, 228, 27, 305, 496, 331, - 40, 98, 405, 221, 327, 488, 252, 73, 218, 152, - 313, 274, 195, 353, 225, 292, 426, 257, 418, - 364, 344, 349, 181}; - int size = 12; - int ans = solve(arr, size); - System.out.println(ans); - } - public static int solve(int[] arr, int size) { - // O(N) time | O(1) space - int currentSum = 0; - int idx = 0; - int len = arr.length; - - // sliding window - for (int i = 0; i < size; i++) - currentSum += arr[i]; - - int startIdx = 1; - int endIdx = size; - int minSum = currentSum; - // slide remaining windows - while (endIdx < len) { - currentSum = currentSum + arr[endIdx] - arr[startIdx - 1]; - if (currentSum < minSum) { - minSum = currentSum; - idx = startIdx; - } - startIdx++; - endIdx++; - } - return idx; - } -} From b8ee0cdb1c80d76207b71c6ee7a23c813103be7e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:26:16 +0530 Subject: [PATCH 0447/1894] add approach --- Strings/group_anagram.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Strings/group_anagram.py b/Strings/group_anagram.py index d451653f..d114cc3f 100644 --- a/Strings/group_anagram.py +++ b/Strings/group_anagram.py @@ -13,6 +13,11 @@ # Example 3: # Input: strs = ["a"] # Output: [["a"]] +# Approach: +# 1. Go through the list of words +# 2. Sort each word. All annograms of the word would look the same being sorted. +# 3. Find matching bucket in map and put the word to it +# 4. When finished, convert the map to vector of vectors and return it From 28358d67ddb97540abc4e58bd5740ba957e2ce0d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:26:19 +0530 Subject: [PATCH 0448/1894] add approach --- Strings/group_anagrams.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Strings/group_anagrams.java b/Strings/group_anagrams.java index f3e240b9..a07b1a33 100644 --- a/Strings/group_anagrams.java +++ b/Strings/group_anagrams.java @@ -17,6 +17,11 @@ Input: strs = ["a"] Output: [["a"]] */ +// Approach: +// 1. Go through the list of words +// 2. Sort each word. All annograms of the word would look the same being sorted. +// 3. Find matching bucket in map and put the word to it +// 4. When finished, convert the map to vector of vectors and return it package Strings; From a33e2fd487b1bd2580e48a15ee3cb1e935a53efe Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:26:22 +0530 Subject: [PATCH 0449/1894] add approach --- Strings/group_anagrams.js | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Strings/group_anagrams.js b/Strings/group_anagrams.js index 20f99963..3159e6df 100644 --- a/Strings/group_anagrams.js +++ b/Strings/group_anagrams.js @@ -18,17 +18,22 @@ * @param {string[]} strs * @return {string[][]} */ +// Approach: +// 1. Go through the list of words +// 2. Sort each word. All annograms of the word would look the same being sorted. +// 3. Find matching bucket in map and put the word to it +// 4. When finished, convert the map to vector of vectors and return it + function groupAnagrams(strs) { - let result = {} + let result = {}; - for (let i of strs){ - let anagram = i.split("").sort().join(""); - if (result[anagram]) { - result[anagram].push(i); - } else { - result[anagram] = [i]; - } + for (let i of strs) { + let anagram = i.split("").sort().join(""); + if (result[anagram]) { + result[anagram].push(i); + } else { + result[anagram] = [i]; } - return Object.values(result); - -}; \ No newline at end of file + } + return Object.values(result); +} From bd03a5d3001e94a957ddea8cf213d64bd92f4941 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:30:02 +0530 Subject: [PATCH 0450/1894] add comments --- Strings/check_anagrams.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Strings/check_anagrams.java b/Strings/check_anagrams.java index 59abfa74..3cea21f7 100644 --- a/Strings/check_anagrams.java +++ b/Strings/check_anagrams.java @@ -56,12 +56,13 @@ public static int solve(String string1, String string2) { int[] freq1 = new int[26]; int[] freq2 = new int[26]; - + // build freq array and store count for each letter for (int i = 0; i < string1.length(); i++) { freq1[string1.charAt(i) - 'a']++; freq2[string2.charAt(i) - 'a']++; } - + // compare if count of each letter + // if mismatch occurs then return 0 for (int i = 0; i < 26; i++) { if (freq1[i] != freq2[i]) return 0; } From 1cb328b8db4ab6ae5fe73249e2c7226531f4b2d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:31:22 +0530 Subject: [PATCH 0451/1894] update comments --- Strings/count_matches_in_tournament.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Strings/count_matches_in_tournament.cpp b/Strings/count_matches_in_tournament.cpp index a35c4846..963aadac 100644 --- a/Strings/count_matches_in_tournament.cpp +++ b/Strings/count_matches_in_tournament.cpp @@ -28,17 +28,17 @@ 1 <= n <= 200 */ -// In case of even simply divide number by 2 ad add result -// In case of add simply divide number by 2 ad add result and increase n by 1 class Solution { public: int numberOfMatches(int n) { int res = 0; while(n > 1){ + // In case of even simply divide number by 2 ad add result if(n % 2 == 0){ n = n / 2; res += n; } + // In case of odd simply divide number by 2 ad add result and increase n by 1 if(n % 2 == 1){ n = n / 2; res += n; From d13e8baa67cc9a6c5784c92ca7b7f556504d78e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:33:04 +0530 Subject: [PATCH 0452/1894] add comment --- Strings/is_ palindrome.js | 56 +++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/Strings/is_ palindrome.js b/Strings/is_ palindrome.js index 4cbf225c..80f863c8 100644 --- a/Strings/is_ palindrome.js +++ b/Strings/is_ palindrome.js @@ -2,42 +2,42 @@ // Two pointer approach function isPalindromeTwoPointer(inputString) { - var string = inputString.trim().toLowerCase(); - - if (string == "") { - return false; - } - - var leftIndex = 0; - var rightIndex = string.length - 1; - - while (leftIndex < rightIndex) { - if (string[leftIndex] !== string[rightIndex]) { - return false; - } - leftIndex++; - rightIndex--; + var string = inputString.trim().toLowerCase(); + + if (string == "") { + return false; + } + + var leftIndex = 0; + var rightIndex = string.length - 1; + // compare start and end position + // if mismatch occurs then return false + // if mismatch doesnot occur then increment start pointer and decrement end pointer till they meet + while (leftIndex < rightIndex) { + if (string[leftIndex] !== string[rightIndex]) { + return false; } - return true; + leftIndex++; + rightIndex--; + } + return true; } // Reverse String approach function isPalindrome(inputString) { - var stringArray = inputString.trim().toLowerCase().split(""); + var stringArray = inputString.trim().toLowerCase().split(""); - var reverseString = ""; + var reverseString = ""; - for (i = stringArray.length - 1; i >= 0; i--) { - reverseString += stringArray[i]; - } + for (i = stringArray.length - 1; i >= 0; i--) { + reverseString += stringArray[i]; + } - if ( - inputString.trim().toLowerCase() == reverseString.trim().toLowerCase() - ) { - return true; - } else { - return false; - } + if (inputString.trim().toLowerCase() == reverseString.trim().toLowerCase()) { + return true; + } else { + return false; + } } // Driver code From a699cab95f5d40403917f32616bc724b00d1e68a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:35:33 +0530 Subject: [PATCH 0453/1894] add formatting --- Strings/Longest_palindromic_substring.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Strings/Longest_palindromic_substring.py b/Strings/Longest_palindromic_substring.py index 429e0808..f30871df 100644 --- a/Strings/Longest_palindromic_substring.py +++ b/Strings/Longest_palindromic_substring.py @@ -23,21 +23,21 @@ class Solution: def __init__(self): self.max_length = -1 self.max_palindrome = "" - def CheckLeftRight(self,s,index,value): - low,high = index,index - if(value=="even"): - high=index+1 - while(low>=0 and highself.max_length): - self.max_length = high-low+1 - self.max_palindrome = s[low:high+1] - low-=1 - high+=1 + def CheckLeftRight(self, s, index, value): + low, high = index, index + if(value == "even"): + high = index + 1 + while(low >= 0 and high < len(s) and s[low] == s[high]): + if(high - low + 1 > self.max_length): + self.max_length = high - low + 1 + self.max_palindrome = s[low:high + 1] + low -= 1 + high += 1 def longestPalindrome(self, s: str) -> str: for i in range(len(s)): #odd values - Solution.CheckLeftRight(self,s,i,"odd") + Solution.CheckLeftRight(self, s, i, "odd") #Even values - Solution.CheckLeftRight(self,s,i,"even") + Solution.CheckLeftRight(self, s, i, "even") return self.max_palindrome \ No newline at end of file From 5887646c060def27f4d6519f2c1ba470f052ec3e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:40:20 +0530 Subject: [PATCH 0454/1894] add comment --- Strings/reverse_string.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Strings/reverse_string.go b/Strings/reverse_string.go index 3464d3b4..a2d228cd 100644 --- a/Strings/reverse_string.go +++ b/Strings/reverse_string.go @@ -5,7 +5,9 @@ package main import "fmt" func reverse(s string) string { + // since strings are immutable in go, we make array of runes chars := []rune(s) + // swap start and end position characters for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } From 462ae38c0dd1346457ece0e4b51b69ec56a5a5ae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Mar 2023 22:42:57 +0530 Subject: [PATCH 0455/1894] update comment --- Strings/reverse_string.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Strings/reverse_string.go b/Strings/reverse_string.go index a2d228cd..514d4c44 100644 --- a/Strings/reverse_string.go +++ b/Strings/reverse_string.go @@ -2,6 +2,7 @@ // Program Author : Abhisek Kumar Gupta package main + import "fmt" func reverse(s string) string { @@ -11,6 +12,7 @@ func reverse(s string) string { for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } + // cast chars to string return string(chars) } From 8e6086eef7870b112cebaff611a8ed26146d567a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:43:29 +0530 Subject: [PATCH 0456/1894] rename directory --- .../BST_delete_from_bst.cpp | 0 .../BST_flatten_a_linked_list_from_a_tree.cpp | 0 .../BST_insert_into_bst.cpp | 0 .../BST_is_valid_bst.cpp | 0 Trees/{Binary_Search_Trees => Binary Search Trees}/BST_search.cpp | 0 Trees/{Binary_Search_Trees => Binary Search Trees}/bst.go | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename Trees/{Binary_Search_Trees => Binary Search Trees}/BST_delete_from_bst.cpp (100%) rename Trees/{Binary_Search_Trees => Binary Search Trees}/BST_flatten_a_linked_list_from_a_tree.cpp (100%) rename Trees/{Binary_Search_Trees => Binary Search Trees}/BST_insert_into_bst.cpp (100%) rename Trees/{Binary_Search_Trees => Binary Search Trees}/BST_is_valid_bst.cpp (100%) rename Trees/{Binary_Search_Trees => Binary Search Trees}/BST_search.cpp (100%) rename Trees/{Binary_Search_Trees => Binary Search Trees}/bst.go (100%) diff --git a/Trees/Binary_Search_Trees/BST_delete_from_bst.cpp b/Trees/Binary Search Trees/BST_delete_from_bst.cpp similarity index 100% rename from Trees/Binary_Search_Trees/BST_delete_from_bst.cpp rename to Trees/Binary Search Trees/BST_delete_from_bst.cpp diff --git a/Trees/Binary_Search_Trees/BST_flatten_a_linked_list_from_a_tree.cpp b/Trees/Binary Search Trees/BST_flatten_a_linked_list_from_a_tree.cpp similarity index 100% rename from Trees/Binary_Search_Trees/BST_flatten_a_linked_list_from_a_tree.cpp rename to Trees/Binary Search Trees/BST_flatten_a_linked_list_from_a_tree.cpp diff --git a/Trees/Binary_Search_Trees/BST_insert_into_bst.cpp b/Trees/Binary Search Trees/BST_insert_into_bst.cpp similarity index 100% rename from Trees/Binary_Search_Trees/BST_insert_into_bst.cpp rename to Trees/Binary Search Trees/BST_insert_into_bst.cpp diff --git a/Trees/Binary_Search_Trees/BST_is_valid_bst.cpp b/Trees/Binary Search Trees/BST_is_valid_bst.cpp similarity index 100% rename from Trees/Binary_Search_Trees/BST_is_valid_bst.cpp rename to Trees/Binary Search Trees/BST_is_valid_bst.cpp diff --git a/Trees/Binary_Search_Trees/BST_search.cpp b/Trees/Binary Search Trees/BST_search.cpp similarity index 100% rename from Trees/Binary_Search_Trees/BST_search.cpp rename to Trees/Binary Search Trees/BST_search.cpp diff --git a/Trees/Binary_Search_Trees/bst.go b/Trees/Binary Search Trees/bst.go similarity index 100% rename from Trees/Binary_Search_Trees/bst.go rename to Trees/Binary Search Trees/bst.go From d3aeecae58cde1035184fa4aa86b83f4e9af5c3d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:44:16 +0530 Subject: [PATCH 0457/1894] rename directory --- Trees/{Binary_Trees => Binary Trees}/binary_tree.go | 0 Trees/{Binary_Trees => Binary Trees}/binary_tree_bfs.cpp | 0 .../binary_tree_bfs_print_level_by_level.cpp | 0 .../binary_tree_build_tree_preorder.cpp | 0 .../{Binary_Trees => Binary Trees}/binary_tree_compute_height.cpp | 0 Trees/{Binary_Trees => Binary Trees}/binary_tree_count_nodes.cpp | 0 .../binary_tree_create_tree_from_preorder_and_inorder.cpp | 0 .../binary_tree_diameter_of_a_tree.cpp | 0 .../binary_tree_diameter_of_a_tree_optimal.cpp | 0 .../binary_tree_inorder_traversal.cpp | 0 .../binary_tree_is_height_balanced.cpp | 0 .../binary_tree_level_order_traversal.cpp | 0 .../binary_tree_postorder_traversal.cpp | 0 .../binary_tree_preorder_traversal.cpp | 0 .../binary_tree_replace_parent_with_sum_of_child.cpp | 0 .../binary_tree_sum_of_all_nodes.cpp | 0 Trees/{Binary_Trees => Binary Trees}/dfs.go | 0 17 files changed, 0 insertions(+), 0 deletions(-) rename Trees/{Binary_Trees => Binary Trees}/binary_tree.go (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_bfs.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_bfs_print_level_by_level.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_build_tree_preorder.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_compute_height.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_count_nodes.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_create_tree_from_preorder_and_inorder.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_diameter_of_a_tree.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_diameter_of_a_tree_optimal.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_inorder_traversal.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_is_height_balanced.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_level_order_traversal.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_postorder_traversal.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_preorder_traversal.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_replace_parent_with_sum_of_child.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/binary_tree_sum_of_all_nodes.cpp (100%) rename Trees/{Binary_Trees => Binary Trees}/dfs.go (100%) diff --git a/Trees/Binary_Trees/binary_tree.go b/Trees/Binary Trees/binary_tree.go similarity index 100% rename from Trees/Binary_Trees/binary_tree.go rename to Trees/Binary Trees/binary_tree.go diff --git a/Trees/Binary_Trees/binary_tree_bfs.cpp b/Trees/Binary Trees/binary_tree_bfs.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_bfs.cpp rename to Trees/Binary Trees/binary_tree_bfs.cpp diff --git a/Trees/Binary_Trees/binary_tree_bfs_print_level_by_level.cpp b/Trees/Binary Trees/binary_tree_bfs_print_level_by_level.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_bfs_print_level_by_level.cpp rename to Trees/Binary Trees/binary_tree_bfs_print_level_by_level.cpp diff --git a/Trees/Binary_Trees/binary_tree_build_tree_preorder.cpp b/Trees/Binary Trees/binary_tree_build_tree_preorder.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_build_tree_preorder.cpp rename to Trees/Binary Trees/binary_tree_build_tree_preorder.cpp diff --git a/Trees/Binary_Trees/binary_tree_compute_height.cpp b/Trees/Binary Trees/binary_tree_compute_height.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_compute_height.cpp rename to Trees/Binary Trees/binary_tree_compute_height.cpp diff --git a/Trees/Binary_Trees/binary_tree_count_nodes.cpp b/Trees/Binary Trees/binary_tree_count_nodes.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_count_nodes.cpp rename to Trees/Binary Trees/binary_tree_count_nodes.cpp diff --git a/Trees/Binary_Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp b/Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp rename to Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp diff --git a/Trees/Binary_Trees/binary_tree_diameter_of_a_tree.cpp b/Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_diameter_of_a_tree.cpp rename to Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp diff --git a/Trees/Binary_Trees/binary_tree_diameter_of_a_tree_optimal.cpp b/Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_diameter_of_a_tree_optimal.cpp rename to Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp diff --git a/Trees/Binary_Trees/binary_tree_inorder_traversal.cpp b/Trees/Binary Trees/binary_tree_inorder_traversal.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_inorder_traversal.cpp rename to Trees/Binary Trees/binary_tree_inorder_traversal.cpp diff --git a/Trees/Binary_Trees/binary_tree_is_height_balanced.cpp b/Trees/Binary Trees/binary_tree_is_height_balanced.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_is_height_balanced.cpp rename to Trees/Binary Trees/binary_tree_is_height_balanced.cpp diff --git a/Trees/Binary_Trees/binary_tree_level_order_traversal.cpp b/Trees/Binary Trees/binary_tree_level_order_traversal.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_level_order_traversal.cpp rename to Trees/Binary Trees/binary_tree_level_order_traversal.cpp diff --git a/Trees/Binary_Trees/binary_tree_postorder_traversal.cpp b/Trees/Binary Trees/binary_tree_postorder_traversal.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_postorder_traversal.cpp rename to Trees/Binary Trees/binary_tree_postorder_traversal.cpp diff --git a/Trees/Binary_Trees/binary_tree_preorder_traversal.cpp b/Trees/Binary Trees/binary_tree_preorder_traversal.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_preorder_traversal.cpp rename to Trees/Binary Trees/binary_tree_preorder_traversal.cpp diff --git a/Trees/Binary_Trees/binary_tree_replace_parent_with_sum_of_child.cpp b/Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_replace_parent_with_sum_of_child.cpp rename to Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp diff --git a/Trees/Binary_Trees/binary_tree_sum_of_all_nodes.cpp b/Trees/Binary Trees/binary_tree_sum_of_all_nodes.cpp similarity index 100% rename from Trees/Binary_Trees/binary_tree_sum_of_all_nodes.cpp rename to Trees/Binary Trees/binary_tree_sum_of_all_nodes.cpp diff --git a/Trees/Binary_Trees/dfs.go b/Trees/Binary Trees/dfs.go similarity index 100% rename from Trees/Binary_Trees/dfs.go rename to Trees/Binary Trees/dfs.go From b4d6f0f9dcafd54454e1369f270dc3b20db4a493 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:45:01 +0530 Subject: [PATCH 0458/1894] add find closest value in bst --- .../BST_find_closest_value.go | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Trees/Binary Search Trees/BST_find_closest_value.go diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/BST_find_closest_value.go new file mode 100644 index 00000000..505bc9a3 --- /dev/null +++ b/Trees/Binary Search Trees/BST_find_closest_value.go @@ -0,0 +1,32 @@ +package main + +type BST struct { + Value int + + Left *BST + Right *BST +} + +func (tree *BST) FindClosestValue(target int) int { + // Write your code here. + return tree.findClosestValue(target, tree.Value) +} + +func (tree *BST) findClosestValue(target, closest int) int { + if absDiff(target, closest) > absDiff(target, tree.Value) { + closest = tree.Value + } + if target < tree.Value && tree.Left != nil { + return tree.Left.findClosestValue(target, closest) + } else if target > tree.Value && tree.Right != nil { + return tree.Right.findClosestValue(target, closest) + } + return closest +} + +func absDiff(a, b int) int { + if a > b { + return a - b + } + return b - a +} From 6925c5d48c76965c206daadb770089dba845afb0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:47:02 +0530 Subject: [PATCH 0459/1894] add description --- Trees/Binary Search Trees/BST_find_closest_value.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/BST_find_closest_value.go index 505bc9a3..1b599637 100644 --- a/Trees/Binary Search Trees/BST_find_closest_value.go +++ b/Trees/Binary Search Trees/BST_find_closest_value.go @@ -1,3 +1,15 @@ +/* + Write a function that takes in a Binary Search Tree (BST) and a target integer + value and returns the closest value to that target value contained in the BST. +Sample Input : + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 +*/ package main type BST struct { From 6918c835d2d747066f648a2083573a0637c83e8f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:47:21 +0530 Subject: [PATCH 0460/1894] add sample io --- Trees/Binary Search Trees/BST_find_closest_value.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/BST_find_closest_value.go index 1b599637..a5cca3d5 100644 --- a/Trees/Binary Search Trees/BST_find_closest_value.go +++ b/Trees/Binary Search Trees/BST_find_closest_value.go @@ -1,15 +1,17 @@ /* Write a function that takes in a Binary Search Tree (BST) and a target integer value and returns the closest value to that target value contained in the BST. -Sample Input : - 10 + +Sample Input : 12 + 10 / \ 5 15 / \ / \ 2 5 13 22 / \ 1 14 -*/ +Output : 13 + */ package main type BST struct { From 19a6887a6fb1708628af48cd6247641f1822c8cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:48:14 +0530 Subject: [PATCH 0461/1894] add time and space complexity --- Trees/Binary Search Trees/BST_find_closest_value.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/BST_find_closest_value.go index a5cca3d5..0204b733 100644 --- a/Trees/Binary Search Trees/BST_find_closest_value.go +++ b/Trees/Binary Search Trees/BST_find_closest_value.go @@ -3,6 +3,7 @@ value and returns the closest value to that target value contained in the BST. Sample Input : 12 + 10 / \ 5 15 @@ -11,7 +12,12 @@ Sample Input : 12 / \ 1 14 Output : 13 - */ + + Time and Space complexity: + + Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST + Worst: O(n) time | O(1) space - where n is the number of nodes in the BST +*/ package main type BST struct { From 51b66fec3cb3eff6b22937b6847c8f42a3a1fd49 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:50:10 +0530 Subject: [PATCH 0462/1894] add comments --- Trees/Binary Search Trees/BST_find_closest_value.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/BST_find_closest_value.go index 0204b733..0c09b8bf 100644 --- a/Trees/Binary Search Trees/BST_find_closest_value.go +++ b/Trees/Binary Search Trees/BST_find_closest_value.go @@ -28,7 +28,7 @@ type BST struct { } func (tree *BST) FindClosestValue(target int) int { - // Write your code here. + // call helper function return tree.findClosestValue(target, tree.Value) } @@ -36,9 +36,11 @@ func (tree *BST) findClosestValue(target, closest int) int { if absDiff(target, closest) > absDiff(target, tree.Value) { closest = tree.Value } + // look for target in left sub tree if target < tree.Value && tree.Left != nil { return tree.Left.findClosestValue(target, closest) } else if target > tree.Value && tree.Right != nil { + // // look for target in right sub tree return tree.Right.findClosestValue(target, closest) } return closest From c9f1baf21fda8a227fdb69da6093d251af20d750 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:51:31 +0530 Subject: [PATCH 0463/1894] add branch sum --- Trees/Binary Trees/branch_sum.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Trees/Binary Trees/branch_sum.go diff --git a/Trees/Binary Trees/branch_sum.go b/Trees/Binary Trees/branch_sum.go new file mode 100644 index 00000000..3d478b22 --- /dev/null +++ b/Trees/Binary Trees/branch_sum.go @@ -0,0 +1,26 @@ +package main + +// This is the struct of the input root. Do not edit it. +type BinaryTree struct { + Value int + Left *BinaryTree + Right *BinaryTree +} + +func BranchSums(root *BinaryTree) []int { + sums := []int{} + calculateBranchSums(root, 0, &sums) + return sums +} + +func calculateBranchSums(node *BinaryTree, runningSum int, sums *[]int) { + if node == nil { + return + } + runningSum += node.Value + if node.Left == nil && node.Right == nil { + *sums = append(*sums, runningSum) + } + calculateBranchSums(node.Left, runningSum, sums) + calculateBranchSums(node.Right, runningSum, sums) +} \ No newline at end of file From 7d51e14ab29385da75a9771c60e9a89f512c9c95 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:52:43 +0530 Subject: [PATCH 0464/1894] add description --- Trees/Binary Trees/branch_sum.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/branch_sum.go b/Trees/Binary Trees/branch_sum.go index 3d478b22..8325446d 100644 --- a/Trees/Binary Trees/branch_sum.go +++ b/Trees/Binary Trees/branch_sum.go @@ -1,6 +1,14 @@ +/* + Write a function that takes in a Binary Tree and returns a list of its branch + sums ordered from leftmost branch sum to rightmost branch sum. + + A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree + branch is a path of nodes in a tree that starts at the root node and ends at + any leaf node. + +*/ package main -// This is the struct of the input root. Do not edit it. type BinaryTree struct { Value int Left *BinaryTree From 4460d906e6d3b905608f45d0a5952ffc779736de Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:53:43 +0530 Subject: [PATCH 0465/1894] add sample io --- Trees/Binary Trees/branch_sum.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Trees/Binary Trees/branch_sum.go b/Trees/Binary Trees/branch_sum.go index 8325446d..ba0f64de 100644 --- a/Trees/Binary Trees/branch_sum.go +++ b/Trees/Binary Trees/branch_sum.go @@ -6,6 +6,16 @@ branch is a path of nodes in a tree that starts at the root node and ends at any leaf node. + Sample INput: + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + / \ / + 8 9 10 + + Output: [15, 16, 18, 10, 11] length of output will be always total number of leaves */ package main From e10b2ef2920d022f5ea675e37ce77eefbf8b586d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Mar 2023 20:55:20 +0530 Subject: [PATCH 0466/1894] add approach --- Trees/Binary Trees/branch_sum.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Trees/Binary Trees/branch_sum.go b/Trees/Binary Trees/branch_sum.go index ba0f64de..2288f1bf 100644 --- a/Trees/Binary Trees/branch_sum.go +++ b/Trees/Binary Trees/branch_sum.go @@ -16,6 +16,7 @@ 8 9 10 Output: [15, 16, 18, 10, 11] length of output will be always total number of leaves + Time and Space complexity : O(n) time | O(n) space - where n is the number of nodes in the Binary Tree */ package main @@ -30,7 +31,15 @@ func BranchSums(root *BinaryTree) []int { calculateBranchSums(root, 0, &sums) return sums } +/* +As you recursively traverse the tree, if you reach a leaf node +(a node with no "left" or "right" Binary Tree nodes), +add the relevant running sum that you've calculated to a list of +sums (which you'll also have to pass to the recursive function). +If you reach a node that isn't a leaf node, keep recursively traversing +its children nodes, passing the correctly updated running sum to them. +*/ func calculateBranchSums(node *BinaryTree, runningSum int, sums *[]int) { if node == nil { return From d64dbe3189cbbbcecacfd93627efa65606959f6b Mon Sep 17 00:00:00 2001 From: Alec Swift Date: Wed, 15 Mar 2023 22:46:29 -0700 Subject: [PATCH 0467/1894] Add heap_sort.py file --- sorting/heap_sort.py | 50 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 sorting/heap_sort.py diff --git a/sorting/heap_sort.py b/sorting/heap_sort.py new file mode 100644 index 00000000..69dcdfb5 --- /dev/null +++ b/sorting/heap_sort.py @@ -0,0 +1,50 @@ +""" +Sorts a list by converting the list to a max heap which by definition contains the +largest element at the root node which is the first element of the list. Then the +function exchanges the first element with the last element of the list and heapifies +the root node to bring the largest element of the remaining list back into the first +position. The function continues this operation n-1 (n = length of the list) times +at which point the list is sorted. + +Time complexity: O(n*log(n)) +""" + +def main(): + an_array = [-5, 4, 0, -1, 2, 4, 6, 1, 3, -10, 1, 2] + heap_sort(an_array) + print(an_array) + +def heap_sort(arr: list[int]) -> None: + heap_size = len(arr) + build_max_heap(arr, heap_size) + source_idx = 0 + for dest_idx in range(len(arr) - 1, 0, -1): + arr[source_idx], arr[dest_idx] = arr[dest_idx], arr[source_idx] + heap_size -= 1 + max_heapify(arr, 0, heap_size) + +def build_max_heap(arr: list[int], heap_size: int) -> None: + """Modifies the input array into a max heap. A tree binary tree structure in every node + satisfies the property: parent node > left node and parent node > right node""" + for idx in range((heap_size // 2) - 1, -1, -1): + max_heapify(arr, idx, heap_size) + +def max_heapify(arr: list[int], idx: int, heap_size: int) -> None: + """ + A recursive function that recursively modifies sub roots + of the tree indicated by the idx into a max heap + """ + left_idx = idx + 1 + right_idx = idx + 2 + if left_idx < heap_size and arr[idx] < arr[left_idx]: + largest = left_idx + else: + largest = idx + if right_idx < heap_size and arr[largest] < arr[right_idx]: + largest = right_idx + if largest != idx: + arr[idx], arr[largest] = arr[largest], arr[idx] + return max_heapify(arr, largest, heap_size) + +if __name__ == "__main__": + main() \ No newline at end of file From 3f9842822dc8eac6d30adb8260aa8c74131285a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Mar 2023 23:18:10 +0530 Subject: [PATCH 0468/1894] add level order traversal of binary tree in go --- Trees/Binary Trees/binary_tree_level_order.go | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_level_order.go diff --git a/Trees/Binary Trees/binary_tree_level_order.go b/Trees/Binary Trees/binary_tree_level_order.go new file mode 100644 index 00000000..7791c772 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_level_order.go @@ -0,0 +1,41 @@ +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Level order traversal is defined as follows: +// 1 Visit the root. +// 2 While traversing level 􀝈, keep all the elements at level 􀝈 + 1 in queue. +// 3 Go to the next level and visit all the nodes at that level. +// 4 Repeat this until all levels are completed. +// The nodes of the tree are visited in the order: [1] [2 3] [ 4 5 6 7] +// Time Complexity: O(n), Space Complexity: O(n) In the worst case, all the nodes on the entire last level could be in the queue. +func LevelOrder(root *BinaryTreeNode) [][]int { + if root == nil { + return [][]int{} + } + // Data from each level is being returned as a separate list + var result [][]int + queue := []*BinaryTreeNode{root} + for len(queue) > 0 { + qlen := len(queue) + var level []int + for i:= 0; i < qlen; i++ { + node := queue[0] + level = append(level, node.data) + queue = queue[1:] + // if there are left children then append them in queue + if node.left != nil { + queue = append(queue, node.left) + } + // if there are right children then append them in queue + if node.right != nil { + queue = append(queue, node.right) + } + } + } + return result +} From 51f39db35eb28cbd6d97c466d369dbc9d1d3291f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Mar 2023 23:20:13 +0530 Subject: [PATCH 0469/1894] add remove leaf nodes in go --- .../binary_tree_remove_leaf_nodes.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_remove_leaf_nodes.go diff --git a/Trees/Binary Trees/binary_tree_remove_leaf_nodes.go b/Trees/Binary Trees/binary_tree_remove_leaf_nodes.go new file mode 100644 index 00000000..7c29aaf7 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_remove_leaf_nodes.go @@ -0,0 +1,26 @@ +// Remove leaf nodes +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: recurse both left and right subtree and check if the node doesn't have +// left and right children +func RemoveLeafNodes(root *BinaryTreeNode) *BinaryTreeNode { + if root == nil { + return root + } + // if it doesnt have left and right children then delete it + if root.left == nil && root.right == nil { + root = nil + return root + } else { // recurse to left and right subtree + root.left = RemoveLeafNodes(root.left) + root.right = RemoveLeafNodes(root.right) + } + return root +} \ No newline at end of file From 81a60fa2b4aa0856cc9b70ee4358a8dd55803467 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Mar 2023 23:22:43 +0530 Subject: [PATCH 0470/1894] add invert binary tree --- Trees/Binary Trees/binary_tree_invert.go | 32 ++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_invert.go diff --git a/Trees/Binary Trees/binary_tree_invert.go b/Trees/Binary Trees/binary_tree_invert.go new file mode 100644 index 00000000..ff5ae6b7 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_invert.go @@ -0,0 +1,32 @@ +// Invert Binary tree +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: The inverse of an empty tree is an empty tree +// The inverse of a tree with root r, and subtrees right and left is a tree with +// root, whose right subtree is the inverse of left and whoose left subtree +// is the inverse of right +func InvertTree(root *BinaryTreeNode) *BinaryTreeNode { + if root != nil { + root.left, root.right = InvertTree(root.right), InvertTree(root.left) + } + return root +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Method2 : swap pointers +func InvertTree2(root *BinaryTreeNode) *BinaryTreeNode { + if root == nil { + return root + } + // swap the pointers in this node + root.left, root.right = root.right, root.left + InvertTree(root.left) + InvertTree(root.right) + return root +} From eb12a80647decf08e1267c7f324dacb66ab1fb81 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Mar 2023 23:23:03 +0530 Subject: [PATCH 0471/1894] update time and space complexity --- Trees/Binary Trees/binary_tree.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree.go b/Trees/Binary Trees/binary_tree.go index 0b2ce78c..c88df663 100644 --- a/Trees/Binary Trees/binary_tree.go +++ b/Trees/Binary Trees/binary_tree.go @@ -305,7 +305,7 @@ func InvertTree(root *BinaryTreeNode) *BinaryTreeNode { return root } -// Time Complexity: O(􀝊). Space Complexity: O(􀝊). +// Time Complexity: O(n). Space Complexity: O(n). // Method2 : swap pointers func InvertTree2(root *BinaryTreeNode) *BinaryTreeNode { if root == nil { From 704b66ffa4f97e8d24dbd008df49088e62fdf18e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Mar 2023 23:25:24 +0530 Subject: [PATCH 0472/1894] add find height of binary tree --- Trees/Binary Trees/binary_tree_height.go | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_height.go diff --git a/Trees/Binary Trees/binary_tree_height.go b/Trees/Binary Trees/binary_tree_height.go new file mode 100644 index 00000000..8ec43847 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_height.go @@ -0,0 +1,27 @@ +// Binary tree Find height +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: Recursively calculate height of left and right subtrees of a node +// and assign height to the node as max of heights of two children + 1 +func Height(root *BinaryTreeNode) int { + if root == nil { + return 0 + } else { + // compute depth of each subtree + leftHeight := Height(root.left) + rightHeight := Height(root.right) + if leftHeight > rightHeight { + return leftHeight + 1 + } else { + return rightHeight + 1 + } + + } +} \ No newline at end of file From a169a9253f02ab5e5a1e7aea645247152ee6031e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:14:44 +0530 Subject: [PATCH 0473/1894] add size of binary tree with and without recursion --- .../binary_tree_calculate_size.go | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_calculate_size.go diff --git a/Trees/Binary Trees/binary_tree_calculate_size.go b/Trees/Binary Trees/binary_tree_calculate_size.go new file mode 100644 index 00000000..5fb3fe4e --- /dev/null +++ b/Trees/Binary Trees/binary_tree_calculate_size.go @@ -0,0 +1,45 @@ +// Size of binary tree +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: calculate the size of left and right subtree recursively +// add 1 (curr node) and return to its parent +func Size(root *BinaryTreeNode) int { + if root == nil { + return 0 + } else { + return Size(root.left) + 1 + Size(root.right) + } +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: use level order traversal and count nodes +func SizeWithoutUsingRecursion(root *BinaryTreeNode) int { + if root == nil { + return 0 + } + var result int + queue := []*BinaryTreeNode{root} + for len(queue) > 0 { + qlen := len(queue) + //var level []int + for i := 0; i < qlen; i++ { + node := queue[0] + result++ + //level = append(level, node.data) + queue = queue[1:] + if node.left != nil { + queue = append(queue, node.left) + } + if node.right != nil { + queue = append(queue, node.right) + } + } + } + return result +} \ No newline at end of file From 1ae566f2f08628b478cffd6cbe273c8fd6ea62b1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:16:18 +0530 Subject: [PATCH 0474/1894] add find max in binary tree with and without recursion --- Trees/Binary Trees/binary_tree_finx_max.go | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_finx_max.go diff --git a/Trees/Binary Trees/binary_tree_finx_max.go b/Trees/Binary Trees/binary_tree_finx_max.go new file mode 100644 index 00000000..d86907b4 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_finx_max.go @@ -0,0 +1,59 @@ +// Find max in Binary tree +package main + +import "math" + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: find maximum in left sub tree, find maximum in right subtree +// compare them with root data and select the one which is giving the max value +// recursive appraoch +func FindMax(root *BinaryTreeNode) int { + max := math.MinInt32 + if root != nil { + rootVal := root.data + left := FindMax(root.left) + right := FindMax(root.right) + if left > max { + max = left + } else { + max = right + } + if rootVal > max { + max = rootVal + } + } + return max +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: Using level order traversal observe the elements data +func FindMaxWithoutRecursion(root *BinaryTreeNode) int { + max := math.MinInt32 + if root == nil { + return max + } + queue := []*BinaryTreeNode{root} + for len(queue) > 0 { + qlen := len(queue) + for i := 0; i < qlen; i++ { + node := queue[0] + if node.data > max { + max = node.data + } + queue = queue[1:] + if node.left != nil { + queue = append(queue, node.left) + } + if node.right != nil { + queue = append(queue, node.right) + } + } + } + return max +} \ No newline at end of file From db57fe95cab8e85d4ddb04adaa0e7669273845b2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:18:12 +0530 Subject: [PATCH 0475/1894] add search an element with and without recursion --- .../binary_tree_search_an_element.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_search_an_element.go diff --git a/Trees/Binary Trees/binary_tree_search_an_element.go b/Trees/Binary Trees/binary_tree_search_an_element.go new file mode 100644 index 00000000..a1c8dfca --- /dev/null +++ b/Trees/Binary Trees/binary_tree_search_an_element.go @@ -0,0 +1,56 @@ +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: recurse down the tree choose left or right branch by comparing data with each node's data +func SearchAnElement(root *BinaryTreeNode, data int) *BinaryTreeNode { + // base case empty tree + if root == nil { + return root + } else { + // if found return root + if data == root.data { + return root + } else { + // recurse down correct subtree + temp := SearchAnElement(root.left, data) + if temp != nil { + return temp + } else { + return SearchAnElement(root.right, data) + } + } + } +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: using level order traversal we can solve this problem, check whether +// the root data is equal to the element we want to search +func SearchAnElementWithoutRecursion(root *BinaryTreeNode, data int) *BinaryTreeNode { + if root == nil { + return root + } + queue := []*BinaryTreeNode{root} + for len(queue) > 0 { + qlen := len(queue) + for i := 0; i < qlen; i++ { + node := queue[0] + if data == node.data { + return node + } + queue = queue[1:] + if node.left != nil { + queue = append(queue, node.left) + } + if node.right != nil { + queue = append(queue, node.right) + } + } + } + return nil +} \ No newline at end of file From f0aba217699c6b8c3a4faf0e35b7bae40d3beb32 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:18:44 +0530 Subject: [PATCH 0476/1894] modify comments --- Trees/Binary Trees/binary_tree.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree.go b/Trees/Binary Trees/binary_tree.go index c88df663..4b6e9662 100644 --- a/Trees/Binary Trees/binary_tree.go +++ b/Trees/Binary Trees/binary_tree.go @@ -325,7 +325,7 @@ func DeleteTree(root *BinaryTreeNode) *BinaryTreeNode { if root == nil { return nil } - // deleet both subtrees + // delete both subtrees root.left = DeleteTree(root.left) root.right = DeleteTree(root.right) // delete current node after deleting subtrees From d0d74e3a95b88ccf80bbbb34ed93bc6c40589aa3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:19:45 +0530 Subject: [PATCH 0477/1894] add delete binary tree --- Trees/Binary Trees/binary_tree_delete.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_delete.go diff --git a/Trees/Binary Trees/binary_tree_delete.go b/Trees/Binary Trees/binary_tree_delete.go new file mode 100644 index 00000000..3ff0be59 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_delete.go @@ -0,0 +1,23 @@ +// Delete binary tree +package main + +type BinaryTreeNode struct { + left *BinaryTreeNode + data int + right *BinaryTreeNode +} + +// Time Complexity: O(n). Space Complexity: O(n). +// Approach: before deleting parent node, delete all its children nodes +// using post order traversal we can solve this problem +func DeleteTree(root *BinaryTreeNode) *BinaryTreeNode { + if root == nil { + return nil + } + // delete both subtrees + root.left = DeleteTree(root.left) + root.right = DeleteTree(root.right) + // delete current node after deleting subtrees + root = nil + return root +} \ No newline at end of file From 9130b6f489ee25e90d18e60973392e11539ed41d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:19:53 +0530 Subject: [PATCH 0478/1894] add description --- Trees/Binary Trees/binary_tree_search_an_element.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Trees/Binary Trees/binary_tree_search_an_element.go b/Trees/Binary Trees/binary_tree_search_an_element.go index a1c8dfca..142e6d53 100644 --- a/Trees/Binary Trees/binary_tree_search_an_element.go +++ b/Trees/Binary Trees/binary_tree_search_an_element.go @@ -1,3 +1,4 @@ +// Search an element in Binary tree package main type BinaryTreeNode struct { From 911d6380e3babc360a4f3ef5ebaa888dda91fce9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:20:45 +0530 Subject: [PATCH 0479/1894] refactor --- Trees/Binary Trees/binary_tree.go | 229 ------------------------------ 1 file changed, 229 deletions(-) diff --git a/Trees/Binary Trees/binary_tree.go b/Trees/Binary Trees/binary_tree.go index 4b6e9662..3e6280ac 100644 --- a/Trees/Binary Trees/binary_tree.go +++ b/Trees/Binary Trees/binary_tree.go @@ -23,7 +23,6 @@ package main import ( "fmt" - "math" "math/rand" ) @@ -138,219 +137,7 @@ func LevelOrder(root *BinaryTreeNode) [][]int { return result } -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: find maximum in left sub tree, find maximum in right subtree -// compare them with root data and select the one which is giving the max value -// recursive appraoch -func FindMax(root *BinaryTreeNode) int { - max := math.MinInt32 - if root != nil { - rootVal := root.data - left := FindMax(root.left) - right := FindMax(root.right) - if left > max { - max = left - } else { - max = right - } - if rootVal > max { - max = rootVal - } - } - return max -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: Using level order traversal observe the elements data -func FindMaxWithoutRecursion(root *BinaryTreeNode) int { - max := math.MinInt32 - if root == nil { - return max - } - queue := []*BinaryTreeNode{root} - for len(queue) > 0 { - qlen := len(queue) - for i := 0; i < qlen; i++ { - node := queue[0] - if node.data > max { - max = node.data - } - queue = queue[1:] - if node.left != nil { - queue = append(queue, node.left) - } - if node.right != nil { - queue = append(queue, node.right) - } - } - } - return max -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: recurse down the tree choose left or right branch by comparing data with each node's data -func SearchAnElement(root *BinaryTreeNode, data int) *BinaryTreeNode { - // base case empty tree - if root == nil { - return root - } else { - // if found return root - if data == root.data { - return root - } else { - // recurse down correct subtree - temp := SearchAnElement(root.left, data) - if temp != nil { - return temp - } else { - return SearchAnElement(root.right, data) - } - } - } -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: using level order traversal we can solve this problem, check whether -// the root data is equal to the element we want to search -func SearchAnElementWithoutRecursion(root *BinaryTreeNode, data int) *BinaryTreeNode { - if root == nil { - return root - } - queue := []*BinaryTreeNode{root} - for len(queue) > 0 { - qlen := len(queue) - for i := 0; i < qlen; i++ { - node := queue[0] - if data == node.data { - return node - } - queue = queue[1:] - if node.left != nil { - queue = append(queue, node.left) - } - if node.right != nil { - queue = append(queue, node.right) - } - } - } - return nil -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: calculate the size of left and right subtree recursively -// add 1 (curr node) and return to its parent -func Size(root *BinaryTreeNode) int { - if root == nil { - return 0 - } else { - return Size(root.left) + 1 + Size(root.right) - } -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: use level order traversal and count nodes -func SizeWithoutUsingRecursion(root *BinaryTreeNode) int { - if root == nil { - return 0 - } - var result int - queue := []*BinaryTreeNode{root} - for len(queue) > 0 { - qlen := len(queue) - //var level []int - for i := 0; i < qlen; i++ { - node := queue[0] - result++ - //level = append(level, node.data) - queue = queue[1:] - if node.left != nil { - queue = append(queue, node.left) - } - if node.right != nil { - queue = append(queue, node.right) - } - } - } - return result -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: Recursively calculate height of left and right subtrees of a node -// and assign height to the node as max of heights of two children + 1 -func Height(root *BinaryTreeNode) int { - if root == nil { - return 0 - } else { - // compute depth of each subtree - leftHeight := Height(root.left) - rightHeight := Height(root.right) - if leftHeight > rightHeight { - return leftHeight + 1 - } else { - return rightHeight + 1 - } - - } -} -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: The inverse of an empty tree is an empty tree -// The inverse of a tree with root r, and subtrees right and left is a tree with -// root, whose right subtree is the inverse of left and whoose left subtree -// is the inverse of right -func InvertTree(root *BinaryTreeNode) *BinaryTreeNode { - if root != nil { - root.left, root.right = InvertTree(root.right), InvertTree(root.left) - } - return root -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Method2 : swap pointers -func InvertTree2(root *BinaryTreeNode) *BinaryTreeNode { - if root == nil { - return root - } - // swap the pointers in this node - root.left, root.right = root.right, root.left - InvertTree(root.left) - InvertTree(root.right) - return root -} - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: before deleting parent node, delete all its children nodes -// using post order traversal we can solve this problem -func DeleteTree(root *BinaryTreeNode) *BinaryTreeNode { - if root == nil { - return nil - } - // delete both subtrees - root.left = DeleteTree(root.left) - root.right = DeleteTree(root.right) - // delete current node after deleting subtrees - root = nil - return root -} - - -// Time Complexity: O(n). Space Complexity: O(n). -// Approach: recurse both left and right subtree and check if the node doesn't have -// left and right children -func RemoveLeafNodes(root *BinaryTreeNode) *BinaryTreeNode { - if root == nil { - return root - } - // if it doesnt have left and right children then delete it - if root.left == nil && root.right == nil { - root = nil - return root - } else { // recurse to left and right subtree - root.left = RemoveLeafNodes(root.left) - root.right = RemoveLeafNodes(root.right) - } - return root -} func main() { t1 := NewBinaryTree(10, 1) @@ -360,20 +147,4 @@ func main() { fmt.Println() PostOrder(t1) fmt.Println() - msg := FindMax(t1) - fmt.Println(msg) - res := SearchAnElement(t1, 1) - fmt.Println(res) - size := Size(t1) - fmt.Println(size) - size = SizeWithoutUsingRecursion(t1) - fmt.Println("Size without recursion") - fmt.Println(size) - height := Height(t1) - fmt.Println(height) - invert := InvertTree(t1) - fmt.Println(invert) - deleteLeaf := RemoveLeafNodes(t1) - fmt.Println(deleteLeaf) - PreOrder(deleteLeaf) } \ No newline at end of file From 730bb9c99211228f46bbcd8fb7f50ce7f9234326 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:21:26 +0530 Subject: [PATCH 0480/1894] remove level order traversal --- Trees/Binary Trees/binary_tree.go | 34 ------------------------------- 1 file changed, 34 deletions(-) diff --git a/Trees/Binary Trees/binary_tree.go b/Trees/Binary Trees/binary_tree.go index 3e6280ac..03981c65 100644 --- a/Trees/Binary Trees/binary_tree.go +++ b/Trees/Binary Trees/binary_tree.go @@ -103,40 +103,6 @@ func PostOrder(root *BinaryTreeNode) { fmt.Printf("%d", root.data) } -// Level order traversal is defined as follows: -// 1 Visit the root. -// 2 While traversing level 􀝈, keep all the elements at level 􀝈 + 1 in queue. -// 3 Go to the next level and visit all the nodes at that level. -// 4 Repeat this until all levels are completed. -// The nodes of the tree are visited in the order: [1] [2 3] [ 4 5 6 7] -// Time Complexity: O(n), Space Complexity: O(n) In the worst case, all the nodes on the entire last level could be in the queue. -func LevelOrder(root *BinaryTreeNode) [][]int { - if root == nil { - return [][]int{} - } - // Data from each level is being returned as a separate list - var result [][]int - queue := []*BinaryTreeNode{root} - for len(queue) > 0 { - qlen := len(queue) - var level []int - for i:= 0; i < qlen; i++ { - node := queue[0] - level = append(level, node.data) - queue = queue[1:] - // if there are left children then append them in queue - if node.left != nil { - queue = append(queue, node.left) - } - // if there are right children then append them in queue - if node.right != nil { - queue = append(queue, node.right) - } - } - } - return result -} - func main() { From e4fd212bd05f46b7a944fd5ce649607c23503f6a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Mar 2023 22:25:39 +0530 Subject: [PATCH 0481/1894] rename file --- .../{binary_tree_finx_max.go => binary_tree_find_max.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trees/Binary Trees/{binary_tree_finx_max.go => binary_tree_find_max.go} (100%) diff --git a/Trees/Binary Trees/binary_tree_finx_max.go b/Trees/Binary Trees/binary_tree_find_max.go similarity index 100% rename from Trees/Binary Trees/binary_tree_finx_max.go rename to Trees/Binary Trees/binary_tree_find_max.go From fa123dcb59dc0077996ddbde60997b1553892ece Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:33:04 +0530 Subject: [PATCH 0482/1894] add find closest value in binary search tree --- .../binary_tree_find_closest_value.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_find_closest_value.go diff --git a/Trees/Binary Trees/binary_tree_find_closest_value.go b/Trees/Binary Trees/binary_tree_find_closest_value.go new file mode 100644 index 00000000..6a61c7f8 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_find_closest_value.go @@ -0,0 +1,33 @@ +// Find Closest Value In BST +package main + +type BST struct { + Value int + + Left *BST + Right *BST +} + +func (tree *BST) FindClosestValue(target int) int { + // Write your code here. + return tree.findClosestValue(target, tree.Value) +} + +func (tree *BST) findClosestValue(target, closest int) int { + if absDiff(target, closest) > absDiff(target, tree.Value) { + closest = tree.Value + } + if target < tree.Value && tree.Left != nil { + return tree.Left.findClosestValue(target, closest) + } else if target > tree.Value && tree.Right != nil { + return tree.Right.findClosestValue(target, closest) + } + return closest +} + +func absDiff(a, b int) int { + if a > b { + return a - b + } + return b - a +} From 0c03d7e16656699739becd15e669bbb22cdcfaba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:33:55 +0530 Subject: [PATCH 0483/1894] file already exists in BST --- .../binary_tree_find_closest_value.go | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 Trees/Binary Trees/binary_tree_find_closest_value.go diff --git a/Trees/Binary Trees/binary_tree_find_closest_value.go b/Trees/Binary Trees/binary_tree_find_closest_value.go deleted file mode 100644 index 6a61c7f8..00000000 --- a/Trees/Binary Trees/binary_tree_find_closest_value.go +++ /dev/null @@ -1,33 +0,0 @@ -// Find Closest Value In BST -package main - -type BST struct { - Value int - - Left *BST - Right *BST -} - -func (tree *BST) FindClosestValue(target int) int { - // Write your code here. - return tree.findClosestValue(target, tree.Value) -} - -func (tree *BST) findClosestValue(target, closest int) int { - if absDiff(target, closest) > absDiff(target, tree.Value) { - closest = tree.Value - } - if target < tree.Value && tree.Left != nil { - return tree.Left.findClosestValue(target, closest) - } else if target > tree.Value && tree.Right != nil { - return tree.Right.findClosestValue(target, closest) - } - return closest -} - -func absDiff(a, b int) int { - if a > b { - return a - b - } - return b - a -} From 52115baa597bbda77f709915b4273d3ae9f0e6cf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:35:08 +0530 Subject: [PATCH 0484/1894] add branch sums --- .../binary_tree_find_branch_sum.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_find_branch_sum.go diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/binary_tree_find_branch_sum.go new file mode 100644 index 00000000..bf59eb93 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_find_branch_sum.go @@ -0,0 +1,26 @@ +// Branch Sums +package main + +type BinaryTree struct { + Value int + Left *BinaryTree + Right *BinaryTree +} + +func BranchSums(root *BinaryTree) []int { + sums := []int{} + calculateBranchSums(root, 0, &sums) + return sums +} + +func calculateBranchSums(node *BinaryTree, runningSum int, sums *[]int) { + if node == nil { + return + } + runningSum += node.Value + if node.Left == nil && node.Right == nil { + *sums = append(*sums, runningSum) + } + calculateBranchSums(node.Left, runningSum, sums) + calculateBranchSums(node.Right, runningSum, sums) +} \ No newline at end of file From e3acd771a46ce2f2d6280d9a042418b1c37b79a1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:36:45 +0530 Subject: [PATCH 0485/1894] add description --- Trees/Binary Trees/binary_tree_find_branch_sum.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/binary_tree_find_branch_sum.go index bf59eb93..cd7cec60 100644 --- a/Trees/Binary Trees/binary_tree_find_branch_sum.go +++ b/Trees/Binary Trees/binary_tree_find_branch_sum.go @@ -1,4 +1,13 @@ -// Branch Sums +/* + Write a function that takes in a Binary Tree and returns a list of its branch + sums ordered from leftmost branch sum to rightmost branch sum. + + + A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree + branch is a path of nodes in a tree that starts at the root node and ends at + any leaf node. + +*/ package main type BinaryTree struct { From ad58463cb093e5ab98b4fd82448c92155dcdfebb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:36:54 +0530 Subject: [PATCH 0486/1894] add sample io --- Trees/Binary Trees/binary_tree_find_branch_sum.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/binary_tree_find_branch_sum.go index cd7cec60..7bd35c47 100644 --- a/Trees/Binary Trees/binary_tree_find_branch_sum.go +++ b/Trees/Binary Trees/binary_tree_find_branch_sum.go @@ -2,11 +2,22 @@ Write a function that takes in a Binary Tree and returns a list of its branch sums ordered from leftmost branch sum to rightmost branch sum. - + A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree branch is a path of nodes in a tree that starts at the root node and ends at any leaf node. + Sample Input + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + / \ / + 8 9 10 + + Output:[15, 16, 18, 10, 11] + */ package main From 28b62697e4ac4fa7504165891bcdeaca3951fc59 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:37:58 +0530 Subject: [PATCH 0487/1894] add approach --- Trees/Binary Trees/binary_tree_find_branch_sum.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/binary_tree_find_branch_sum.go index 7bd35c47..d807260a 100644 --- a/Trees/Binary Trees/binary_tree_find_branch_sum.go +++ b/Trees/Binary Trees/binary_tree_find_branch_sum.go @@ -2,7 +2,7 @@ Write a function that takes in a Binary Tree and returns a list of its branch sums ordered from leftmost branch sum to rightmost branch sum. - + A branch sum is the sum of all values in a Binary Tree branch. A Binary Tree branch is a path of nodes in a tree that starts at the root node and ends at any leaf node. @@ -19,6 +19,13 @@ Output:[15, 16, 18, 10, 11] */ + +/* + As you recursively traverse the tree, if you reach a leaf node (a node with no "left" or "right" Binary Tree nodes), + add the relevant running sum that you've calculated to a list of sums (which you'll also have to pass to the recursive + function). If you reach a node that isn't a leaf node, keep recursively traversing its children nodes, + passing the correctly updated running sum to them. +*/ package main type BinaryTree struct { From 2095a9465d9fc886969af446a1fcc1ab9f006052 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:38:31 +0530 Subject: [PATCH 0488/1894] add time and space complexity --- Trees/Binary Trees/binary_tree_find_branch_sum.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/binary_tree_find_branch_sum.go index d807260a..41f9bd28 100644 --- a/Trees/Binary Trees/binary_tree_find_branch_sum.go +++ b/Trees/Binary Trees/binary_tree_find_branch_sum.go @@ -25,6 +25,8 @@ add the relevant running sum that you've calculated to a list of sums (which you'll also have to pass to the recursive function). If you reach a node that isn't a leaf node, keep recursively traversing its children nodes, passing the correctly updated running sum to them. + + Time and Space complexity : O(n) time | O(n) space - where n is the number of nodes in the Binary Tree */ package main From 3f64d3d3595b2a3fbaa33dadc98dd21f7b012229 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:39:56 +0530 Subject: [PATCH 0489/1894] add node depths --- Trees/Binary Trees/binary_tree_node_depth.go | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_node_depth.go diff --git a/Trees/Binary Trees/binary_tree_node_depth.go b/Trees/Binary Trees/binary_tree_node_depth.go new file mode 100644 index 00000000..091c41b9 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_node_depth.go @@ -0,0 +1,25 @@ +/* + The distance between a node in a Binary Tree and the tree's root is called the + node's depth. + + Write a function that takes in a Binary Tree and returns the sum of its nodes' + depths. +*/ +package main + +type BinaryTree struct { + Value int + Left, Right *BinaryTree +} + +func NodeDepths(root *BinaryTree) int { + return nodeDepthHelper(root, 0) + return -1 +} + +func nodeDepthHelper(root *BinaryTree, depth int) int { + if root == nil { + return 0 + } + return depth + nodeDepthHelper(root.Left, depth + 1) + nodeDepthHelper(root.Right, depth + 1) +} \ No newline at end of file From 85e9efa7ecb17b662cc4e30ca5f20cb273fac7a8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:40:56 +0530 Subject: [PATCH 0490/1894] add sample io --- Trees/Binary Trees/binary_tree_node_depth.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Trees/Binary Trees/binary_tree_node_depth.go b/Trees/Binary Trees/binary_tree_node_depth.go index 091c41b9..ceceb514 100644 --- a/Trees/Binary Trees/binary_tree_node_depth.go +++ b/Trees/Binary Trees/binary_tree_node_depth.go @@ -3,7 +3,17 @@ node's depth. Write a function that takes in a Binary Tree and returns the sum of its nodes' - depths. + depths. + + Sample Input: + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + / \ +8 9 + Output: 16 */ package main @@ -14,7 +24,6 @@ type BinaryTree struct { func NodeDepths(root *BinaryTree) int { return nodeDepthHelper(root, 0) - return -1 } func nodeDepthHelper(root *BinaryTree, depth int) int { From be9905b712382d4a738822fbca13334bacfe5c9d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:42:07 +0530 Subject: [PATCH 0491/1894] add approach and time and space complexity --- Trees/Binary Trees/binary_tree_node_depth.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Trees/Binary Trees/binary_tree_node_depth.go b/Trees/Binary Trees/binary_tree_node_depth.go index ceceb514..573cd9ed 100644 --- a/Trees/Binary Trees/binary_tree_node_depth.go +++ b/Trees/Binary Trees/binary_tree_node_depth.go @@ -15,6 +15,17 @@ 8 9 Output: 16 */ + +/* + The depth of any node in the tree is equal to the depth of its parent node plus 1. + By starting at the root node whose depth is 0, you can pass down to every node in + the tree its respective depth, and you can implement the algorithm that does this + and that sums up all of the depths either recursively or iteratively. + + Time and Space complexity + Average case: when the tree is balanced + O(n) time | O(h) space - where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree +*/ package main type BinaryTree struct { From b0fc73a7b159a3776690d4b106cc1f5f795d128f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:48:06 +0530 Subject: [PATCH 0492/1894] add dfs on graph --- Graphs/graphs_dfs.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Graphs/graphs_dfs.go diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go new file mode 100644 index 00000000..d532caae --- /dev/null +++ b/Graphs/graphs_dfs.go @@ -0,0 +1,34 @@ +/* + DFS on a graph + Sample Input + A + / | \ + B C D + / \ / \ + E F G H + / \ \ + I J K + Output: ["A", "B", "E", "F", "I", "J", "C", "D", "G", "K", "H"] +*/ +package main + +import "fmt" + +type Node struct { + Name string + Children []*Node +} + +func (n *Node) DepthFirstSearch(array []string) []string { + return n.dfsHelper(array) +} + +func (n *Node) dfsHelper(array []string) []string { + array = append(array, n.Name) + + for _, child := range n.Children { + fmt.Println(child.Name, " -->") + array = child.dfsHelper(array) + } + return array +} From 1df515a2eb7b9e8a4bd66953fd5a74ffb2fb8dee Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 18 Mar 2023 22:49:08 +0530 Subject: [PATCH 0493/1894] add approach and time and space complexity --- Graphs/graphs_dfs.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index d532caae..84a25273 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -10,6 +10,15 @@ I J K Output: ["A", "B", "E", "F", "I", "J", "C", "D", "G", "K", "H"] */ +/* + Start at the root Node and try simply calling the depthFirstSearch method on all of its children Nodes. + Then, call the depthFirstSearch method on all children Nodes of each child node. + Keep applying this logic until the entire graph has been traversed. + Don't forget to add the current Node's name to the input array at every call of depthFirstSearch. + + Time and Space complexity: O(v + e) time | O(v) space - where v is the number of vertices of the input graph and e is the number of edges of the input graph +*/ + package main import "fmt" From d047e6fc5077db4edb02c59505e70b5f594d2e3d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:35:33 +0530 Subject: [PATCH 0494/1894] refactor --- .../binary_search_sorted_2d_matrix.py | 25 ----------- Binary Search/ceil_of_target.java | 45 ------------------- 2 files changed, 70 deletions(-) delete mode 100644 Binary Search/binary_search_sorted_2d_matrix.py delete mode 100644 Binary Search/ceil_of_target.java diff --git a/Binary Search/binary_search_sorted_2d_matrix.py b/Binary Search/binary_search_sorted_2d_matrix.py deleted file mode 100644 index 4ac7da8d..00000000 --- a/Binary Search/binary_search_sorted_2d_matrix.py +++ /dev/null @@ -1,25 +0,0 @@ -class Solution: - def __init__(self): - self.index = -1 - def binarySearch(self,arr,low,high,key): - if(low>high): - return self.index - mid=(low+high)//2 - if(arr[mid]>key): - return Solution.binarySearch(self,arr,low,mid-1,key) - elif(arr[mid] bool: - n = len(matrix[0]) - m = len(matrix) - - arr = [matrix[i][0] for i in range(m)] - ind1 = Solution.binarySearch(self,arr,0,m-1,target) - self.index=-1 - ind2 = Solution.binarySearch(self,matrix[ind1],0,n-1,target) - if(matrix[ind1][ind2] == target): - return True - return False diff --git a/Binary Search/ceil_of_target.java b/Binary Search/ceil_of_target.java deleted file mode 100644 index 41f67461..00000000 --- a/Binary Search/ceil_of_target.java +++ /dev/null @@ -1,45 +0,0 @@ -/* Ceiling of an element in a sorted array - You are given a sorted array nums and a target . - Find the index of the smallest element that is greater than or equal to target - - EXAMPLES: - INPUT : nums = [2,4,5,7,9,11,18,25], target = 18 - OUTPUT: 6 - - INPUT : nums = [2,4,5,7,9,11,18,25], target = 10 - OUTPUT: 5 - - APPROACH : - We will implement this problem using BinarySearch since the array is sorted. - - */ - - - - - - -public class CeilOfTarget{ - - public static int search_ceil(int[] nums,int target){ - int start = 0,end = nums.length-1; - while(start <=end){ - int mid = start +(end-start)/2; - if(nums[mid]==target){ - return mid; // returns the target - } - else if(nums[mid] > target){ - end = mid-1; - } - else{ - start = mid +1; - } - } - return start; // returns the nearest element to target if the target is not found - } - public static void main(String[] args){ - int[] nums = {2,4,5,7,9,11,18,25}; - int target = 18; - System.out.print(search_ceil(nums,target)); -} -} From c3b0918666983bdcc49172bbbe2b07a0ffe9af89 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:39:42 +0530 Subject: [PATCH 0495/1894] add longest pallindromic substring --- .../longest_pallindromic_substring.go | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Dynamic Programming/longest_pallindromic_substring.go diff --git a/Dynamic Programming/longest_pallindromic_substring.go b/Dynamic Programming/longest_pallindromic_substring.go new file mode 100644 index 00000000..267357b1 --- /dev/null +++ b/Dynamic Programming/longest_pallindromic_substring.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" +) + +func LongestPalindromicSubstring(Array string) int { + n := len(Array) + L := make([][]bool, n) + for i := range L { + L[i] = make([]bool, n) // defaults to false + } + max := 1 + for i := 0; i < n-1; i++ { + L[i][i] = true + if Array[i] == Array[i+1] { + L[i][i+1] = true + max = 2 + } + } + for k := 3; k <= n; k++ { + for i := 1; i < n-k+1; i++ { + j := i + k - 1 + if Array[i] == Array[j] && L[i+1][j-1] { + L[i][j] = true + max = k + } else { + L[i][j] = false + } + } + } + return max +} + +func main() { + fmt.Print(LongestPalindromicSubstring("babad")) + +} \ No newline at end of file From 3c8fca458b3afa513443be3c769e5a04b3211685 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:40:40 +0530 Subject: [PATCH 0496/1894] add description --- .../longest_pallindromic_substring.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Dynamic Programming/longest_pallindromic_substring.go b/Dynamic Programming/longest_pallindromic_substring.go index 267357b1..2e19a03b 100644 --- a/Dynamic Programming/longest_pallindromic_substring.go +++ b/Dynamic Programming/longest_pallindromic_substring.go @@ -1,3 +1,21 @@ +/* + Given a string s, return the longest palindromic substring in s. + + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +*/ package main import ( From ce6ecd7b31249bed39bf86ad01c2326e8b0a2351 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:41:44 +0530 Subject: [PATCH 0497/1894] rfmt --- Dynamic Programming/longest_pallindromic_substring.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Dynamic Programming/longest_pallindromic_substring.go b/Dynamic Programming/longest_pallindromic_substring.go index 2e19a03b..d923ec7e 100644 --- a/Dynamic Programming/longest_pallindromic_substring.go +++ b/Dynamic Programming/longest_pallindromic_substring.go @@ -1,7 +1,6 @@ /* Given a string s, return the longest palindromic substring in s. - Example 1: Input: s = "babad" Output: "bab" @@ -29,17 +28,17 @@ func LongestPalindromicSubstring(Array string) int { L[i] = make([]bool, n) // defaults to false } max := 1 - for i := 0; i < n-1; i++ { + for i := 0; i < n - 1; i++ { L[i][i] = true - if Array[i] == Array[i+1] { - L[i][i+1] = true + if Array[i] == Array[i + 1] { + L[i][i + 1] = true max = 2 } } for k := 3; k <= n; k++ { - for i := 1; i < n-k+1; i++ { + for i := 1; i < n - k + 1; i++ { j := i + k - 1 - if Array[i] == Array[j] && L[i+1][j-1] { + if Array[i] == Array[j] && L[i + 1][j - 1] { L[i][j] = true max = k } else { From 758089ad4def2a3442f7c396d5cd4a537f4ba4f9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:50:38 +0530 Subject: [PATCH 0498/1894] refactor --- Hash Table/col_sum.java | 75 ----------------- Hash Table/coloful_number.java | 105 ------------------------ Hash Table/count_distinct_elements.java | 60 -------------- Hash Table/count_elements.java | 103 ----------------------- Hash Table/count_subarray_zero_sum.java | 60 -------------- Hash Table/count_unique_elements.java | 105 ------------------------ Hash Table/equilbrium_array.java | 56 ------------- 7 files changed, 564 deletions(-) delete mode 100644 Hash Table/col_sum.java delete mode 100644 Hash Table/coloful_number.java delete mode 100644 Hash Table/count_distinct_elements.java delete mode 100644 Hash Table/count_elements.java delete mode 100644 Hash Table/count_subarray_zero_sum.java delete mode 100644 Hash Table/count_unique_elements.java delete mode 100644 Hash Table/equilbrium_array.java diff --git a/Hash Table/col_sum.java b/Hash Table/col_sum.java deleted file mode 100644 index 8f114a2c..00000000 --- a/Hash Table/col_sum.java +++ /dev/null @@ -1,75 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * You are given a 2D integer matrix A, return a 1D integer array containing column-wise sums of original matrix. - * - * - * - * Problem Constraints - * 1 <= A.size() <= 103 - * - * 1 <= A[i].size() <= 103 - * - * 1 <= A[i][j] <= 103 - * - * - * - * Input Format - * First argument is a 2D array of integers.(2D matrix). - * - * - * - * Output Format - * Return an array conatining column-wise sums of original matrix. - * - * - * - * Example Input - * Input 1: - * - * [1,2,3,4] - * [5,6,7,8] - * [9,2,3,4] - * - * - * Example Output - * Output 1: - * - * {15,10,13,16} - * - * - * Example Explanation - * Explanation 1 - * - * Column 1 = 1+5+9 = 15 - * Column 2 = 2+6+2 = 10 - * Column 3 = 3+7+3 = 13 - * Column 4 = 4+8+4 = 16 - */ -public class ColSum { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, 2, 3, 4)); - array.add(Arrays.asList(5, 6, 7, 8)); - array.add(Arrays.asList(9, 2, 3, 4)); - - System.out.println((solve(3, 4, array))); - } - public static ArrayList solve (int row, int col, List> array) { - // O(row*col) time | O(col) space - ArrayList result = new ArrayList<>(); - - for (int colIdx = 0; colIdx < col; colIdx++) { - int currentSum = 0; - for (int rowIdx = 0; rowIdx < row; rowIdx++) { - int currentNum = array.get(rowIdx).get(colIdx); - currentSum += currentNum; - } - result.add(currentSum); - } - return result; - } - -} diff --git a/Hash Table/coloful_number.java b/Hash Table/coloful_number.java deleted file mode 100644 index 30fc5cd9..00000000 --- a/Hash Table/coloful_number.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Problem Description - * Given a number A, find if it is COLORFUL number or not. - * - * If number A is a COLORFUL number return 1 else, return 0. - * - * What is a COLORFUL Number: - * - * A number can be broken into different consecutive sequence of digits. - * The number 3245 can be broken into sequences like 3, 2, 4, 5, 32, 24, 45, 324 and 245. - * This number is a COLORFUL number, since the product of every consecutive sequence of digits is different - * - * - * Problem Constraints - * 1 <= A <= 2 * 109 - * - * - * - * Input Format - * The first and only argument is an integer A. - * - * - * - * Output Format - * Return 1 if integer A is COLORFUL else return 0. - * - * - * - * Example Input - * Input 1: - * - * A = 23 - * Input 2: - * - * A = 236 - * - * - * Example Output - * Output 1: - * - * 1 - * Output 2: - * - * 0 - * - * - * Example Explanation - * Explanation 1: - * - * Possible Sub-sequences: [2, 3, 23] where - * 2 -> 2 - * 3 -> 3 - * 23 -> 6 (product of digits) - * This number is a COLORFUL number since product of every digit of a sub-sequence are different. - * Explanation 2: - * - * Possible Sub-sequences: [2, 3, 6, 23, 36, 236] where - * 2 -> 2 - * 3 -> 3 - * 6 -> 6 - * 23 -> 6 (product of digits) - * 36 -> 18 (product of digits) - * 236 -> 36 (product of digits) - * This number is not a COLORFUL number since the product sequence 23 and sequence 6 is same. - */ - -package Hashing; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -public class ColorfulNumber { - public static void main(String[] args) { - int num = 236; - - int res = solve(num); - System.out.println(res); - } - public static int solve(int num) { - // O(DIGITS ^ 2) time | O(DIGITS ^ 2) space - HashSet hashSet = new HashSet<>(); - ArrayList numbers = new ArrayList<>(); - - int currentNum = num; - while (currentNum != 0) { - int digit = currentNum % 10; - numbers.add(digit); - currentNum /= 10; - } - - Collections.reverse(numbers); - int len = numbers.size(); - for (int i = 0; i < len; i++) { - int product = 1; - for (int j = i; j < len; j++) { - - product *= numbers.get(j); - if (hashSet.contains(product)) return 0; - hashSet.add(product); - } - } - return 1; - } -} diff --git a/Hash Table/count_distinct_elements.java b/Hash Table/count_distinct_elements.java deleted file mode 100644 index 7bfee076..00000000 --- a/Hash Table/count_distinct_elements.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Problem Description - * You are given an array A of N integers. You will have to return number of distinct elements of the array. - * - * Problem Constraints - * 1 <= N <= 105 - * 1 <= A[i] <= 109 - * - * - * Input Format - * First argument A is an array of integers. - * - * - * Output Format - * Return an integer. - * - * - * Example Input - * Input 1: - * A = [3, 4, 3, 6, 6] - * Input 2: - * A = [3, 3, 3, 9, 0, 1, 0] - * - * - * Example Output - * Output 1: - * 3 - * Output 2: - * 4 - * - * - * Example Explanation - * For Input 1: - * The distinct elements of the array are 3, 4 and 6. - * For Input 2: - * The distinct elements of the array are 3, 9, 0 and 1. - */ - -package Hashing; - -import java.util.HashSet; - -public class CountDistinctElements { - public static void main(String[] args) { - int[] array = {3, 4, 3, 6, 6}; - - int res = solve(array); - System.out.println(res); - } - public static int solve(int[] array) { - // O(N) time | O(N) space - - HashSet hashSet = new HashSet<>(); - - for (int num : array) - hashSet.add((long) num); - - return (int) hashSet.size(); - } -} diff --git a/Hash Table/count_elements.java b/Hash Table/count_elements.java deleted file mode 100644 index edab1d8b..00000000 --- a/Hash Table/count_elements.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Given two integer arrays, A and B of size N and M, respectively. Your task is to find all the common elements in both the array. - * - * NOTE: - * - * Each element in the result should appear as many times as it appears in both arrays. - * The result can be in any order. - * - * - * Problem Constraints - * 1 <= N, M <= 105 - * - * 1 <= A[i] <= 109 - * - * - * - * Input Format - * First argument is an integer array A of size N. - * - * Second argument is an integer array B of size M. - * - * - * - * Output Format - * Return an integer array denoting the common elements. - * - * - * - * Example Input - * Input 1: - * - * A = [1, 2, 2, 1] - * B = [2, 3, 1, 2] - * Input 2: - * - * A = [2, 1, 4, 10] - * B = [3, 6, 2, 10, 10] - * - * - * Example Output - * Output 1: - * - * [1, 2, 2] - * Output 2: - * - * [2, 10] - * - * - * Example Explanation - * Explanation 1: - * - * Elements (1, 2, 2) appears in both the array. Note 2 appears twice in both the array. - * Explantion 2: - * - * Elements (2, 10) appears in both the array. - */ - -package Hashing; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - -public class CountElements { - public static void main(String[] args) { - int[] array1 = {2, 1, 4, 10, 10}; - int[] array2 = {3, 6, 2, 10, 10, 10}; - - int[] res = solve(array1, array2); - System.out.println(Arrays.toString(res)); - } - - public static int[] solve(int[] array1, int[] array2) { - // O(N + M) time | O(N + M) space - - HashMap hashMap1 = new HashMap<>(); - HashMap hashMap2 = new HashMap<>(); - - for (int num : array1) { - hashMap1.put(num, hashMap1.getOrDefault(num, 0) + 1); - } - - for (int num : array2) { - hashMap2.put(num, hashMap2.getOrDefault(num, 0) + 1); - } - - ArrayList res = new ArrayList<>(); - - for (int key: hashMap1.keySet()) { - - if (hashMap2.containsKey(key)) { - - for (int i = 0; i < Math.min(hashMap1.get(key), hashMap2.get(key)); ++i) { // to get common elements - res.add(key); - } - } - } - - return res.stream().mapToInt(i -> i).toArray(); - - } -} - diff --git a/Hash Table/count_subarray_zero_sum.java b/Hash Table/count_subarray_zero_sum.java deleted file mode 100644 index 7bfee076..00000000 --- a/Hash Table/count_subarray_zero_sum.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Problem Description - * You are given an array A of N integers. You will have to return number of distinct elements of the array. - * - * Problem Constraints - * 1 <= N <= 105 - * 1 <= A[i] <= 109 - * - * - * Input Format - * First argument A is an array of integers. - * - * - * Output Format - * Return an integer. - * - * - * Example Input - * Input 1: - * A = [3, 4, 3, 6, 6] - * Input 2: - * A = [3, 3, 3, 9, 0, 1, 0] - * - * - * Example Output - * Output 1: - * 3 - * Output 2: - * 4 - * - * - * Example Explanation - * For Input 1: - * The distinct elements of the array are 3, 4 and 6. - * For Input 2: - * The distinct elements of the array are 3, 9, 0 and 1. - */ - -package Hashing; - -import java.util.HashSet; - -public class CountDistinctElements { - public static void main(String[] args) { - int[] array = {3, 4, 3, 6, 6}; - - int res = solve(array); - System.out.println(res); - } - public static int solve(int[] array) { - // O(N) time | O(N) space - - HashSet hashSet = new HashSet<>(); - - for (int num : array) - hashSet.add((long) num); - - return (int) hashSet.size(); - } -} diff --git a/Hash Table/count_unique_elements.java b/Hash Table/count_unique_elements.java deleted file mode 100644 index 30fc5cd9..00000000 --- a/Hash Table/count_unique_elements.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Problem Description - * Given a number A, find if it is COLORFUL number or not. - * - * If number A is a COLORFUL number return 1 else, return 0. - * - * What is a COLORFUL Number: - * - * A number can be broken into different consecutive sequence of digits. - * The number 3245 can be broken into sequences like 3, 2, 4, 5, 32, 24, 45, 324 and 245. - * This number is a COLORFUL number, since the product of every consecutive sequence of digits is different - * - * - * Problem Constraints - * 1 <= A <= 2 * 109 - * - * - * - * Input Format - * The first and only argument is an integer A. - * - * - * - * Output Format - * Return 1 if integer A is COLORFUL else return 0. - * - * - * - * Example Input - * Input 1: - * - * A = 23 - * Input 2: - * - * A = 236 - * - * - * Example Output - * Output 1: - * - * 1 - * Output 2: - * - * 0 - * - * - * Example Explanation - * Explanation 1: - * - * Possible Sub-sequences: [2, 3, 23] where - * 2 -> 2 - * 3 -> 3 - * 23 -> 6 (product of digits) - * This number is a COLORFUL number since product of every digit of a sub-sequence are different. - * Explanation 2: - * - * Possible Sub-sequences: [2, 3, 6, 23, 36, 236] where - * 2 -> 2 - * 3 -> 3 - * 6 -> 6 - * 23 -> 6 (product of digits) - * 36 -> 18 (product of digits) - * 236 -> 36 (product of digits) - * This number is not a COLORFUL number since the product sequence 23 and sequence 6 is same. - */ - -package Hashing; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; - -public class ColorfulNumber { - public static void main(String[] args) { - int num = 236; - - int res = solve(num); - System.out.println(res); - } - public static int solve(int num) { - // O(DIGITS ^ 2) time | O(DIGITS ^ 2) space - HashSet hashSet = new HashSet<>(); - ArrayList numbers = new ArrayList<>(); - - int currentNum = num; - while (currentNum != 0) { - int digit = currentNum % 10; - numbers.add(digit); - currentNum /= 10; - } - - Collections.reverse(numbers); - int len = numbers.size(); - for (int i = 0; i < len; i++) { - int product = 1; - for (int j = i; j < len; j++) { - - product *= numbers.get(j); - if (hashSet.contains(product)) return 0; - hashSet.add(product); - } - } - return 1; - } -} diff --git a/Hash Table/equilbrium_array.java b/Hash Table/equilbrium_array.java deleted file mode 100644 index ab634e40..00000000 --- a/Hash Table/equilbrium_array.java +++ /dev/null @@ -1,56 +0,0 @@ -import java.util.ArrayList; -import java.util.Arrays; - -/** - * You are given an array A of integers of size N. - * - * Your task is to find the equilibrium index of the given array - * - * The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. - * - * NOTE: - * - * Array indexing starts from 0. - * If there is no equilibrium index then return -1. - * If there are more than one equilibrium indexes then return the minimum index. - * - * Input 1: - * A=[-7, 1, 5, 2, -4, 3, 0] - * Input 2: - * - * A=[1,2,3] - */ -public class EquilibriumOfAnArray { - public static void main(String[] args) { - ArrayList array = new ArrayList<>(Arrays.asList( - -7653, -3893, 2371, 4846, 5531, 7995, -9637, 2740, -5807, -5974, -8040, -5191, 2756, 7044, 1702, 2357, 6428, -3363, -7233, 356, 1161, -6762, 3844, -2591, 1683, -1529, -1485, 5264, 5837, 6942, -2790, 362, -3670, 8013, -882, 1014, 869, -4855, -5179, 2357, -8530, 3458, -3298, 9639, 9387, -3568, -4375, -2076, 6962, 1023, 6093, 7771, -4167, 5472, 710, -1886, -7533, 5588, 1830, -7054, -8271, 7956, 9231, -8723, 133, 5288, -7930, 6596, 9084, 3889, -1322, -9644, -1845, -6600, -3502, -1679, -524, -2646, -7516, 7477, 3345, -9345, 6552, -9659, -8228, 8736, -3801, 2717, -5218, 33, -9392, -737, -343, -5206, -5151, -192, 9857, -7362, 6713, 7524, 1892, 2156, -4224, 8030, -5094, 959, 9250, -4588, -4368, 3531, 5868, -9777, 7064, -5718, 6412, -189, -4323, -5987, 8161, 2709, 7433, 9648, -185, 270, -1299, -1976, -4157, -4372, -7090, -633, -9468, -8274, 9549, -6744, 2385, 8156, 5688, -792, -3338, 2283, 6503, -9786, 3878, 9541, -6152, 3785, 9396, -9695, -6004, 3621, -645, -3609, 2176, 6398, 1248, 2320, -4962, 5011, -8832, 6127, -7635, -6142, -4646, 3047, -2509, -4769, 4140, 5508, 9420, 8120, -2694, 6560, 8398, -100, 5759, 2696, 5696, 7748, -9611, 1007, -5228, 8574, 4507, -1011, 2723, -9726, 179, -2428, 9181, 4898, -8915, 7768, -5208, 8306, -2659, 3844, -661, 8452, 6041, 1380, 7817, 8973, 6751, -4815, 5347, -2711, 188, -5371, -679, -8278, 1903, -5038, -5791, -7893, 6515, -4994, 4527, -2608, -1213, 6028, 8742, -4275, -4817, -6160, 6422, -1766, -8639, 6205, -3150, 4615, 7417, 8710, -6074, -344, 4148, 1425, -632, -9160, 3297, -7114, 5159, 1386, 9770, 2347, -3587, -3875, -2635, 5048, -5901, -7484, 8975, -4308, 161, 299, -4049, -8815, -7762, 7018, -7943, 237, -6695, 7629, -7953, 9459, 4735, -3829, 9727, -6403, 5466, 6218, -5877, 2033, -4857, 1585, 514, -6989, 5236, -9830, -5191, 5947, 2560, -4052, -8077, -1288, 492, -4326, -492, 2294, -4923, -5192, 5162, 3137, 5975, 7399, -5645, 4187, -8523, 3651, -2419, 7813, 6036, -7307, 8254, 7936, -9467, 5581, -3412, 7572, 5229, 101, 1171, 8309, -6208, -8279, 444, -2281, -2046, -8015, 9570, -7134, 4339, 5946, 3592, -3576, -886, -4246, -610, 8529, 114, 6778, -7997, 7117, 7970, -9467, 1722, -1286, 3767, -930, 7682, -3814, -4258, -3810, -8109, -9843, 8266, -732, 6784, -8437, 2357, -4750, -7906, -9440, -4353, -7544, 8803, 5253, 5256, -5497, 8886, 4304, 8080, 908, 6009, 4940, -9357, 3402, -1661, -1435, 5537, -7720, 5460, -872, -1353, -5385, 9094, -4783, 9087, -8572, -1667, 1788, -7608, 2228, 6087, 2984, 7494, -7699, -2480, -3224, -7232, 4543, -6029, -2972, 9430, 8164, 1959, -2684, -2414, -8991, -3467, -4217, -1649, 837, 4336, -2265, -3976, 9518, -734, 4976, 3196, 8596, -6076, -1447, -4851, 4907, -478, -7859, -5003, 8428, -9053, 4681, -795, 3330, 5359, -5970, -220, -7393, 1088, -1559, -9193, 7574, 6186, -9753, -9647, 7090, 443, -4809, 3298, 6116, 2494, 7231, 3493, -6231, -6764, -6311, 5140, 5977, 4169, 5221, 4568, -1875, 7542, 9705, 2771, -718, 3135, 5548, -1085, 3003, -3784, -2730, -6471, 9204, 9575, -8391, -3986, 1410, -5961, 4005, -6029, -6209, 8290, 2692, 3424, 5242, -8314, 4330, -2775, 4755, 8850, 2378, 8147, 5597, 8121, -5413, 7104, 9328, 5535, 0, 9065, -4788, -1505, 2202, -8444, 5989, 7361, 9707, -7802, 3466, -8042, 2077, -8845, -66, -7741, 5097, -268, -4540, -3439, -9265, -2806, 6926, 4592, 3148, -7634, 2777, -9401, -6748, -9755, 7814, -7294, -2509, -820, 338, 7721, 4314, 5798, 5146, -9934, -1057, 8088, 4854, 9482, 719, 7099, -5376, -2543, 587, 2026, -5367, -4480, 2011, -3743, 5779, -9267, -7509, 8485, -666, 1450, -4380, -1108, -2459, -7715, -3057, -1689, 436, 2696, -6039, -1375, -9400, 4052, 5780, 2796, -4295, 3960, 855, 548, -5908, -5673, -8366, 7366, -3138, -3512, 9567, -7559, 9387, -7031, 9293, -4569, -2683, -1176, 7786, -3516, -2594, 4886, 4669, 2079, -6810, -1645, -1342, 3529, 2070, -6946, 6439, 952, -1495, -4243, 8994, -6882 - )); - System.out.println(solve(array)); - } - public static int solve(ArrayList array) { - // O(n) time | O(n) space - /** - * 1. find prefix sum. - * 2. check for equilibrium - */ - System.out.println(array); - ArrayList prefixSum = new ArrayList<>(); - - prefixSum.add(array.get(0)); - for (int i = 1; i < array.size(); i++) { - int currentPrefixSum = prefixSum.get(i - 1) + array.get(i); - prefixSum.add(currentPrefixSum); - } - - for (int i = 0; i < array.size(); i++) { - if (i == 0 ) { - if (prefixSum.get(prefixSum.size() - 1) - prefixSum.get(i) == 0) return i; - continue; - } - if (prefixSum.get(i - 1) == prefixSum.get(prefixSum.size() - 1) - prefixSum.get(i)) - return i; - } - return -1; - } - -} From db7a27f514e9328701b42f11c48421719d1ca205 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:52:12 +0530 Subject: [PATCH 0499/1894] refactor --- Hash Table/LongestSubstring.java | 60 --------------- Hash Table/first_repeating_number.java | 83 --------------------- Hash Table/number_of_good_pairs.java | 63 ---------------- Hash Table/row_sum.java | 71 ------------------ Hash Table/smaller_number_than_current.java | 67 ----------------- 5 files changed, 344 deletions(-) delete mode 100644 Hash Table/LongestSubstring.java delete mode 100644 Hash Table/first_repeating_number.java delete mode 100644 Hash Table/number_of_good_pairs.java delete mode 100644 Hash Table/row_sum.java delete mode 100644 Hash Table/smaller_number_than_current.java diff --git a/Hash Table/LongestSubstring.java b/Hash Table/LongestSubstring.java deleted file mode 100644 index e4f76110..00000000 --- a/Hash Table/LongestSubstring.java +++ /dev/null @@ -1,60 +0,0 @@ -import java.util.Set; -import java.util.HashSet; - -/* -Given a string s, find the length of the longest -substring without repeating characters. - - - -Example 1: - -Input: s = "abcabcbb" -Output: 3 -Explanation: The answer is "abc", with the length of 3. -Example 2: - -Input: s = "bbbbb" -Output: 1 -Explanation: The answer is "b", with the length of 1. -Example 3: - -Input: s = "pwwkew" -Output: 3 -Explanation: The answer is "wke", with the length of 3. -Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. - - -Constraints: - -0 <= s.length <= 5 * 104 -s consists of English letters, digits, symbols and spaces. -*/ - -class Solution { - public int lengthOfLongestSubstring(String s) { - if (s == null || s.equals("")) - return 0; - - int start=0,end=0,maxLength=0; - Set uniqueCharacters = new HashSet<>(); - while (end < s.length()) { - if (uniqueCharacters.add(s.charAt(end))) { - end++; - maxLength = Math.max(maxLength, uniqueCharacters.size()); - } else { - uniqueCharacters.remove(s.charAt(start)); - start++; - } - } - return maxLength; - - } -} -class LongestSubstring { - public static void main(String[] args) { - Solution s=new Solution(); - String str="abcabcbb"; - System.out.println(s.lengthOfLongestSubstring(str)); - } -} \ No newline at end of file diff --git a/Hash Table/first_repeating_number.java b/Hash Table/first_repeating_number.java deleted file mode 100644 index 878bc0c2..00000000 --- a/Hash Table/first_repeating_number.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Problem Description - * Given an integer array A of size N, find the first repeating element in it. - * - * We need to find the element that occurs more than once and whose index of the first occurrence is the smallest. - * - * If there is no repeating element, return -1. - * - * - * - * Problem Constraints - * 1 <= N <= 105 - * - * 1 <= A[i] <= 109 - * - * - * - * Input Format - * The first and only argument is an integer array A of size N. - * - * - * - * Output Format - * Return an integer denoting the first repeating element. - * - * - * - * Example Input - * Input 1: - * - * A = [10, 5, 3, 4, 3, 5, 6] - * Input 2: - * - * A = [6, 10, 5, 4, 9, 120] - * - * - * Example Output - * Output 1: - * - * 5 - * Output 2: - * - * -1 - * - * - * Example Explanation - * Explanation 1: - * - * 5 is the first element that repeats - * Explanation 2: - * - * There is no repeating element, output -1 - */ -package Hashing; - -import java.util.HashMap; - -public class FirstRepeatingElement { - public static void main(String[] args) { - int[] array = {10, 5, 3, 4, 3, 5, 6}; - - int res = solve(array); - System.out.println(res); - } - public static int solve(int[] array) { - // O(N) time | O(N) space where N is length of array - - // Build HashMap - HashMap hashMap = new HashMap<>(); - - for (int num : array) { - - if (!hashMap.containsKey(num)) hashMap.put(num, 0); - hashMap.put(num, hashMap.get(num) + 1); - } - - for (int num : array) { - if (hashMap.get(num) > 1) return num; - } - - return -1; - } -} diff --git a/Hash Table/number_of_good_pairs.java b/Hash Table/number_of_good_pairs.java deleted file mode 100644 index cca2a573..00000000 --- a/Hash Table/number_of_good_pairs.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Given an array of integers nums, return the number of good pairs. - * - * A pair (i, j) is called good if nums[i] == nums[j] and i < j. - * - * - * - * Example 1: - * - * Input: nums = [1,2,3,1,1,3] - * Output: 4 - * Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. - * Example 2: - * - * Input: nums = [1,1,1,1] - * Output: 6 - * Explanation: Each pair in the array are good. - * Example 3: - * - * Input: nums = [1,2,3] - * Output: 0 - * - * - * Constraints: - * - * 1 <= nums.length <= 100 - * 1 <= nums[i] <= 100 - */ - -package Hashing; - -import java.util.HashMap; - -public class NumberOfGoodPairs { - public static void main(String[] args) { - int[] array = {1, 1, 1, 1}; - - int res = solve(array); - System.out.println(res); - } - - public static int solve(int[] array) { - // O(N) time | O(N) space - int res = 0; - HashMap hashmap = new HashMap<>(); - - for (int num : array) { - - int numCount = hashmap.getOrDefault(num, 0); - res += numCount; - hashmap.put(num, numCount); - } - - // O(N^2) time | O(N) space -// for (int i = 0; i < array.length; i++) { -// for (int j = i + 1; j < array.length; j++) { -// if (array[i] == array[j]) res++; -// } -// } - - return res; - } -} diff --git a/Hash Table/row_sum.java b/Hash Table/row_sum.java deleted file mode 100644 index 3844877f..00000000 --- a/Hash Table/row_sum.java +++ /dev/null @@ -1,71 +0,0 @@ -import java.util.*; -/** - * You are given a 2D integer matrix A, return a 1D integer array containing row-wise sums of original matrix. - * - * - * - * Problem Constraints - * - * 1 <= A.size() <= 103 - * - * 1 <= A[i].size() <= 103 - * - * 1 <= A[i][j] <= 103 - * - * - * - * Input Format - * First argument A is a 2D array of integers.(2D matrix). - * - * - * - * Output Format - * Return an array conatining row-wise sums of original matrix. - * - * Example Input - * Input 1: - * - * [1,2,3,4] - * [5,6,7,8] - * [9,2,3,4] - * - * - * Example Output - * Output 1: - * - * [10,26,18] - * - * - * Example Explanation - * Explanation 1 - * - * Row 1 = 1+2+3+4 = 10 - * Row 2 = 5+6+7+8 = 26 - * Row 3 = 9+2+3+4 = 18 - */ - -public class RowSum { - public static void main(String[] args) { - List> array = new ArrayList<>(); - array.add(Arrays.asList(1, 2, 3, 4)); - array.add(Arrays.asList(5, 6, 7, 8)); - array.add(Arrays.asList(9, 2, 3, 4)); - - System.out.println((solve(3, 4, array))); - } - public static ArrayList solve (int row, int col, List> array) { - // O(row*col) time | O(row) space - ArrayList result = new ArrayList<>(); - - for (int rowIdx = 0; rowIdx < row; rowIdx++) { - int currentSum = 0; - for (int colIdx = 0; colIdx < col; colIdx++) { - int currentNum = array.get(rowIdx).get(colIdx); - currentSum += currentNum; - } - result.add(currentSum); - } - return result; - } - -} diff --git a/Hash Table/smaller_number_than_current.java b/Hash Table/smaller_number_than_current.java deleted file mode 100644 index 44371430..00000000 --- a/Hash Table/smaller_number_than_current.java +++ /dev/null @@ -1,67 +0,0 @@ -import java.util.HashMap; -/* -Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. - -Return the answer in an array. - - - -Example 1: - -Input: nums = [8,1,2,2,3] -Output: [4,0,1,1,3] -Explanation: -For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). -For nums[1]=1 does not exist any smaller number than it. -For nums[2]=2 there exist one smaller number than it (1). -For nums[3]=2 there exist one smaller number than it (1). -For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). -Example 2: - -Input: nums = [6,5,4,8] -Output: [2,1,0,3] -Example 3: - -Input: nums = [7,7,7,7] -Output: [0,0,0,0] - - -Constraints: - -2 <= nums.length <= 500 -0 <= nums[i] <= 100 -*/ -class Solution { - public int[] smallerNumbersThanCurrent(int[] nums) { - int[] res= new int[nums.length]; - int count=0; - HashMap hm = new HashMap(); - for(int i = 0; i < nums.length ; i++) - { - for(int j = 0 ; j < nums.length ; j++) - { - if(nums[j] < nums[i]) - count++; - - } - hm.put(nums[i],count); - count = 0; - } - - for(int i = 0 ;i < nums.length ; i++) - res[i] = hm.get(nums[i]); - - return res; - } -} -class Main { - public static void main(String[] args) { - int arr[] = {1,2,2,7}; - Solution s = new Solution(); - int ans[] = s.smallerNumbersThanCurrent(arr); - for (int i = 0 ; i < ans.length ; i++){ - System.out.println(ans[i]); - } - - } -} \ No newline at end of file From 487cb19a1d4869dc8b20b5ba7b7d958c05b1ed98 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:52:43 +0530 Subject: [PATCH 0500/1894] refactor --- Hash Table/first_non_repeating_element.java | 30 --------------------- 1 file changed, 30 deletions(-) delete mode 100644 Hash Table/first_non_repeating_element.java diff --git a/Hash Table/first_non_repeating_element.java b/Hash Table/first_non_repeating_element.java deleted file mode 100644 index dbd7d510..00000000 --- a/Hash Table/first_non_repeating_element.java +++ /dev/null @@ -1,30 +0,0 @@ -package Hashing; - -import java.util.HashMap; - -public class FirstNonRepeatingElement { - public static void main(String[] args) { - int[] array = {10, 5, 3, 4, 3, 5, 6}; - - int res = solve(array); - System.out.println(res); - } - public static int solve(int[] array) { - // O(N) time | O(N) space where N is length of array - - // Build HashMap - HashMap hashMap = new HashMap<>(); - - for (int num : array) { - - if (!hashMap.containsKey(num)) hashMap.put(num, 0); - hashMap.put(num, hashMap.get(num) + 1); - } - - for (int num : array) { - if (hashMap.get(num) == 1) return num; - } - - return -1; - } -} From 3ede91275c77612d2ba8171ea1798c3773d00c0a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Mar 2023 19:53:03 +0530 Subject: [PATCH 0501/1894] refactor --- Bit Manipulation/decimal_to_any_base.java | 62 ------------------- Bit Manipulation/find_good_days.java | 74 ----------------------- 2 files changed, 136 deletions(-) delete mode 100644 Bit Manipulation/decimal_to_any_base.java delete mode 100644 Bit Manipulation/find_good_days.java diff --git a/Bit Manipulation/decimal_to_any_base.java b/Bit Manipulation/decimal_to_any_base.java deleted file mode 100644 index b8c672d7..00000000 --- a/Bit Manipulation/decimal_to_any_base.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * You are given a number A. You are also given a base B. A is a number on base B. - * You are required to convert the number A into its corresponding value in decimal number system. - * - * - * Problem Constraints - * 0 <= A <= 109 - * 2 <= B <= 9 - * - * - * Input Format - * First argument A is an integer. - * Second argument B is an integer. - * - * - * Output Format - * Return an integer. - * - * - * Example Input - * Input 1: - * A = 1010 - * B = 2 - * Input 2: - * A = 22 - * B = 3 - * - * - * Example Output - * Output 1: - * 10 - * Output 2: - * 8 - * - * - * Example Explanation - * For Input 1: - * The decimal 10 in base 2 is 1010. - * For Input 2: - * The decimal 8 in base 3 is 22. - */ -package BitManipulation; - -public class AnyBaseToDecimal { - public static void main(String[] args) { - int num = 22; - int base = 3; - int ans = solve(num, base); - System.out.println(ans); - } - public static int solve(int num, int base) { - // O(1) time | O(1) space - int res = 0 , multiplier = 1, currentNum = num; - while(currentNum > 0){ - int currentDigit = currentNum % 10; - res += multiplier * currentDigit; - multiplier *= B; - currentNum /= 10; - } - return res; - } -} diff --git a/Bit Manipulation/find_good_days.java b/Bit Manipulation/find_good_days.java deleted file mode 100644 index 64a849e8..00000000 --- a/Bit Manipulation/find_good_days.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Problem Description - * Alex has a cat named Boomer. He decides to put his cat to the test for eternity. - * - * He starts on day 1 with one stash of food unit, every next day, the stash doubles. - * - * If Boomer is well behaved during a particular day, only then she receives food worth equal to the stash produced on that day. - * - * Boomer receives a net worth of A units of food. What is the number of days she received the stash? - * - * - * - * Problem Constraints - * 1 <= A <= 231-1 - * - * - * - * Input Format - * First and only argument is an integer A. - * - * - * - * Output Format - * Return an integer denoting the number of days Boomer was well behaved. - * - * - * - * Example Input - * Input 1: - * - * A = 5 - * Input 2: - * - * A = 8 - * - * - * Example Output - * Output 1: - * - * 2 - * Output 2: - * - * 1 - * - * - * Example Explanation - * Explanation 1: - * - * To eat a total of 5 units of food, Boomer behaved normally on Day 1 and on the Day 3. - * Explanation 2: - * - * To eat a total of 8 units of food, Boomer behaved normally only on day 4. - */ - -package BitManipulation; -public class FindGoodDays { - public static void main(String[] args) { - int a = 5; - int res = solve(a); - System.out.println(res); - } - public static int solve(int a) { - // O(N) time | O(1) space - - // Count 1 bits - int currentNum = a, res = 0; - - while (currentNum != 0) { - if ( (currentNum & 1) == 1) res++; - currentNum = currentNum >> 1; - } - return res; - } -} From 3c4adabdfbeecba1f3adbc074cc051466b7d76cf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 22:54:56 +0530 Subject: [PATCH 0502/1894] update link for kth node from end in python --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1950eb5..e568acdb 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ The key idea is that the pointers start at the same location, but they move forw - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) -- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) +- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) # Pattern 3: Sliding Window From 9c99f84821fdd950b415ca3e952a34fb7ffe0bbf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 22:58:59 +0530 Subject: [PATCH 0503/1894] update link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index debba909..e568acdb 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ The key idea is that the pointers start at the same location, but they move forw - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) -- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Lin ked%20List/remove_kth_node_from_end.py) +- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) # Pattern 3: Sliding Window From 3d86a8097d254ef391b98c8465448cae3034dbbc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 23:05:08 +0530 Subject: [PATCH 0504/1894] add kth from end in go --- Linked List/linked_list_kth_from_end.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Linked List/linked_list_kth_from_end.go diff --git a/Linked List/linked_list_kth_from_end.go b/Linked List/linked_list_kth_from_end.go new file mode 100644 index 00000000..a476bda6 --- /dev/null +++ b/Linked List/linked_list_kth_from_end.go @@ -0,0 +1,13 @@ +// Finding Kth node from end of a LinkedList +package main + +func kthFromEnd(head *ListNode, n int) *ListNode { + first, second := head, head + for ; n > 0; n-- { + second = second.next + } + for ; second.next != nil; first, second = first.next, second.next { + } + first.next = first.next.next + return first +} \ No newline at end of file From ef471ea872f0f4d0e56ef0630d2cb8b60d68780d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 23:05:22 +0530 Subject: [PATCH 0505/1894] add approach --- Linked List/linked_list_kth_from_end.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Linked List/linked_list_kth_from_end.go b/Linked List/linked_list_kth_from_end.go index a476bda6..c469aca6 100644 --- a/Linked List/linked_list_kth_from_end.go +++ b/Linked List/linked_list_kth_from_end.go @@ -1,6 +1,14 @@ // Finding Kth node from end of a LinkedList package main +/* +Approach +1. Make two pointers slow and fast and keep them both on the head of the linked list. +2. Now, move the fast pointer k steps away from the slow pointer. +3. Now, move the fast pointer and the slow pointer each one step at a time till + the fast pointer reaches the tail of the linked list. When the fast pointer reaches the tail, + the node at which the slow pointer resides will be our answer. +*/ func kthFromEnd(head *ListNode, n int) *ListNode { first, second := head, head for ; n > 0; n-- { From 79589ecb4f0105918b1dd0597bc264edeaf485dd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 23:07:00 +0530 Subject: [PATCH 0506/1894] add time and space complexity --- Linked List/linked_list_kth_from_end.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Linked List/linked_list_kth_from_end.go b/Linked List/linked_list_kth_from_end.go index c469aca6..410617c5 100644 --- a/Linked List/linked_list_kth_from_end.go +++ b/Linked List/linked_list_kth_from_end.go @@ -8,6 +8,16 @@ Approach 3. Now, move the fast pointer and the slow pointer each one step at a time till the fast pointer reaches the tail of the linked list. When the fast pointer reaches the tail, the node at which the slow pointer resides will be our answer. + +Time and space complexity + + Time complexity of the solution is O(n) as we have traversed the linked list once. + We have traversed it in two parts. + First we traversed k elements and then we traversed the remaining (size minus k) elements. + + Space complexity is O(1) as we have not used any extra space for the solution. + + */ func kthFromEnd(head *ListNode, n int) *ListNode { first, second := head, head From d8370ebf4e3db31ac0f8c686614c9dd19decc984 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Mar 2023 23:09:13 +0530 Subject: [PATCH 0507/1894] update link for go version of kth node from end --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e568acdb..2c75468a 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ The key idea is that the pointers start at the same location, but they move forw - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) -- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) +- Remove Kth node from end [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_kth_from_end.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) - Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) # Pattern 3: Sliding Window From 0232081330c9a44516f7ee10c1ef68a54253c226 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Mar 2023 22:58:02 +0530 Subject: [PATCH 0508/1894] update readme.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2c75468a..0b0cd970 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ # Implementation of well known Data Structures and Algorithms 🌈 Everyone is welcome! -You can join the fun by following our [contributing](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md) guide. +You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). # Sorting From d8a02be0c527c283c9cba89b2aaa64b12b3e442f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Mar 2023 23:00:31 +0530 Subject: [PATCH 0509/1894] add intro --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 0b0cd970..74bebf17 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,13 @@ 🌈 Everyone is welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). +#Intro + +The design of algorithms consists of problem solving and mathematical +thinking. Skills for analyzing problems and solving them creatively are needed. +An algorithm for solving a problem has to be both correct and efficient, and the +core of the problem is often about inventing an efficient algorithm. + # Sorting Sorting a list of items into ascending or descending order can help either a human or a computer find items on that list quickly, perhaps using an algorithm like binary search. Most Programming languages have built-in sorting methods. It works on arrays of numbers, or even on arrays of strings: From d006ce06f1d70f99143559925f9db3f7d35987d7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Mar 2023 23:05:09 +0530 Subject: [PATCH 0510/1894] update description of sorting --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 74bebf17..d6e8bfcf 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,17 @@ core of the problem is often about inventing an efficient algorithm. # Sorting -Sorting a list of items into ascending or descending order can help either a human or a computer find items on that list quickly, perhaps using an algorithm like binary search. Most Programming languages have built-in sorting methods. It works on arrays of numbers, or even on arrays of strings: +Sorting is a fundamental algorithm design problem. Many efficient algorithms +use sorting as a subroutine, because it is often easier to process data if the +elements are in a sorted order. +For example, the problem ”does an array contain two equal elements?” is easy +to solve using sorting. If the array contains two equal elements, they will be next +to each other after sorting, so it is easy to find them. Also, the problem ”what is +the most frequent element in an array?” can be solved similarly. +There are many algorithms for sorting, and they are also good examples of +how to apply different algorithm design techniques. The efficient general sorting +algorithms work in O(nlogn) time, and many algorithms that use sorting as a +subroutine also have this time complexity. ``` heights = [6, 5, 4, 5, 2, 3]; From 9259b268dfb2d33f3f186ab1620fb536b4263740 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Mar 2023 23:11:11 +0530 Subject: [PATCH 0511/1894] add binary search --- README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/README.md b/README.md index d6e8bfcf..3ed90267 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,29 @@ Even though languages have built-in sorting method, sorting is a great example o - Merge Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.py) - Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) +# Binary Search + +A general method for searching for an element in an array is to use a for loop +that iterates through the elements of the array. For example, the following code +searches for an element x in an array: + +``` +for (int i = 0; i < n; i++) { + if (array[i] == x) { + // x found at index i + } +} +``` + +The time complexity of this approach is O(n), because in the worst case, it +is necessary to check all elements of the array. If the order of the elements is +arbitrary, this is also the best possible approach, because there is no additional +information available where in the array we should search for the element x. +However, if the array is sorted, the situation is different. In this case it is +possible to perform the search much faster, because the order of the elements in +the array guides the search. The following binary search algorithm efficiently +searches for an element in a sorted array in O(logn) time. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From d918ea54cd908e0dfd4375a3124e1ddf6dff0c14 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Mar 2023 23:13:23 +0530 Subject: [PATCH 0512/1894] add method 1 for binary search --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 3ed90267..0021aa2f 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,30 @@ possible to perform the search much faster, because the order of the elements in the array guides the search. The following binary search algorithm efficiently searches for an element in a sorted array in O(logn) time. +## Method 1 + +The usual way to implement binary search resembles looking for a word in a +dictionary. The search maintains an active region in the array, which initially +contains all array elements. Then, a number of steps is performed, each of which +halves the size of the region. +At each step, the search checks the middle element of the active region. If +the middle element is the target element, the search terminates. Otherwise, the +search recursively continues to the left or right half of the region, depending on +the value of the middle element. +The above idea can be implemented as follows: + +``` +int a = 0, b = n-1; +while (a <= b) { + int k = (a+b)/2; + if (array[k] == x) { + // x found at index k + } + if (array[k] > x) b = k-1; + else a = k+1; +} +``` + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 3c215ae73ce6f93362f0b88c74d070c0ae50a565 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Mar 2023 22:11:55 +0530 Subject: [PATCH 0513/1894] add method 2 --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/README.md b/README.md index 0021aa2f..83cb30bc 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,31 @@ while (a <= b) { } ``` +## Method 2 + +An alternative method to implement binary search is based on an efficient way to +iterate through the elements of the array. The idea is to make jumps and slow +the speed when we get closer to the target element. +The search goes through the array from left to right, and the initial jump +length is n/2. At each step, the jump length will be halved: first n/4, then n/8, +n/16, etc., until finally the length is 1. After the jumps, either the target element +has been found or we know that it does not appear in the array. +The following code implements the above idea: + +``` +int k = 0; +for (int b = n/2; b >= 1; b /= 2) { + while (k+b < n && array[k+b] <= x) k += b; +} +if (array[k] == x) { + // x found at index k +} +``` + +During the search, the variable b contains the current jump length. The +time complexity of the algorithm is O(logn), because the code in the while loop is +performed at most twice for each jump length. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From b7ca181f884f065e24d59bfb2c67ac5cd1aa49eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Mar 2023 22:17:25 +0530 Subject: [PATCH 0514/1894] add datastructures intro --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 83cb30bc..e408a060 100644 --- a/README.md +++ b/README.md @@ -12,13 +12,24 @@ 🌈 Everyone is welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). -#Intro +# Intro The design of algorithms consists of problem solving and mathematical thinking. Skills for analyzing problems and solving them creatively are needed. An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. +# Data structures + +A data structure is a way to store data in the memory of a computer. It is +important to choose an appropriate data structure for a problem, because each +data structure has its own advantages and disadvantages. The crucial question +is: which operations are efficient in the chosen data structure? + +- Dynamic arrays : A dynamic array is an array whose size can be changed during the execution of the program. +- Set structures : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. +- Map structures : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. + # Sorting Sorting is a fundamental algorithm design problem. Many efficient algorithms From 61f75c3e01bec90d5154061531cce2ffe1ebb50f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Mar 2023 22:20:47 +0530 Subject: [PATCH 0515/1894] add definition for dequeue stack and queue --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index e408a060..2b28e122 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,9 @@ is: which operations are efficient in the chosen data structure? - Dynamic arrays : A dynamic array is an array whose size can be changed during the execution of the program. - Set structures : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. - Map structures : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. +- Deque : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. +- Stack : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. +- Queue : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. # Sorting From b6fa2c3bf93fc421de4adbc48195ee6c5a611886 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Mar 2023 22:22:43 +0530 Subject: [PATCH 0516/1894] add definition for priority queue --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2b28e122..9c37935f 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ is: which operations are efficient in the chosen data structure? - Deque : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. - Stack : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. - Queue : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. +- Priority queue : A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take O(logn) time, and retrieval takes O(1) time. While an ordered set efficiently supports all the operations of a priority queue, the benefit of using a priority queue is that it has smaller constant factors. A priority queue is usually implemented using a heap structure that is much simpler than a balanced binary tree used in an ordered set. # Sorting From 6f5b58f8f740a95ad749673247456d26e4264e06 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Mar 2023 22:30:22 +0530 Subject: [PATCH 0517/1894] add links for Binary Search --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9c37935f..fc2c5130 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,10 @@ while (a <= b) { } ``` +## Example + +[Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search_iterative.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.py) + ## Method 2 An alternative method to implement binary search is based on an efficient way to From 2226c7b3ad1d9f1dc8e370f2479e034640048c12 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Mar 2023 23:04:05 +0530 Subject: [PATCH 0518/1894] add greedy algorithms --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index fc2c5130..57defb4b 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,17 @@ During the search, the variable b contains the current jump length. The time complexity of the algorithm is O(logn), because the code in the while loop is performed at most twice for each jump length. +# Greedy algorithms + +A greedy algorithm constructs a solution to the problem by always making a +choice that looks the best at the moment. A greedy algorithm never takes back +its choices, but directly constructs the final solution. For this reason, greedy +algorithms are usually very efficient. +The difficulty in designing greedy algorithms is to find a greedy strategy that +always produces an optimal solution to the problem. The locally optimal choices +in a greedy algorithm should also be globally optimal. It is often difficult to argue +that a greedy algorithm works. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 97cc2cfbcc0e69c75a5709af0580a564dcc7c4b4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Mar 2023 23:06:53 +0530 Subject: [PATCH 0519/1894] add coin problem --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 57defb4b..dea5c2d3 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,17 @@ always produces an optimal solution to the problem. The locally optimal choices in a greedy algorithm should also be globally optimal. It is often difficult to argue that a greedy algorithm works. +## Coin problem + +As a first example, we consider a problem where we are given a set of coins and +our task is to form a sum of money n using the coins. The values of the coins are +coins = `{c1, c2,..., ck}`, and each coin can be used as many times we want. What +is the minimum number of coins needed? +For example, if the coins are the euro coins (in cents) +`{1,2,5,10,20,50,100,200}` +and `n = 520`, we need at least four coins. The optimal solution is to select coins +`200 + 200 + 100 + 20` whose sum is `520`. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 486e205a1f9502a7260f20a7bd826f83079d3a84 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Mar 2023 23:11:09 +0530 Subject: [PATCH 0520/1894] add description for coin change --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index dea5c2d3..964a1802 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,28 @@ For example, if the coins are the euro coins (in cents) and `n = 520`, we need at least four coins. The optimal solution is to select coins `200 + 200 + 100 + 20` whose sum is `520`. +A simple greedy algorithm to the problem always selects the largest possible coin, +until the required sum of money has been constructed. This algorithm works in +the example case, because we first select two `200` cent coins, then one `100` cent +coin and finally one `20` cent coin. But does this algorithm always work? +It turns out that if the coins are the euro coins, the greedy algorithm always +works, i.e., it always produces a solution with the fewest possible number of coins. +The correctness of the algorithm can be shown as follows: +First, each coin `1, 5, 10, 50 and 100` appears at most once in an optimal +solution, because if the solution would contain two such coins, we could replace them by one coin and obtain a better solution. For example, if the solution would +contain coins `5 + 5`, we could replace them by coin 10. +In the same way, coins 2 and 20 appear at most twice in an optimal solution, +because we could replace coins `2 + 2 + 2` by coins `5 + 1` and coins `20 + 20 + 20` by +coins 50 + 10. Moreover, an optimal solution cannot contain coins `2 + 2 + 1` or +`20 + 20 + 10`, because we could replace them by coins 5 and 50. +Using these observations, we can show for each coin x that it is not possible +to optimally construct a sum x or any larger sum by only using coins that are +smaller than x. For example, `if x = 100`, the largest optimal sum using the smaller +coins is `50 + 20 + 20 + 5 + 2 + 2 = 99`. Thus, the greedy algorithm that always selects +the largest coin produces the optimal solution. +This example shows that it can be difficult to argue that a greedy algorithm +works, even if the algorithm itself is simple. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 8445d9df84171226ffea640f2fc19ecbef6f2f19 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 23 Mar 2023 23:14:13 +0530 Subject: [PATCH 0521/1894] add general case where greedy solution doesn't work --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 964a1802..b488ae6f 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,17 @@ the largest coin produces the optimal solution. This example shows that it can be difficult to argue that a greedy algorithm works, even if the algorithm itself is simple. +## General case + +In the general case, the coin set can contain any coins and the greedy algorithm +does not necessarily produce an optimal solution. +We can prove that a greedy algorithm does not work by showing a counterexample +where the algorithm gives a wrong answer. In this problem we can easily +find a counterexample: if the coins are `{1,3,4}` and the target sum is `6`, the greedy +algorithm produces the solution 4 + 1 + 1 while the optimal solution is `3 + 3`. +It is not known if the general coin problem can be solved using any greedy +algorithm. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From f4bd62f845b1c29292486c423a6d8961ece4fe65 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 24 Mar 2023 14:59:26 +0530 Subject: [PATCH 0522/1894] Readme fixed --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 8bd3f3e2..3b265ce7 100644 --- a/README.md +++ b/README.md @@ -19,13 +19,13 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) +- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) -- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) +- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/sum_of_three_values.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) -- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) +- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) # Pattern 2: Fast and Slow Pointers @@ -41,8 +41,8 @@ The key idea is that the pointers start at the same location, but they move forw ## Practice problems for fast and slow pointers -- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) -- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) -- Pallindrome Linked List -- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) -- Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) +- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_floyds_cycle_detection.cpp) +- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_compute_midpoint.cpp) +- Pallindrome Linked List +- Remove Kth node from end [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) +- Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) From b412a23456393e0ca9228e1815702ff7868684eb Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Fri, 24 Mar 2023 15:09:56 +0530 Subject: [PATCH 0523/1894] word changed --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec5482e5..15e039bd 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ The pointers can be used to iterate the data structure in one or both directions - Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) -- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.js) +- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) - Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) From 987dee44204652f5aad3acbffb4233a83d0b6c13 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Mar 2023 22:29:52 +0530 Subject: [PATCH 0524/1894] add dynamic programming --- README.md | 133 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 70 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index 15e039bd..2a1825e6 100644 --- a/README.md +++ b/README.md @@ -26,13 +26,13 @@ important to choose an appropriate data structure for a problem, because each data structure has its own advantages and disadvantages. The crucial question is: which operations are efficient in the chosen data structure? -- Dynamic arrays : A dynamic array is an array whose size can be changed during the execution of the program. -- Set structures : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. -- Map structures : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. -- Deque : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. -- Stack : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. -- Queue : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. -- Priority queue : A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take O(logn) time, and retrieval takes O(1) time. While an ordered set efficiently supports all the operations of a priority queue, the benefit of using a priority queue is that it has smaller constant factors. A priority queue is usually implemented using a heap structure that is much simpler than a balanced binary tree used in an ordered set. +- Dynamic arrays : A dynamic array is an array whose size can be changed during the execution of the program. +- Set structures : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. +- Map structures : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. +- Deque : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. +- Stack : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. +- Queue : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. +- Priority queue : A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take O(logn) time, and retrieval takes O(1) time. While an ordered set efficiently supports all the operations of a priority queue, the benefit of using a priority queue is that it has smaller constant factors. A priority queue is usually implemented using a heap structure that is much simpler than a balanced binary tree used in an ordered set. # Sorting @@ -58,11 +58,11 @@ Even though languages have built-in sorting method, sorting is a great example o ### Well known sorting algorithms -- Bubble Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.py) -- Insertion Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.py) -- Selection Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.py) -- Merge Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.py) -- Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) +- Bubble Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/bubble_sort.py) +- Insertion Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.py) +- Selection Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.py) +- Merge Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.py) +- Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) # Binary Search @@ -195,6 +195,13 @@ algorithm produces the solution 4 + 1 + 1 while the optimal solution is `3 + 3`. It is not known if the general coin problem can be solved using any greedy algorithm. +# Dynamic programming + +Dynamic programming is a technique that combines the correctness of complete +search and the efficiency of greedy algorithms. Dynamic programming can +be applied if the problem can be divided into overlapping subproblems that can +be solved independently. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. @@ -203,15 +210,15 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) +- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) -- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) +- Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) -- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) +- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) -- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) +- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) # Pattern 2: Fast and Slow Pointers @@ -227,12 +234,12 @@ The key idea is that the pointers start at the same location, but they move forw ## Practice problems for fast and slow pointers -- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) -- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) -- Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) -- Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) -- Remove Kth node from end [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_kth_from_end.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) -- Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) +- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) +- Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) +- Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) +- Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) +- Remove Kth node from end [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_kth_from_end.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_remove_nth_node_from_end.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/remove_kth_node_from_end.py) +- Linked List Sort List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/liniked_list_sort_list.cpp) # Pattern 3: Sliding Window @@ -248,11 +255,11 @@ Instead, what if we focused on the element entering the window and the one leavi ## Practice problems for sliding window -- Find Maximum in Sliding Window [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.py) -- Minimum Window Subsequence -- Repeated DNA Sequences -- Minimum Window Substring -- Longest Substring without Repeating Characters [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/longest_substring_without_repeating_characters.go) +- Find Maximum in Sliding Window [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/sliding_window_max.py) +- Minimum Window Subsequence +- Repeated DNA Sequences +- Minimum Window Substring +- Longest Substring without Repeating Characters [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Sliding%20Window/longest_substring_without_repeating_characters.go) # Pattern 4: Merge Interval @@ -264,19 +271,19 @@ The key to understanding this pattern and exploiting its power lies in understan Many problems in the real world use the merge intervals pattern. Let’s look at some examples. -- Display busy schedule: Display the busy hours of a user to other users without revealing the individual meeting slots in a calendar. +- Display busy schedule: Display the busy hours of a user to other users without revealing the individual meeting slots in a calendar. -- Schedule a new meeting: Add a new meeting to the tentative meeting schedule of a user in such a way that no two meetings overlap each other. +- Schedule a new meeting: Add a new meeting to the tentative meeting schedule of a user in such a way that no two meetings overlap each other. -- Task scheduling in operating systems (OS): Schedule tasks for the OS based on task priority and the free slots in the machine’s processing schedule. +- Task scheduling in operating systems (OS): Schedule tasks for the OS based on task priority and the free slots in the machine’s processing schedule. ## Practice problems for merge intervals -- Merge Intervals -- Insert Interval -- Interval List Intersections -- Employee Free Time -- Meeting Rooms +- Merge Intervals +- Insert Interval +- Interval List Intersections +- Employee Free Time +- Meeting Rooms # Pattern 5: In-place Reversal of a Linked List @@ -293,12 +300,12 @@ Similarly, for space complexity: the naive approach requires the use of addition ## Practice problems for in-place reversal of a linked list -- Reverse Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_reverse.cpp) -- Reverse Nodes in k-group -- Reorder List -- Swapping Nodes in a Linked List -- Swapping Nodes in Pairs [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_swap_nodes_in_pair.cpp) -- Reverse Nodes in Even Length Groups +- Reverse Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_reverse.cpp) +- Reverse Nodes in k-group +- Reorder List +- Swapping Nodes in a Linked List +- Swapping Nodes in Pairs [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_swap_nodes_in_pair.cpp) +- Reverse Nodes in Even Length Groups # Pattern 6: Two Heaps @@ -312,15 +319,15 @@ There might be cases where we need to find the two largest numbers from two diff Many problems in the real world use the two heaps pattern. Let’s look at some examples. -- Video streaming: During a user session, there is often a possibility that packet drops and buffering might occur. We want to record the median number of buffering events that might occur in a particular session, which could then be used to improve the user experience. +- Video streaming: During a user session, there is often a possibility that packet drops and buffering might occur. We want to record the median number of buffering events that might occur in a particular session, which could then be used to improve the user experience. -- Netflix: As part of a demographic study, we’re interested in the median age of our viewers. We want to implement a functionality whereby the median age can be updated efficiently whenever a new user signs up for video streaming. +- Netflix: As part of a demographic study, we’re interested in the median age of our viewers. We want to implement a functionality whereby the median age can be updated efficiently whenever a new user signs up for video streaming. ## Practice problems for two heaps -- Maximize Capital -- Find Median from a data stream -- Schedule Tasks on minimum machines +- Maximize Capital +- Find Median from a data stream +- Schedule Tasks on minimum machines # Pattern 7: K-way Merge @@ -336,18 +343,18 @@ Here is what the pattern looks like: Many problems in the real world use the k-way merge pattern. Let’s look at some examples. -- Merge tweets in twitter feed: Sometimes we need to implement a module that adds a user’s Tweets into an already populated Twitter feed in chronological order. +- Merge tweets in twitter feed: Sometimes we need to implement a module that adds a user’s Tweets into an already populated Twitter feed in chronological order. -- Used in external sorting procedures: When an algorithm is processing huge amounts of data, it needs to repeatedly fetch it from external storage because RAM capacity is fixed. To overcome the speed limitation of external storage, k-way merges are used in external sorting. Let’s consider a case where we need to perform six merges. A binary merge requires three merge passes while a 6-way merge only requires one pass. K-way merge reduces the number of accesses to external storage, which in turn greatly improves performance when dealing with large amounts of data. +- Used in external sorting procedures: When an algorithm is processing huge amounts of data, it needs to repeatedly fetch it from external storage because RAM capacity is fixed. To overcome the speed limitation of external storage, k-way merges are used in external sorting. Let’s consider a case where we need to perform six merges. A binary merge requires three merge passes while a 6-way merge only requires one pass. K-way merge reduces the number of accesses to external storage, which in turn greatly improves performance when dealing with large amounts of data. ## Practice problems for k-way Merge -- Merge Sorted Array -- Kth smallest number in M sorted list -- Find K pairs with smallest sums -- Merge K sorted lists -- Kth Smallest element in a sorted matrix -- Median of two sorted arrays +- Merge Sorted Array +- Kth smallest number in M sorted list +- Find K pairs with smallest sums +- Merge K sorted lists +- Kth Smallest element in a sorted matrix +- Median of two sorted arrays # Pattern 8: Top K Elements @@ -366,15 +373,15 @@ Iterating the complete list takes O(n) time, and the heap takes O(logk) time for Many problems in the real world use the top K elements pattern. Let’s look at some examples. -- Uber: Select at least the n nearest drivers within the user’s vicinity, avoiding the drivers that are too far away. +- Uber: Select at least the n nearest drivers within the user’s vicinity, avoiding the drivers that are too far away. -- Stocks: Given the set of IDs of brokers, determine the top K broker’s performance with the frequently repeated IDs in the given data set. +- Stocks: Given the set of IDs of brokers, determine the top K broker’s performance with the frequently repeated IDs in the given data set. ## Practice problems for Top K Elements -- Kth largest element in a stream -- Reorganize string -- K closest point to origin -- Top K frequent element -- Kth largest element in an array -- Kth smallest element in an BST +- Kth largest element in a stream +- Reorganize string +- K closest point to origin +- Top K frequent element +- Kth largest element in an array +- Kth smallest element in an BST From 3c7b4173043a0e6cd0a7b02587f2fa6676af12b2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Mar 2023 22:32:03 +0530 Subject: [PATCH 0525/1894] add uses --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 2a1825e6..2c059e4a 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,11 @@ search and the efficiency of greedy algorithms. Dynamic programming can be applied if the problem can be divided into overlapping subproblems that can be solved independently. +There are two uses for dynamic programming: + +- Finding an optimal solution: We want to find a solution that is as large as possible or as small as possible. +- Counting the number of solutions: We want to calculate the total number of possible solutions. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From cffeb13dd925d213612acd4b0995904da751426f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Mar 2023 22:35:01 +0530 Subject: [PATCH 0526/1894] add coin problem example using greedy algo --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index 2c059e4a..65426abc 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,22 @@ There are two uses for dynamic programming: - Finding an optimal solution: We want to find a solution that is as large as possible or as small as possible. - Counting the number of solutions: We want to calculate the total number of possible solutions. +## Coin problem + +We first focus on a problem that we have already seen in Greedy Algorithm Given a set +of coin values coins = `{c1, c2,..., ck}` and a target sum of money n, our task is to +form the sum n using as few coins as possible. +We solved the problem using a greedy algorithm that always +chooses the largest possible coin. The greedy algorithm works, for example, when +the coins are the euro coins, but in the general case the greedy algorithm does +not necessarily produce an optimal solution. +Now is time to solve the problem efficiently using dynamic programming, so +that the algorithm works for any coin set. The dynamic programming algorithm +is based on a recursive function that goes through all possibilities how to form +the sum, like a brute force algorithm. However, the dynamic programming +algorithm is efficient because it uses memoization and calculates the answer to +each subproblem only once. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 36d6e157521205a14e955b5eb6de62196e5778f3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Mar 2023 22:40:28 +0530 Subject: [PATCH 0527/1894] add idea behind solution --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 65426abc..46d41333 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,25 @@ the sum, like a brute force algorithm. However, the dynamic programming algorithm is efficient because it uses memoization and calculates the answer to each subproblem only once. +The idea in dynamic programming is to formulate the problem recursively so +that the solution to the problem can be calculated from solutions to smaller +subproblems. In the coin problem, a natural recursive problem is as follows: what +is the smallest number of coins required to form a sum x? +Let solve(x) denote the minimum number of coins required for a sum x. +The values of the function depend on the values of the coins. For example, if +`coins = {1,3,4}`, the first values of the function are as follows: +solve(0) = 0 +solve(1) = 1 +solve(2) = 2 +solve(3) = 1 +solve(4) = 1 +solve(5) = 2 +solve(6) = 2 +solve(7) = 2 +solve(8) = 2 +solve(9) = 3 +solve(10) = 3 + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 0675d622c70306883f7267d0e807352f58c947fa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Mar 2023 22:15:50 +0530 Subject: [PATCH 0528/1894] add example --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 46d41333..53d8c470 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,15 @@ solve(8) = 2 solve(9) = 3 solve(10) = 3 +For example, `solve(10) = 3`, because at least 3 coins are needed to form the +sum `10`. The optimal solution is `3 + 3 + 4 = 10`. +The essential property of solve is that its values can be recursively calculated +from its smaller values. The idea is to focus on the first coin that we choose for +the sum. For example, in the above scenario, the first coin can be either `1, 3 +or 4`. If we first choose coin `1`, the remaining task is to form the sum 9 using +the minimum number of coins, which is a subproblem of the original problem. +Of course, the same applies to coins` 3 and 4`. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From ccf6df64e57e6896adc02ad9f735bec5981a7b48 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Mar 2023 22:18:10 +0530 Subject: [PATCH 0529/1894] add recursive formula --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 53d8c470..55af697d 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,11 @@ or 4`. If we first choose coin `1`, the remaining task is to form the sum 9 usin the minimum number of coins, which is a subproblem of the original problem. Of course, the same applies to coins` 3 and 4`. +Thus, we can use the following recursive formula to calculate the minimum number of coins: +solve(x) = min(solve(x - 1) + 1, +solve(x - 3) + 1, +solve(x - 4) + 1). + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From b54eec2366c582c209c5bc06cf8bed76eca07cf8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Mar 2023 22:19:58 +0530 Subject: [PATCH 0530/1894] add base case --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 55af697d..efb5b78a 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,9 @@ solve(x) = min(solve(x - 1) + 1, solve(x - 3) + 1, solve(x - 4) + 1). +The base case of the recursion is solve(0) Æ 0, because no coins are needed to form an empty sum. For example, +solve(10) = solve(7) + 1 = solve(4) + 2 = solve(0) + 3 = 3. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From e01e2ea9f55641bff8dfafea66d979560f2d1e1d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Mar 2023 22:26:38 +0530 Subject: [PATCH 0531/1894] add recursive formula --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index efb5b78a..1e5cd977 100644 --- a/README.md +++ b/README.md @@ -256,9 +256,14 @@ solve(x) = min(solve(x - 1) + 1, solve(x - 3) + 1, solve(x - 4) + 1). -The base case of the recursion is solve(0) Æ 0, because no coins are needed to form an empty sum. For example, +The base case of the recursion is solve(0) Æ 0, because no coins are needed to form an empty sum. For example, solve(10) = solve(7) + 1 = solve(4) + 2 = solve(0) + 3 = 3. +Now we are ready to give a general recursive function that calculates the minimum number of coins needed to form a sum x: +solve(x) = Infinity if x < 0 +solve(x) = 0 if x == 0 +solve(x) = min(c --> coins) ==> solve(x - c) + 1, if x > 0 + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 4b3d9cf814bef72b401ae6723abaa9cecd516904 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Mar 2023 22:29:04 +0530 Subject: [PATCH 0532/1894] add solution for recursive formula --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index 1e5cd977..dd849e8f 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,20 @@ solve(x) = Infinity if x < 0 solve(x) = 0 if x == 0 solve(x) = min(c --> coins) ==> solve(x - c) + 1, if x > 0 +Once a recursive function that solves the problem has been found, we can +directly implement a solution, (the constant INF denotes infinity): + +```` +int solve(int x) { + if (x < 0) return INF; + if (x == 0) return 0; + int best = INF; + for (auto c : coins) { + best = min(best, solve(x-c)+1); + } + return best; +}``` + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. @@ -447,3 +461,4 @@ Many problems in the real world use the top K elements pattern. Let’s look at - Top K frequent element - Kth largest element in an array - Kth smallest element in an BST +```` From b9296eb1462e980a08ef8126edea071f8668775b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:15:18 +0530 Subject: [PATCH 0533/1894] fix insertion sort --- sorting/insertion_sort.cpp | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 050155d1..0b4e274d 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -20,23 +20,21 @@ Output: [-1 0 1 2 3 4 10] #include using namespace std; -void InsertionSort(int A[], int n){ - int flag = 0; - for(int i = 1; i < n; i++){ - int hole = i; - int value = A[i]; - while(hole > 0 && A[hole-1] > value){ - A[hole] = A[hole-1]; - hole = hole - 1; - } - A[hole] = value; - } -} + int main(){ - int A[] = {5,9,77,1,2,3,4,5}; - InsertionSort(A,6); + int temp = 0; + int array[] = {5,9,77,1,2,3}; + for (int i = 1; i < 6; i++) { + int j = i; + while (j > 0 && array[j] < array[j - 1]) { + temp = array[j]; + array[j] = array[j - 1]; + array[j - 1] = temp; + j -= 1; + } + } for(int i = 0; i < 6; i++){ - cout << A[i] << " "; + cout << array[i] << " "; } return 0; From a5ea5f8dcdcf2b962eda377d2a107c3b7584bc40 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:22:48 +0530 Subject: [PATCH 0534/1894] improve insertion sort for go --- sorting/insertion_sort.go | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/sorting/insertion_sort.go b/sorting/insertion_sort.go index 7d6f24b2..b5ce2273 100644 --- a/sorting/insertion_sort.go +++ b/sorting/insertion_sort.go @@ -27,14 +27,12 @@ func main() { fmt.Print(a_lst) } -func insertion_sort(a_lst []int) { - for index := 1; index < len(a_lst); index++ { - val := a_lst[index] - position := index - 1 - for 0 <= position && val < a_lst[position] { - a_lst[position+1] = a_lst[position] - position-- - } - a_lst[position+1] = val - } +func insertion_sort(array []int) { + for i := 1; i < len(array); i++ { + j := i + for j > 0 && array[j] < array[j - 1] { + array[j], array[j - 1] = array[j - 1], array[j] + j -= 1 + } + } } From 37ebac96f9f14b529d6c3ec15036edae556baf6a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:23:56 +0530 Subject: [PATCH 0535/1894] add comments --- sorting/insertion_sort.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sorting/insertion_sort.go b/sorting/insertion_sort.go index b5ce2273..d6eaf0e6 100644 --- a/sorting/insertion_sort.go +++ b/sorting/insertion_sort.go @@ -27,6 +27,12 @@ func main() { fmt.Print(a_lst) } +/* + Divide the input array into two subarrays in place. The first subarray should be sorted at all times + and should start with a length of 1, while the second subarray should be unsorted. + Iterate through the unsorted subarray, inserting all of its elements into the sorted subarray + in the correct position by swapping them into place. Eventually, the entire array will be sorted. +*/ func insertion_sort(array []int) { for i := 1; i < len(array); i++ { j := i From fa558a26200f13146b0a5c245243966dbd211def Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:27:04 +0530 Subject: [PATCH 0536/1894] rename file --- .../{bubble_sort_recursive.cpp => recursive_bubble_sort.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{bubble_sort_recursive.cpp => recursive_bubble_sort.cpp} (100%) diff --git a/Recursion/bubble_sort_recursive.cpp b/Recursion/recursive_bubble_sort.cpp similarity index 100% rename from Recursion/bubble_sort_recursive.cpp rename to Recursion/recursive_bubble_sort.cpp From 9552628267fae7995627a9d8acf7a3f30315db7f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:27:43 +0530 Subject: [PATCH 0537/1894] rename file --- Recursion/{count_zeroes.go => count_zeros.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Recursion/{count_zeroes.go => count_zeros.go} (100%) diff --git a/Recursion/count_zeroes.go b/Recursion/count_zeros.go similarity index 100% rename from Recursion/count_zeroes.go rename to Recursion/count_zeros.go From 495ac34a684797c3d35342174a93571495213537 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:28:47 +0530 Subject: [PATCH 0538/1894] rename file --- ...h_node_from_end.py => linked_list_remove_kth_node_from_end.py} | 0 ...h_node_from_end.py => linked_list_remove_nth_node_from_end.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Linked List/{remove_kth_node_from_end.py => linked_list_remove_kth_node_from_end.py} (100%) rename Linked List/{linkedlist_remove_nth_node_from_end.py => linked_list_remove_nth_node_from_end.py} (100%) diff --git a/Linked List/remove_kth_node_from_end.py b/Linked List/linked_list_remove_kth_node_from_end.py similarity index 100% rename from Linked List/remove_kth_node_from_end.py rename to Linked List/linked_list_remove_kth_node_from_end.py diff --git a/Linked List/linkedlist_remove_nth_node_from_end.py b/Linked List/linked_list_remove_nth_node_from_end.py similarity index 100% rename from Linked List/linkedlist_remove_nth_node_from_end.py rename to Linked List/linked_list_remove_nth_node_from_end.py From c9fc98f0fa7ef8d588ba5af546b3012c5ce61663 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:29:38 +0530 Subject: [PATCH 0539/1894] remove duplicate file --- Hash Table/first_repeating_character.go | 30 ------------------------- 1 file changed, 30 deletions(-) delete mode 100644 Hash Table/first_repeating_character.go diff --git a/Hash Table/first_repeating_character.go b/Hash Table/first_repeating_character.go deleted file mode 100644 index 97143f3e..00000000 --- a/Hash Table/first_repeating_character.go +++ /dev/null @@ -1,30 +0,0 @@ -// Give an algorithm for printing the first repeated character if there are duplicated elements in it - -package main - -import "fmt" - -// FirstRepeatedCharacter: returns the first repeating character -// Approach: we know extended ascii has 256 values, so create an array with length 256 -// initialize with all zeroes. -// Each of input character in word go to the corresponding position and increment its count -// while scanning the array if we see some value is already 1 then return the value -func FirstRepeatedCharacter(word string) byte { - lengthOfString := len(word) - // The maximum number of characters that can be represented in extended ASCII is 256 - asciiArr := [256]int{} - for i := 0; i < 256; i++ { - asciiArr[i] = 0 - } - for i := 0; i < lengthOfString; i++ { - if asciiArr[word[i]] == 1 { - return word[i] - } - asciiArr[word[i]]++ - } - return byte(0) -} - -func main() { - fmt.Printf("%c", FirstRepeatedCharacter("abcdefghe")); -} \ No newline at end of file From 03ba849ff710136620e66cdc991149f111202f1e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 26 Mar 2023 21:30:31 +0530 Subject: [PATCH 0540/1894] remove duplicate file and rename file --- Math/check_if_num_is_palindrome.cpp | 41 ------------------- ...is_palindrome.py => pallindrome_number.py} | 0 2 files changed, 41 deletions(-) delete mode 100644 Math/check_if_num_is_palindrome.cpp rename Math/{check_if_num_is_palindrome.py => pallindrome_number.py} (100%) diff --git a/Math/check_if_num_is_palindrome.cpp b/Math/check_if_num_is_palindrome.cpp deleted file mode 100644 index 7cfe4c2f..00000000 --- a/Math/check_if_num_is_palindrome.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - Given an integer x, return true if x is a - palindrome - , and false otherwise. - - Example 1: - Input: x = 121 - Output: true - Explanation: 121 reads as 121 from left to right and from right to left. - - Example 2: - Input: x = -121 - Output: false - Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. - - Example 3: - Input: x = 10 - Output: false - Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - Constraints: - -231 <= x <= 231 - 1 - - Follow up: Could you solve it without converting the integer to a string? -*/ -class Solution { -public: - bool isPalindrome(int num) { - - if (num < 0 || (num % 10 == 0 && num != 0)) { - return false; - } - - int reversed = 0; - while (num > reversed) { - reversed = reversed * 10 + num % 10; - num /= 10; - } - - return num == reversed || num == reversed / 10; - } -}; \ No newline at end of file diff --git a/Math/check_if_num_is_palindrome.py b/Math/pallindrome_number.py similarity index 100% rename from Math/check_if_num_is_palindrome.py rename to Math/pallindrome_number.py From 70dbaf57411e8e7b2b13460cbefcd0fa57961b45 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:42:57 +0530 Subject: [PATCH 0541/1894] refactor code --- Math/pallindrome_number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Math/pallindrome_number.py b/Math/pallindrome_number.py index b211df50..7b04f550 100644 --- a/Math/pallindrome_number.py +++ b/Math/pallindrome_number.py @@ -25,12 +25,12 @@ class Solution: def isPalindrome(self, x: int) -> bool: #check if the number is less than zero. - if(x<0): + if x < 0: return False #Then, calculating the reverse of the number to see if it is equal to the original number. rev = 0 original_value = x while x != 0: rev = rev * 10 + x % 10 - x = x// 10 + x = x // 10 return rev == original_value \ No newline at end of file From d27395f2cc9fef28ef470a93d72c44ef60f8e128 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:51:16 +0530 Subject: [PATCH 0542/1894] fix readme and add memoization --- README.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dd849e8f..3553f787 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ solve(x) = min(c --> coins) ==> solve(x - c) + 1, if x > 0 Once a recursive function that solves the problem has been found, we can directly implement a solution, (the constant INF denotes infinity): -```` +``` int solve(int x) { if (x < 0) return INF; if (x == 0) return 0; @@ -276,7 +276,15 @@ int solve(int x) { best = min(best, solve(x-c)+1); } return best; -}``` +} +``` + +Still, this function is not efficient, because there may be an exponential number of ways to construct the sum. However, next we will see how to make the function efficient using a technique called memoization. + +## Using memoization + +The idea of dynamic programming is to use memoization to efficiently calculate values of a recursive function. This means that the values of the function are stored in an array after calculating them. For each parameter, the value of the function is calculated recursively only once, and after this, the value can be +directly retrieved from the array. # Pattern 1: Two Pointers @@ -461,4 +469,7 @@ Many problems in the real world use the top K elements pattern. Let’s look at - Top K frequent element - Kth largest element in an array - Kth smallest element in an BST -```` + +``` + +``` From d80bda177e7104780fe8b51dfbc3d721e716f49e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:53:07 +0530 Subject: [PATCH 0543/1894] add program --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index 3553f787..693e928c 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,32 @@ Still, this function is not efficient, because there may be an exponential numbe The idea of dynamic programming is to use memoization to efficiently calculate values of a recursive function. This means that the values of the function are stored in an array after calculating them. For each parameter, the value of the function is calculated recursively only once, and after this, the value can be directly retrieved from the array. +In this problem, we use arrays + +``` +bool ready[N]; +int value[N]; +``` + +where `ready[x]` indicates whether the value of `solve(x)` has been calculated, +and if it is, `value[x]` contains this value. The constant `N` has been chosen so that all required values fit in the arrays. +Now the function can be efficiently implemented as follows: + +``` +int solve(int x) { + if (x < 0) return INF; + if (x == 0) return 0; + if (ready[x]) return value[x]; + int best = INF; + for (auto c : coins) { + best = min(best, solve(x-c)+1); + } + value[x] = best; + ready[x] = true; + return best; +} +``` + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 050963df1cc3de1c3b2b79af20a00dd423d29104 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:56:30 +0530 Subject: [PATCH 0544/1894] highlight c++ code --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 693e928c..73cd7187 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ where `ready[x]` indicates whether the value of `solve(x)` has been calculated, and if it is, `value[x]` contains this value. The constant `N` has been chosen so that all required values fit in the arrays. Now the function can be efficiently implemented as follows: -``` +```cpp int solve(int x) { if (x < 0) return INF; if (x == 0) return 0; From 2e5a4f2f2910d293592b2cfb9da7074d679482c9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:58:13 +0530 Subject: [PATCH 0545/1894] highlight cpp code --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 73cd7187..72eb28d5 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ n/16, etc., until finally the length is 1. After the jumps, either the target el has been found or we know that it does not appear in the array. The following code implements the above idea: -``` +```cpp int k = 0; for (int b = n/2; b >= 1; b /= 2) { while (k+b < n && array[k+b] <= x) k += b; @@ -267,7 +267,7 @@ solve(x) = min(c --> coins) ==> solve(x - c) + 1, if x > 0 Once a recursive function that solves the problem has been found, we can directly implement a solution, (the constant INF denotes infinity): -``` +```cpp int solve(int x) { if (x < 0) return INF; if (x == 0) return 0; @@ -288,7 +288,7 @@ directly retrieved from the array. In this problem, we use arrays -``` +```cpp bool ready[N]; int value[N]; ``` From 833c2aed2ca3c7e72e5dcb3eaf41aa78d8f5e29e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 22:59:35 +0530 Subject: [PATCH 0546/1894] highlight c++ and js code --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 72eb28d5..d8a2e80f 100644 --- a/README.md +++ b/README.md @@ -48,10 +48,10 @@ how to apply different algorithm design techniques. The efficient general sortin algorithms work in O(nlogn) time, and many algorithms that use sorting as a subroutine also have this time complexity. -``` +```js heights = [6, 5, 4, 5, 2, 3]; heights.sort(); -Output : [2, 3, 4, 5, 5, 6] +Output: [2, 3, 4, 5, 5, 6]; ``` Even though languages have built-in sorting method, sorting is a great example of how there may be many ways to think about the same problem, some perhaps better than others. Understanding sorting is a traditional first step towards mastery of algorithms and computer science. @@ -70,7 +70,7 @@ A general method for searching for an element in an array is to use a for loop that iterates through the elements of the array. For example, the following code searches for an element x in an array: -``` +```cpp for (int i = 0; i < n; i++) { if (array[i] == x) { // x found at index i @@ -99,7 +99,7 @@ search recursively continues to the left or right half of the region, depending the value of the middle element. The above idea can be implemented as follows: -``` +```cpp int a = 0, b = n-1; while (a <= b) { int k = (a+b)/2; From ce9f50c436c31b7a209c472e019f88b3481d1442 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 27 Mar 2023 23:02:43 +0530 Subject: [PATCH 0547/1894] add new heading --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8a2e80f..21443394 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ # Implementation of well known Data Structures and Algorithms -🌈 Everyone is welcome! +Contributions are welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). # Intro From 096d602ddf0bcf5df21e038de6a2b1585c606525 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Mar 2023 18:56:47 +0530 Subject: [PATCH 0548/1894] highlight topics --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 21443394..3c0525b9 100644 --- a/README.md +++ b/README.md @@ -26,13 +26,13 @@ important to choose an appropriate data structure for a problem, because each data structure has its own advantages and disadvantages. The crucial question is: which operations are efficient in the chosen data structure? -- Dynamic arrays : A dynamic array is an array whose size can be changed during the execution of the program. -- Set structures : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. -- Map structures : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. -- Deque : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. -- Stack : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. -- Queue : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. -- Priority queue : A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take O(logn) time, and retrieval takes O(1) time. While an ordered set efficiently supports all the operations of a priority queue, the benefit of using a priority queue is that it has smaller constant factors. A priority queue is usually implemented using a heap structure that is much simpler than a balanced binary tree used in an ordered set. +- `Dynamic arrays` : A dynamic array is an array whose size can be changed during the execution of the program. +- `Set structures` : A set is a data structure that maintains a collection of elements. The basic operations of sets are element insertion, search and removal. +- `Map structures` : A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0,1,...,n-1, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values. +- `Deque` : A deque is a dynamic array whose size can be efficiently changed at both ends of the array. Like a vector, a deque provides the functions push_back and pop_back, but it also includes the functions push_front and pop_front which are not available in a vector. +- `Stack` : A stack is a data structure that provides two O(1) time operations: adding an element to the top, and removing an element from the top. It is only possible to access the top element of a stack. +- `Queue` : A queue also provides two O(1) time operations: adding an element to the end of the queue, and removing the first element in the queue. It is only possible to access the first and last element of a queue. +- `Priority queue` : A priority queue maintains a set of elements. The supported operations are insertion and, depending on the type of the queue, retrieval and removal of either the minimum or maximum element. Insertion and removal take O(logn) time, and retrieval takes O(1) time. While an ordered set efficiently supports all the operations of a priority queue, the benefit of using a priority queue is that it has smaller constant factors. A priority queue is usually implemented using a heap structure that is much simpler than a balanced binary tree used in an ordered set. # Sorting From 02733e8e86980b9fe4afe750bb27f020208d5997 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Mar 2023 18:58:17 +0530 Subject: [PATCH 0549/1894] highlight value of function --- README.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 3c0525b9..418a6b05 100644 --- a/README.md +++ b/README.md @@ -229,18 +229,20 @@ subproblems. In the coin problem, a natural recursive problem is as follows: wha is the smallest number of coins required to form a sum x? Let solve(x) denote the minimum number of coins required for a sum x. The values of the function depend on the values of the coins. For example, if -`coins = {1,3,4}`, the first values of the function are as follows: -solve(0) = 0 -solve(1) = 1 -solve(2) = 2 -solve(3) = 1 -solve(4) = 1 -solve(5) = 2 -solve(6) = 2 -solve(7) = 2 -solve(8) = 2 -solve(9) = 3 +`coins = {1,3,4}`, the first values of the function are as follows: + +```solve(0) = 0 +solve(1) = 1 +solve(2) = 2 +solve(3) = 1 +solve(4) = 1 +solve(5) = 2 +solve(6) = 2 +solve(7) = 2 +solve(8) = 2 +solve(9) = 3 solve(10) = 3 +``` For example, `solve(10) = 3`, because at least 3 coins are needed to form the sum `10`. The optimal solution is `3 + 3 + 4 = 10`. From c04337f90ab6099449cbd7920e43e9d890e448fd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 28 Mar 2023 19:00:46 +0530 Subject: [PATCH 0550/1894] add amortized analysis --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 418a6b05..86acae04 100644 --- a/README.md +++ b/README.md @@ -314,6 +314,11 @@ int solve(int x) { } ``` +# Amortized analysis + +The time complexity of an algorithm is often easy to analyze just by examining the structure of the algorithm: what loops does the algorithm contain and how many times the loops are performed. However, sometimes a straightforward analysis does not give a true picture of the efficiency of the algorithm. +Amortized analysis can be used to analyze algorithms that contain operations whose time complexity varies. The idea is to estimate the total time used to all such operations during the execution of the algorithm, instead of focusing on individual operations. + # Pattern 1: Two Pointers As the name suggests, the two pointers pattern uses two pointers to iterate over an array or list until the conditions of the problem are satisfied. This is useful because it allows us to keep track of the values of two different indexes in a single iteration. Whenever there’s a requirement to find two data elements in an array that satisfy a certain condition, the two pointers pattern should be the first strategy to come to mind. From 169ca1f0814d1ccb261445a907d143bd5248e6bf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 22:56:32 +0530 Subject: [PATCH 0551/1894] add time complexity --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 86acae04..df6c915e 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ thinking. Skills for analyzing problems and solving them creatively are needed. An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. +# Time complexity + +The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. + # Data structures A data structure is a way to store data in the memory of a computer. It is From 2ad4e40ac00695a76bb6bee6d4087f0d64d1a985 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 22:57:50 +0530 Subject: [PATCH 0552/1894] add calculation rules --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index df6c915e..5eb3b60a 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,10 @@ core of the problem is often about inventing an efficient algorithm. The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. +## Calculation rules + +The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. + # Data structures A data structure is a way to store data in the memory of a computer. It is From 3d2b85221209cd563cbc006b11b868d622b51953 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 23:00:28 +0530 Subject: [PATCH 0553/1894] add loops --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 5eb3b60a..323570e1 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,10 @@ The efficiency of algorithms is important. Usually, it is easy to design an algo The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. +## Loops + +A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). + # Data structures A data structure is a way to store data in the memory of a computer. It is From 5a2ae56c3b4ef6a88519b91fb1bf2100e3a93071 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 23:01:44 +0530 Subject: [PATCH 0554/1894] add basic time complexity --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index 323570e1..46068652 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,24 @@ The time complexity of an algorithm is denoted `O(...)` where the three dots rep A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). +For example, the time complexity of the following code is O(n): + +```cpp +for (int i = 1; i <= n; i++) { + // code +} +``` + +And the time complexity of the following code is O(n^2): + +```cpp +for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // code + } +} +``` + # Data structures A data structure is a way to store data in the memory of a computer. It is From 58ee14ed6bf079a9391c89f6585dfef73c81c940 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 23:05:15 +0530 Subject: [PATCH 0555/1894] add order of magnitude --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index 46068652..74239a65 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,38 @@ for (int i = 1; i <= n; i++) { } ``` +## Order of magnitude + +A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). + +```cpp +for (int i = 1; i <= 3*n; i++) { + // code +} +``` + +```cpp +for (int i = 1; i <= n+5; i++) { + // code +} +``` + +```cpp +for (int i = 1; i <= n; i += 2) { +// code +} +``` + +As another example, the time complexity of the following code is O(n^2): + +```cpp +for (int i = 1; i <= n; i++) { + for (int j = i+1; j <= n; j++) { + // code + } +} +``` + # Data structures A data structure is a way to store data in the memory of a computer. It is From 62e01ad3bf2d34d9e10f987dc1d8f2dde5fb8bd6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 23:07:35 +0530 Subject: [PATCH 0556/1894] add phases --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index 74239a65..0e6a12b4 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,24 @@ for (int i = 1; i <= n; i++) { } ``` +## Phases + +If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). + +```cpp +for (int i = 1; i <= n; i++) { + // code +} +for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // code + } +} +for (int i = 1; i <= n; i++) { +// code +} +``` + # Data structures A data structure is a way to store data in the memory of a computer. It is From 14d0987d0002d8166abcbf0d1df2df81574fbacf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 29 Mar 2023 23:09:26 +0530 Subject: [PATCH 0557/1894] add example with several variables --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 0e6a12b4..570e251e 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,18 @@ for (int i = 1; i <= n; i++) { } ``` +## Several variables + +Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): + +```cpp +for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + // code + } +} +``` + # Data structures A data structure is a way to store data in the memory of a computer. It is From bd59731be77e3c277e2fde24729c82c6a1a5c3f6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:37:46 +0530 Subject: [PATCH 0558/1894] add recursion --- README.md | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 570e251e..d2ed660b 100644 --- a/README.md +++ b/README.md @@ -20,27 +20,21 @@ An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. # Time complexity - The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. ## Calculation rules - -The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. +The time complexity of an algorithm is denoted ```O(...)``` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. ## Loops - A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). -For example, the time complexity of the following code is O(n): - +For example, the time complexity of the following code is O(n): ```cpp for (int i = 1; i <= n; i++) { // code } ``` - -And the time complexity of the following code is O(n^2): - +And the time complexity of the following code is O(n^2): ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { @@ -48,31 +42,24 @@ for (int i = 1; i <= n; i++) { } } ``` - ## Order of magnitude - -A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). - +A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). ```cpp for (int i = 1; i <= 3*n; i++) { // code } ``` - ```cpp for (int i = 1; i <= n+5; i++) { // code } ``` - ```cpp for (int i = 1; i <= n; i += 2) { // code } ``` - -As another example, the time complexity of the following code is O(n^2): - +As another example, the time complexity of the following code is O(n^2): ```cpp for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { @@ -82,9 +69,7 @@ for (int i = 1; i <= n; i++) { ``` ## Phases - -If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). - +If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). ```cpp for (int i = 1; i <= n; i++) { // code @@ -100,9 +85,7 @@ for (int i = 1; i <= n; i++) { ``` ## Several variables - -Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): - +Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { @@ -110,7 +93,17 @@ for (int i = 1; i <= n; i++) { } } ``` - +## Recursion +The time complexity of a recursive function depends on the number of times the function is called and the time complexity of a single call. The total time complexity is the product of these values. +For example, consider the following function: +```cpp +void f(int n) { + if (n == 1) return; + f(n-1); +} +``` +The call f(n) causes n function calls, and the time complexity of each call is O(1). +Thus, the total time complexity is O(n). # Data structures A data structure is a way to store data in the memory of a computer. It is From 4d55a246dd238621c0c27daf38cf27161a752971 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:37:52 +0530 Subject: [PATCH 0559/1894] add recursion --- README.md | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d2ed660b..40bf15aa 100644 --- a/README.md +++ b/README.md @@ -20,21 +20,27 @@ An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. # Time complexity + The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. ## Calculation rules -The time complexity of an algorithm is denoted ```O(...)``` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. + +The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. ## Loops + A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). -For example, the time complexity of the following code is O(n): +For example, the time complexity of the following code is O(n): + ```cpp for (int i = 1; i <= n; i++) { // code } ``` -And the time complexity of the following code is O(n^2): + +And the time complexity of the following code is O(n^2): + ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { @@ -42,24 +48,31 @@ for (int i = 1; i <= n; i++) { } } ``` + ## Order of magnitude -A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). + +A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). + ```cpp for (int i = 1; i <= 3*n; i++) { // code } ``` + ```cpp for (int i = 1; i <= n+5; i++) { // code } ``` + ```cpp for (int i = 1; i <= n; i += 2) { // code } ``` -As another example, the time complexity of the following code is O(n^2): + +As another example, the time complexity of the following code is O(n^2): + ```cpp for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { @@ -69,7 +82,9 @@ for (int i = 1; i <= n; i++) { ``` ## Phases -If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). + +If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). + ```cpp for (int i = 1; i <= n; i++) { // code @@ -85,7 +100,9 @@ for (int i = 1; i <= n; i++) { ``` ## Several variables -Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): + +Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): + ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { @@ -93,17 +110,22 @@ for (int i = 1; i <= n; i++) { } } ``` + ## Recursion + The time complexity of a recursive function depends on the number of times the function is called and the time complexity of a single call. The total time complexity is the product of these values. -For example, consider the following function: +For example, consider the following function: + ```cpp void f(int n) { if (n == 1) return; f(n-1); } ``` + The call f(n) causes n function calls, and the time complexity of each call is O(1). Thus, the total time complexity is O(n). + # Data structures A data structure is a way to store data in the memory of a computer. It is From 120ccc1282312febe0a32609b547a8b1bb6e4687 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:43:30 +0530 Subject: [PATCH 0560/1894] add another example --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 40bf15aa..236bfdd6 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,25 @@ void f(int n) { The call f(n) causes n function calls, and the time complexity of each call is O(1). Thus, the total time complexity is O(n). +As another example, consider the following function: + +```cpp +void g(int n) { + if (n == 1) return; + g(n-1); + g(n-1); +} +``` + +In this case each function call generates two other calls, except for n = 1. Let us see what happens when g is called with parameter n. The following table shows the function calls produced by this single call: + +function call number of calls +g(n)        1 +g(n - 1)        2 +g(n - 2)        4 +....        +g(1)        2^(n - 1) + # Data structures A data structure is a way to store data in the memory of a computer. It is From 5df4936e5fede86fe6bbf20468084a659a7e84ee Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:45:57 +0530 Subject: [PATCH 0561/1894] add time complexity for recursion --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 236bfdd6..c8ddbe2e 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,9 @@ g(n - 2)        4 ....        g(1)        2^(n - 1) +Based on this, the time complexity is +1 + 2 + 4 + ... + 2^(n - 1) = 2^(n - 1) = O(2^n). + # Data structures A data structure is a way to store data in the memory of a computer. It is From f6a03ca7bb7d823d9c7bb4ffaee484f081346722 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:53:30 +0530 Subject: [PATCH 0562/1894] add complexity classes --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index c8ddbe2e..8d19f486 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,28 @@ g(1)        2^(n - 1) Based on this, the time complexity is 1 + 2 + 4 + ... + 2^(n - 1) = 2^(n - 1) = O(2^n). +# Complexity classes + +The following list contains common time complexities of algorithms: + +O(1) : The running time of a constant-time algorithm does not depend on the input size. A typical constant-time algorithm is a direct formula that calculates the answer. + +O(logn) : A logarithmic algorithm often halves the input size at each step. The running time of such an algorithm is logarithmic, because log base 2 n equals the number of times n must be divided by 2 to get 1. + +O(√n) : A square root algorithm is slower than O(logn) but faster than O(n). A special property of square roots is that √n = n / √n , so the square root √n lies, in some sense, in the middle of the input. + +O(n) : A linear algorithm goes through the input a constant number of times. This is often the best possible time complexity, because it is usually necessary to access each input element at least once before reporting the answer. + +O(nlogn) : This time complexity often indicates that the algorithm sorts the input, because the time complexity of efficient sorting algorithms is O(nlogn). Another possibility is that the algorithm uses a data structure where each operation takes O(logn) time. + +O(n^2) : A quadratic algorithm often contains two nested loops. It is possible to go through all pairs of the input elements in O(n^2) time. + +O(n^3) : A cubic algorithm often contains three nested loops. It is possible to go through all triplets of the input elements in O(n^3) time. + +O(2^n) : This time complexity often indicates that the algorithm iterates through all subsets of the input elements. For example, the subsets of {1,2,3} are Φ, {1}, {2}, {3}, {1,2}, {1,3}, {2,3} and {1,2,3}. + +O(n!) : This time complexity often indicates that the algorithm iterates through all permutations of the input elements. For example, the permutations of {1,2,3} are (1,2,3), (1,3,2), (2,1,3 , (2,3,1), (3,1,2) and (3,2,1). + # Data structures A data structure is a way to store data in the memory of a computer. It is From 2d3879a90662e8b2cc228addc2e3e57141e6d517 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 15:56:37 +0530 Subject: [PATCH 0563/1894] add description on polynomial time algorithm --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 8d19f486..cc4ab8de 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,9 @@ O(2^n) : This time complexity often indicates that the algorithm iterates throug O(n!) : This time complexity often indicates that the algorithm iterates through all permutations of the input elements. For example, the permutations of {1,2,3} are (1,2,3), (1,3,2), (2,1,3 , (2,3,1), (3,1,2) and (3,2,1). +An algorithm is polynomial if its time complexity is at most O(n^k) where k is a constant. All the above time complexities except O(2^n) and O(n!) are polynomial. +In practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. + # Data structures A data structure is a way to store data in the memory of a computer. It is From deba71e54b14aebee0e275ee59c54ff8e94a1e8e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 30 Mar 2023 16:01:20 +0530 Subject: [PATCH 0564/1894] add estimating efficiency --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index cc4ab8de..c7386ff7 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,10 @@ O(n!) : This time complexity often indicates that the algorithm iterates through An algorithm is polynomial if its time complexity is at most O(n^k) where k is a constant. All the above time complexities except O(2^n) and O(n!) are polynomial. In practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. +# Estimating efficiency + +By calculating the time complexity of an algorithm, it is possible to check, before implementing the algorithm, that it is efficient enough for the problem. The starting point for estimations is the fact that a modern computer can perform some hundreds of millions of operations in a second. For example, assume that the time limit for a problem is one second and the input size is n = 10 ^ 5. If the time complexity is O(n^2), the algorithm will perform about (10 ^ 5) ^ 2 = 10 ^ 10 operations. This should take at least some tens of seconds, so the algorithm seems to be too slow for solving the problem. + # Data structures A data structure is a way to store data in the memory of a computer. It is From 88263294dcc2654f34e2999d1ec330b32c45f990 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 31 Mar 2023 13:43:22 +0530 Subject: [PATCH 0565/1894] add guessing time complexity --- README.md | 78 ++++++++++++++++++++++--------------------------------- 1 file changed, 31 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index c7386ff7..ee95c71f 100644 --- a/README.md +++ b/README.md @@ -20,27 +20,21 @@ An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. # Time complexity - The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. ## Calculation rules - -The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. +The time complexity of an algorithm is denoted ```O(...)``` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. ## Loops - A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). -For example, the time complexity of the following code is O(n): - +For example, the time complexity of the following code is O(n): ```cpp for (int i = 1; i <= n; i++) { // code } ``` - -And the time complexity of the following code is O(n^2): - +And the time complexity of the following code is O(n^2): ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { @@ -48,31 +42,24 @@ for (int i = 1; i <= n; i++) { } } ``` - ## Order of magnitude - -A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). - +A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). ```cpp for (int i = 1; i <= 3*n; i++) { // code } ``` - ```cpp for (int i = 1; i <= n+5; i++) { // code } ``` - ```cpp for (int i = 1; i <= n; i += 2) { // code } ``` - -As another example, the time complexity of the following code is O(n^2): - +As another example, the time complexity of the following code is O(n^2): ```cpp for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { @@ -82,9 +69,7 @@ for (int i = 1; i <= n; i++) { ``` ## Phases - -If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). - +If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). ```cpp for (int i = 1; i <= n; i++) { // code @@ -100,9 +85,7 @@ for (int i = 1; i <= n; i++) { ``` ## Several variables - -Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): - +Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { @@ -110,24 +93,19 @@ for (int i = 1; i <= n; i++) { } } ``` - ## Recursion - The time complexity of a recursive function depends on the number of times the function is called and the time complexity of a single call. The total time complexity is the product of these values. -For example, consider the following function: - +For example, consider the following function: ```cpp void f(int n) { if (n == 1) return; f(n-1); } ``` - The call f(n) causes n function calls, and the time complexity of each call is O(1). Thus, the total time complexity is O(n). As another example, consider the following function: - ```cpp void g(int n) { if (n == 1) return; @@ -135,38 +113,36 @@ void g(int n) { g(n-1); } ``` - -In this case each function call generates two other calls, except for n = 1. Let us see what happens when g is called with parameter n. The following table shows the function calls produced by this single call: +In this case each function call generates two other calls, except for n = 1. Let us see what happens when g is called with parameter n. The following table shows the function calls produced by this single call: function call number of calls -g(n)        1 -g(n - 1)        2 -g(n - 2)        4 -....        -g(1)        2^(n - 1) +g(n)        1 +g(n - 1)        2 +g(n - 2)        4 +....        +g(1)        2^(n - 1) Based on this, the time complexity is 1 + 2 + 4 + ... + 2^(n - 1) = 2^(n - 1) = O(2^n). # Complexity classes +The following list contains common time complexities of algorithms: -The following list contains common time complexities of algorithms: +O(1) : The running time of a constant-time algorithm does not depend on the input size. A typical constant-time algorithm is a direct formula that calculates the answer. -O(1) : The running time of a constant-time algorithm does not depend on the input size. A typical constant-time algorithm is a direct formula that calculates the answer. +O(logn) : A logarithmic algorithm often halves the input size at each step. The running time of such an algorithm is logarithmic, because log base 2 n equals the number of times n must be divided by 2 to get 1. -O(logn) : A logarithmic algorithm often halves the input size at each step. The running time of such an algorithm is logarithmic, because log base 2 n equals the number of times n must be divided by 2 to get 1. - -O(√n) : A square root algorithm is slower than O(logn) but faster than O(n). A special property of square roots is that √n = n / √n , so the square root √n lies, in some sense, in the middle of the input. +O(√n) : A square root algorithm is slower than O(logn) but faster than O(n). A special property of square roots is that √n = n / √n , so the square root √n lies, in some sense, in the middle of the input. O(n) : A linear algorithm goes through the input a constant number of times. This is often the best possible time complexity, because it is usually necessary to access each input element at least once before reporting the answer. -O(nlogn) : This time complexity often indicates that the algorithm sorts the input, because the time complexity of efficient sorting algorithms is O(nlogn). Another possibility is that the algorithm uses a data structure where each operation takes O(logn) time. +O(nlogn) : This time complexity often indicates that the algorithm sorts the input, because the time complexity of efficient sorting algorithms is O(nlogn). Another possibility is that the algorithm uses a data structure where each operation takes O(logn) time. -O(n^2) : A quadratic algorithm often contains two nested loops. It is possible to go through all pairs of the input elements in O(n^2) time. +O(n^2) : A quadratic algorithm often contains two nested loops. It is possible to go through all pairs of the input elements in O(n^2) time. -O(n^3) : A cubic algorithm often contains three nested loops. It is possible to go through all triplets of the input elements in O(n^3) time. +O(n^3) : A cubic algorithm often contains three nested loops. It is possible to go through all triplets of the input elements in O(n^3) time. -O(2^n) : This time complexity often indicates that the algorithm iterates through all subsets of the input elements. For example, the subsets of {1,2,3} are Φ, {1}, {2}, {3}, {1,2}, {1,3}, {2,3} and {1,2,3}. +O(2^n) : This time complexity often indicates that the algorithm iterates through all subsets of the input elements. For example, the subsets of {1,2,3} are Φ, {1}, {2}, {3}, {1,2}, {1,3}, {2,3} and {1,2,3}. O(n!) : This time complexity often indicates that the algorithm iterates through all permutations of the input elements. For example, the permutations of {1,2,3} are (1,2,3), (1,3,2), (2,1,3 , (2,3,1), (3,1,2) and (3,2,1). @@ -174,9 +150,17 @@ An algorithm is polynomial if its time complexity is at most O(n^k) where k is a In practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. # Estimating efficiency - By calculating the time complexity of an algorithm, it is possible to check, before implementing the algorithm, that it is efficient enough for the problem. The starting point for estimations is the fact that a modern computer can perform some hundreds of millions of operations in a second. For example, assume that the time limit for a problem is one second and the input size is n = 10 ^ 5. If the time complexity is O(n^2), the algorithm will perform about (10 ^ 5) ^ 2 = 10 ^ 10 operations. This should take at least some tens of seconds, so the algorithm seems to be too slow for solving the problem. +On the other hand, given the input size, we can try to guess the required time complexity of the algorithm that solves the problem. The following table contains some useful estimates assuming a time limit of one second. +input size required time complexity +n <= 10        O(n!) +n <= 20        O(2 ^ n) +n <= 500         O(n ^ 3) +n <= 5000       O(n ^ 2) +n <= 106      O(nlogn) or O(n) +n is large      O(1) or O(logn) + # Data structures A data structure is a way to store data in the memory of a computer. It is From 638db04748b25ac24f1651cfebd6f74498386fba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 31 Mar 2023 13:46:34 +0530 Subject: [PATCH 0566/1894] add example --- README.md | 77 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 52 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index ee95c71f..226c925c 100644 --- a/README.md +++ b/README.md @@ -20,21 +20,27 @@ An algorithm for solving a problem has to be both correct and efficient, and the core of the problem is often about inventing an efficient algorithm. # Time complexity + The efficiency of algorithms is important. Usually, it is easy to design an algorithm that solves the problem slowly, but the real challenge is to invent a fast algorithm. The time complexity of an algorithm estimates how much time the algorithm will use for some input. The idea is to represent the efficiency as a function whose parameter is the size of the input. By calculating the time complexity, we can find out whether the algorithm is fast enough without implementing it. ## Calculation rules -The time complexity of an algorithm is denoted ```O(...)``` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. + +The time complexity of an algorithm is denoted `O(...)` where the three dots represent some function. Usually, the variable n denotes the input size. For example, if the input is an array of numbers, n will be the size of the array, and if the input is a string, n will be the length of the string. ## Loops + A common reason why an algorithm is slow is that it contains many loops that go through the input. The more nested loops the algorithm contains, the slower it is. If there are k nested loops, the time complexity is O(n^k). -For example, the time complexity of the following code is O(n): +For example, the time complexity of the following code is O(n): + ```cpp for (int i = 1; i <= n; i++) { // code } ``` -And the time complexity of the following code is O(n^2): + +And the time complexity of the following code is O(n^2): + ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { @@ -42,24 +48,31 @@ for (int i = 1; i <= n; i++) { } } ``` + ## Order of magnitude -A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). + +A time complexity does not tell us the exact number of times the code inside a loop is executed, but it only shows the order of magnitude. In the following examples, the code inside the loop is executed 3n, n + 5 and [n / 2] times, but the time complexity of each code is O(n). + ```cpp for (int i = 1; i <= 3*n; i++) { // code } ``` + ```cpp for (int i = 1; i <= n+5; i++) { // code } ``` + ```cpp for (int i = 1; i <= n; i += 2) { // code } ``` -As another example, the time complexity of the following code is O(n^2): + +As another example, the time complexity of the following code is O(n^2): + ```cpp for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { @@ -69,7 +82,9 @@ for (int i = 1; i <= n; i++) { ``` ## Phases -If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). + +If the algorithm consists of consecutive phases, the total time complexity is the largest time complexity of a single phase. The reason for this is that the slowest phase is usually the bottleneck of the code. For example, the following code consists of three phases with time complexities O(n), O(n^2) and O(n). Thus, the total time complexity is O(n^2). + ```cpp for (int i = 1; i <= n; i++) { // code @@ -85,7 +100,9 @@ for (int i = 1; i <= n; i++) { ``` ## Several variables -Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): + +Sometimes the time complexity depends on several factors. In this case, the time complexity formula contains several variables. For example, the time complexity of the following code is O(nm): + ```cpp for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { @@ -93,19 +110,24 @@ for (int i = 1; i <= n; i++) { } } ``` + ## Recursion + The time complexity of a recursive function depends on the number of times the function is called and the time complexity of a single call. The total time complexity is the product of these values. -For example, consider the following function: +For example, consider the following function: + ```cpp void f(int n) { if (n == 1) return; f(n-1); } ``` + The call f(n) causes n function calls, and the time complexity of each call is O(1). Thus, the total time complexity is O(n). As another example, consider the following function: + ```cpp void g(int n) { if (n == 1) return; @@ -113,36 +135,38 @@ void g(int n) { g(n-1); } ``` -In this case each function call generates two other calls, except for n = 1. Let us see what happens when g is called with parameter n. The following table shows the function calls produced by this single call: + +In this case each function call generates two other calls, except for n = 1. Let us see what happens when g is called with parameter n. The following table shows the function calls produced by this single call: function call number of calls -g(n)        1 -g(n - 1)        2 -g(n - 2)        4 -....        -g(1)        2^(n - 1) +g(n)        1 +g(n - 1)        2 +g(n - 2)        4 +....        +g(1)        2^(n - 1) Based on this, the time complexity is 1 + 2 + 4 + ... + 2^(n - 1) = 2^(n - 1) = O(2^n). # Complexity classes -The following list contains common time complexities of algorithms: -O(1) : The running time of a constant-time algorithm does not depend on the input size. A typical constant-time algorithm is a direct formula that calculates the answer. +The following list contains common time complexities of algorithms: -O(logn) : A logarithmic algorithm often halves the input size at each step. The running time of such an algorithm is logarithmic, because log base 2 n equals the number of times n must be divided by 2 to get 1. +O(1) : The running time of a constant-time algorithm does not depend on the input size. A typical constant-time algorithm is a direct formula that calculates the answer. -O(√n) : A square root algorithm is slower than O(logn) but faster than O(n). A special property of square roots is that √n = n / √n , so the square root √n lies, in some sense, in the middle of the input. +O(logn) : A logarithmic algorithm often halves the input size at each step. The running time of such an algorithm is logarithmic, because log base 2 n equals the number of times n must be divided by 2 to get 1. + +O(√n) : A square root algorithm is slower than O(logn) but faster than O(n). A special property of square roots is that √n = n / √n , so the square root √n lies, in some sense, in the middle of the input. O(n) : A linear algorithm goes through the input a constant number of times. This is often the best possible time complexity, because it is usually necessary to access each input element at least once before reporting the answer. -O(nlogn) : This time complexity often indicates that the algorithm sorts the input, because the time complexity of efficient sorting algorithms is O(nlogn). Another possibility is that the algorithm uses a data structure where each operation takes O(logn) time. +O(nlogn) : This time complexity often indicates that the algorithm sorts the input, because the time complexity of efficient sorting algorithms is O(nlogn). Another possibility is that the algorithm uses a data structure where each operation takes O(logn) time. -O(n^2) : A quadratic algorithm often contains two nested loops. It is possible to go through all pairs of the input elements in O(n^2) time. +O(n^2) : A quadratic algorithm often contains two nested loops. It is possible to go through all pairs of the input elements in O(n^2) time. -O(n^3) : A cubic algorithm often contains three nested loops. It is possible to go through all triplets of the input elements in O(n^3) time. +O(n^3) : A cubic algorithm often contains three nested loops. It is possible to go through all triplets of the input elements in O(n^3) time. -O(2^n) : This time complexity often indicates that the algorithm iterates through all subsets of the input elements. For example, the subsets of {1,2,3} are Φ, {1}, {2}, {3}, {1,2}, {1,3}, {2,3} and {1,2,3}. +O(2^n) : This time complexity often indicates that the algorithm iterates through all subsets of the input elements. For example, the subsets of {1,2,3} are Φ, {1}, {2}, {3}, {1,2}, {1,3}, {2,3} and {1,2,3}. O(n!) : This time complexity often indicates that the algorithm iterates through all permutations of the input elements. For example, the permutations of {1,2,3} are (1,2,3), (1,3,2), (2,1,3 , (2,3,1), (3,1,2) and (3,2,1). @@ -150,16 +174,19 @@ An algorithm is polynomial if its time complexity is at most O(n^k) where k is a In practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. # Estimating efficiency + By calculating the time complexity of an algorithm, it is possible to check, before implementing the algorithm, that it is efficient enough for the problem. The starting point for estimations is the fact that a modern computer can perform some hundreds of millions of operations in a second. For example, assume that the time limit for a problem is one second and the input size is n = 10 ^ 5. If the time complexity is O(n^2), the algorithm will perform about (10 ^ 5) ^ 2 = 10 ^ 10 operations. This should take at least some tens of seconds, so the algorithm seems to be too slow for solving the problem. -On the other hand, given the input size, we can try to guess the required time complexity of the algorithm that solves the problem. The following table contains some useful estimates assuming a time limit of one second. +On the other hand, given the input size, we can try to guess the required time complexity of the algorithm that solves the problem. The following table contains some useful estimates assuming a time limit of one second. input size required time complexity -n <= 10        O(n!) +n <= 10        O(n!) n <= 20        O(2 ^ n) n <= 500         O(n ^ 3) n <= 5000       O(n ^ 2) n <= 106      O(nlogn) or O(n) -n is large      O(1) or O(logn) +n is large      O(1) or O(logn) + +For example, if the input size is n = 10 ^ 5, it is probably expected that the time complexity of the algorithm is O(n) or O(nlogn). This information makes it easier to design the algorithm, because it rules out approaches that would yield an algorithm with a worse time complexity. Still, it is important to remember that a time complexity is only an estimate of efficiency, because it hides the constant factors. For example, an algorithm that runs in O(n) time may perform n/2 or 5n operations. This has an important effect on the actual running time of the algorithm. # Data structures From bec5e825e81256bff8f2b93fd7e921d0df4c8595 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 31 Mar 2023 14:18:08 +0530 Subject: [PATCH 0567/1894] add table of content --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 226c925c..f06ae92c 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,28 @@ Contributions are welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). +- [Intro]() + - [Time complexity]() + - [Loops]() + - [Phases]() + - [Recursion]() + - [Complexity classes]() + - [Estimating efficiency]() + - [Estimating efficiency]() +- [Data structures]() +- [Sorting]() +- [Binary Search]() + - [Method 1]() + - [Example]() + - [Method 2]() +- [Greedy algorithms]() + - [Coin problem]() + - [General case]() +- [Dynamic programming]() + - [Coin problem]() + - [Using memoization]() +- [Amortized analysis]() + # Intro The design of algorithms consists of problem solving and mathematical From 2b881617597dc5b2f53afa8be491a86fb02cda02 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 31 Mar 2023 14:22:49 +0530 Subject: [PATCH 0568/1894] update links --- README.md | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index f06ae92c..d1969a59 100644 --- a/README.md +++ b/README.md @@ -12,27 +12,30 @@ Contributions are welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). -- [Intro]() - - [Time complexity]() - - [Loops]() - - [Phases]() - - [Recursion]() - - [Complexity classes]() - - [Estimating efficiency]() - - [Estimating efficiency]() -- [Data structures]() -- [Sorting]() -- [Binary Search]() - - [Method 1]() - - [Example]() - - [Method 2]() -- [Greedy algorithms]() - - [Coin problem]() - - [General case]() -- [Dynamic programming]() - - [Coin problem]() - - [Using memoization]() -- [Amortized analysis]() +- [Intro](https://github.com/akgmage/data-structures-and-algorithms#intro) + - [Time complexity](https://github.com/akgmage/data-structures-and-algorithms#time-complexity) + - [Calculation Rules](https://github.com/akgmage/data-structures-and-algorithms#calculation-rules) + - [Loops](https://github.com/akgmage/data-structures-and-algorithms#loops) + - [Order of Magnitude](https://github.com/akgmage/data-structures-and-algorithms#order-of-magnitude) + - [Phases](https://github.com/akgmage/data-structures-and-algorithms#phases) + - [Several Variables](https://github.com/akgmage/data-structures-and-algorithms#several-variables) + - [Recursion](https://github.com/akgmage/data-structures-and-algorithms#recursion) + - [Complexity classes](https://github.com/akgmage/data-structures-and-algorithms#complexity-classes) + - [Estimating efficiency](https://github.com/akgmage/data-structures-and-algorithms#estimating-efficiency) +- [Data structures](https://github.com/akgmage/data-structures-and-algorithms#data-structures) +- [Sorting](https://github.com/akgmage/data-structures-and-algorithms#sorting) + \*[Well Known Sorting Algorithms](https://github.com/akgmage/data-structures-and-algorithms#well-known-sorting-algorithms) +- [Binary Search](https://github.com/akgmage/data-structures-and-algorithms#binary-search) + - [Method 1](https://github.com/akgmage/data-structures-and-algorithms#method-1) + - [Example](https://github.com/akgmage/data-structures-and-algorithms#example) + - [Method 2](https://github.com/akgmage/data-structures-and-algorithms#method-2) +- [Greedy algorithms](https://github.com/akgmage/data-structures-and-algorithms#greedy-algorithms) + - [Coin problem](https://github.com/akgmage/data-structures-and-algorithms#coin-problem) + - [General case](https://github.com/akgmage/data-structures-and-algorithms#general-case) +- [Dynamic programming](https://github.com/akgmage/data-structures-and-algorithms#dynamic-programming) + - [Coin problem](https://github.com/akgmage/data-structures-and-algorithms#coin-problem-1) + - [Using memoization](https://github.com/akgmage/data-structures-and-algorithms#using-memoization) +- [Amortized analysis](https://github.com/akgmage/data-structures-and-algorithms#amortized-analysis) # Intro From 9899eef0847e1e768fbfbe4934057fcdbf2eb71b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 31 Mar 2023 14:24:38 +0530 Subject: [PATCH 0569/1894] fix bullet --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d1969a59..490c7923 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,8 @@ You can join the fun by following our [contributing guide](https://github.com/ak - [Complexity classes](https://github.com/akgmage/data-structures-and-algorithms#complexity-classes) - [Estimating efficiency](https://github.com/akgmage/data-structures-and-algorithms#estimating-efficiency) - [Data structures](https://github.com/akgmage/data-structures-and-algorithms#data-structures) -- [Sorting](https://github.com/akgmage/data-structures-and-algorithms#sorting) - \*[Well Known Sorting Algorithms](https://github.com/akgmage/data-structures-and-algorithms#well-known-sorting-algorithms) +- [Sorting](https://github.com/akgmage/data-structures-and-algorithms#sorting) + - [Well Known Sorting Algorithms](https://github.com/akgmage/data-structures-and-algorithms#well-known-sorting-algorithms) - [Binary Search](https://github.com/akgmage/data-structures-and-algorithms#binary-search) - [Method 1](https://github.com/akgmage/data-structures-and-algorithms#method-1) - [Example](https://github.com/akgmage/data-structures-and-algorithms#example) From 545fc8df4fde040eb47c5f1be5d04a08cc15eac4 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Fri, 31 Mar 2023 17:11:36 +0530 Subject: [PATCH 0570/1894] feat: Implemented Queue data-structure in java --- Queue/Implement Queue data structure in Java | 124 +++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 Queue/Implement Queue data structure in Java diff --git a/Queue/Implement Queue data structure in Java b/Queue/Implement Queue data structure in Java new file mode 100644 index 00000000..4c274745 --- /dev/null +++ b/Queue/Implement Queue data structure in Java @@ -0,0 +1,124 @@ +1. Here's an implementation of a Queue data structure in Java using an array: + + public class Queue { + private int maxSize; + private int[] queueArray; + private int front; + private int rear; + private int currentSize; + + public Queue(int size) { + this.maxSize = size; + this.queueArray = new int[size]; + this.front = 0; + this.rear = -1; + this.currentSize = 0; + } + + public void enqueue(int item) { + if (isFull()) { + System.out.println("Queue is full"); + return; + } + rear++; + if (rear == maxSize) { + rear = 0; + } + queueArray[rear] = item; + currentSize++; + } + + public int dequeue() { + if (isEmpty()) { + System.out.println("Queue is empty"); + return -1; + } + int temp = queueArray[front]; + front++; + if (front == maxSize) { + front = 0; + } + currentSize--; + return temp; + } + + public boolean isEmpty() { + return currentSize == 0; + } + + public boolean isFull() { + return currentSize == maxSize; + } + + public int size() { + return currentSize; + } + } + + + In this implementation, we use an array to store the elements of the queue, and we keep track of the front and rear indices, as well as the current size of the queue. + The enqueue operation adds an item to the rear of the queue, while the dequeue operation removes an item from the front of the queue. + The isEmpty and isFull methods check whether the queue is empty or full, respectively, while the size method returns the current size of the queue. + + +2. Here's an example implementation of a Queue data structure in Java using a linked list + + public class Queue { + private Node front; + private Node rear; + private int size; + + public Queue() { + front = null; + rear = null; + size = 0; + } + + private static class Node { + T data; + Node next; + + public Node(T data) { + this.data = data; + this.next = null; + } + } + + public void enqueue(T item) { + Node newNode = new Node<>(item); + if (isEmpty()) { + front = newNode; + } else { + rear.next = newNode; + } + rear = newNode; + size++; + } + + public T dequeue() { + if (isEmpty()) { + System.out.println("Queue is empty"); + return null; + } + T item = front.data; + front = front.next; + if (front == null) { + rear = null; + } + size--; + return item; + } + + public boolean isEmpty() { + return size == 0; + } + + public int size() { + return size; + } + } + + In this implementation, we use a linked list to store the elements of the queue, and we keep track of the front and rear nodes, as well as the current size of the queue. + The enqueue operation adds a new node to the rear of the linked list, while the dequeue operation removes the head node from the linked list. + The isEmpty method checks whether the queue is empty, while the size method returns the current size of the queue. + Note that this implementation uses generics to allow the queue to store elements of any type. \ No newline at end of file From a46355855987cce489f9127260e2b005063bb1a0 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Sat, 1 Apr 2023 14:32:35 +0530 Subject: [PATCH 0571/1894] Implement Queue data structure in Javascript --- ...plement Queue data structure in Javascript | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Queue/Implement Queue data structure in Javascript diff --git a/Queue/Implement Queue data structure in Javascript b/Queue/Implement Queue data structure in Javascript new file mode 100644 index 00000000..3948ac85 --- /dev/null +++ b/Queue/Implement Queue data structure in Javascript @@ -0,0 +1,108 @@ +1. Here's an implementation of a Queue data structure in JavaScript using an array: + + class Queue { + constructor() { + this.items = []; + } + + enqueue(element) { + this.items.push(element); + } + + dequeue() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + front() { + if (this.isEmpty()) { + return "No elements in Queue"; + } + return this.items[0]; + } + + isEmpty() { + return this.items.length === 0; + } + + printQueue() { + let str = ""; + for (let i = 0; i < this.items.length; i++) { + str += this.items[i] + " "; + } + return str; + } + } + +The enqueue method adds an element to the end of the queue, while dequeue removes and returns the element at the front of the queue. +The front method returns the element at the front of the queue without removing it, while the isEmpty method returns true if the queue is empty and false otherwise. +The printQueue method returns a string representation of the elements in the queue. + + +2. Here's an implementation of a Queue data structure in JavaScript using a linked list: + + class Node { + constructor(data) { + this.data = data; + this.next = null; + } + } + + class Queue { + constructor() { + this.front = null; + this.rear = null; + this.size = 0; + } + + enqueue(data) { + let newNode = new Node(data); + if (this.rear === null) { + this.front = newNode; + this.rear = newNode; + } else { + this.rear.next = newNode; + this.rear = newNode; + } + this.size++; + } + + dequeue() { + if (this.front === null) { + return "Underflow"; + } + let removedNode = this.front; + this.front = this.front.next; + if (this.front === null) { + this.rear = null; + } + this.size--; + return removedNode.data; + } + + isEmpty() { + return this.size === 0; + } + + getFront() { + return this.front ? this.front.data : "No elements in Queue"; + } + + printQueue() { + let str = ""; + let temp = this.front; + while (temp) { + str += temp.data + " "; + temp = temp.next; + } + return str; + } + } + + +In this implementation, we define a Node class to represent each element in the queue, and a Queue class that maintains a front and rear pointer to the first and last nodes in the linked list. +The enqueue method adds a new node to the end of the linked list, while the dequeue method removes and returns the node at the front of the linked list. +The isEmpty method checks if the queue is empty, and the getFront method returns the data of the first node in the linked list without removing it. +The printQueue method returns a string representation of the elements in the queue. From f11349fd1abdde2e2466f23fd397a970c1a1ce9f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Apr 2023 14:58:49 +0530 Subject: [PATCH 0572/1894] modify comments --- ...ueue data structure in Java => queue.java} | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) rename Queue/{Implement Queue data structure in Java => queue.java} (92%) diff --git a/Queue/Implement Queue data structure in Java b/Queue/queue.java similarity index 92% rename from Queue/Implement Queue data structure in Java rename to Queue/queue.java index 4c274745..df09d22b 100644 --- a/Queue/Implement Queue data structure in Java +++ b/Queue/queue.java @@ -1,6 +1,13 @@ -1. Here's an implementation of a Queue data structure in Java using an array: +// 1. Queue Using Array: +// 2. Queue Using LinkedList: +/* + In this implementation, we use an array to store the elements of the queue, and we keep track of the front and rear indices, as well as the current size of the queue. + The enqueue operation adds an item to the rear of the queue, while the dequeue operation removes an item from the front of the queue. + The isEmpty and isFull methods check whether the queue is empty or full, respectively, while the size method returns the current size of the queue. - public class Queue { +*/ +// 1. Queue Using Array: +public class Queue { private int maxSize; private int[] queueArray; private int front; @@ -53,17 +60,20 @@ public boolean isFull() { public int size() { return currentSize; } - } - - - In this implementation, we use an array to store the elements of the queue, and we keep track of the front and rear indices, as well as the current size of the queue. - The enqueue operation adds an item to the rear of the queue, while the dequeue operation removes an item from the front of the queue. - The isEmpty and isFull methods check whether the queue is empty or full, respectively, while the size method returns the current size of the queue. + } -2. Here's an example implementation of a Queue data structure in Java using a linked list + - public class Queue { +// Here's an example implementation of a Queue data structure in Java using a linked list +/* + In this implementation, we use a linked list to store the elements of the queue, and we keep track of the front and rear nodes, as well as the current size of the queue. + The enqueue operation adds a new node to the rear of the linked list, while the dequeue operation removes the head node from the linked list. + The isEmpty method checks whether the queue is empty, while the size method returns the current size of the queue. + Note that this implementation uses generics to allow the queue to store elements of any type. +*/ +// 2. Queue Using LinkedList: +public class Queue { private Node front; private Node rear; private int size; @@ -116,9 +126,5 @@ public boolean isEmpty() { public int size() { return size; } - } + } - In this implementation, we use a linked list to store the elements of the queue, and we keep track of the front and rear nodes, as well as the current size of the queue. - The enqueue operation adds a new node to the rear of the linked list, while the dequeue operation removes the head node from the linked list. - The isEmpty method checks whether the queue is empty, while the size method returns the current size of the queue. - Note that this implementation uses generics to allow the queue to store elements of any type. \ No newline at end of file From b06d027b6469fe7b6b839fd3e2617caaf3cf5e60 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Apr 2023 15:05:28 +0530 Subject: [PATCH 0573/1894] update table of content --- README.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 490c7923..d73ce0cd 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,24 @@ You can join the fun by following our [contributing guide](https://github.com/ak - [Coin problem](https://github.com/akgmage/data-structures-and-algorithms#coin-problem-1) - [Using memoization](https://github.com/akgmage/data-structures-and-algorithms#using-memoization) - [Amortized analysis](https://github.com/akgmage/data-structures-and-algorithms#amortized-analysis) +- [Pattern 1: Two Pointers]() + - [Practice problems for two pointers]() +- [Pattern 2: Fast and Slow Pointers]() + - [Practice problems for fast and slow pointers]() +- [Pattern 3: Sliding Window]() + - [Practice problems for sliding window]() +- [Pattern 3: Sliding Window]() + - [Practice problems for sliding window]() +- [Pattern 4: Merge Interval]() + - [Practice problems for merge intervals]() +- [Pattern 5: In-place Reversal of a Linked List]() + - [Practice problems for in-place reversal of a linked list]() +- [Pattern 6: Two Heaps]() + - [Practice problems for two heaps]() +- [Pattern 7: K-way Merge]() + - [Practice problems for k-way Merge]() +- [Pattern 8: Top K Elements]() + - [Practice problems for Top K Elements]() # Intro @@ -696,7 +714,3 @@ Many problems in the real world use the top K elements pattern. Let’s look at - Top K frequent element - Kth largest element in an array - Kth smallest element in an BST - -``` - -``` From 047699cbf95be65d60c2d7ff8947eab877550650 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Apr 2023 15:06:11 +0530 Subject: [PATCH 0574/1894] add heading --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d73ce0cd..b9419511 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Contributions are welcome! You can join the fun by following our [contributing guide](https://github.com/akgmage/data-structures-and-algorithms/blob/main/CONTRIBUTING.md). +# Table of contents + - [Intro](https://github.com/akgmage/data-structures-and-algorithms#intro) - [Time complexity](https://github.com/akgmage/data-structures-and-algorithms#time-complexity) - [Calculation Rules](https://github.com/akgmage/data-structures-and-algorithms#calculation-rules) From ace70ac419bdb4882384a0e579b110706344b927 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Apr 2023 15:09:52 +0530 Subject: [PATCH 0575/1894] update links --- README.md | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index b9419511..d8c46e9e 100644 --- a/README.md +++ b/README.md @@ -38,24 +38,22 @@ You can join the fun by following our [contributing guide](https://github.com/ak - [Coin problem](https://github.com/akgmage/data-structures-and-algorithms#coin-problem-1) - [Using memoization](https://github.com/akgmage/data-structures-and-algorithms#using-memoization) - [Amortized analysis](https://github.com/akgmage/data-structures-and-algorithms#amortized-analysis) -- [Pattern 1: Two Pointers]() - - [Practice problems for two pointers]() -- [Pattern 2: Fast and Slow Pointers]() - - [Practice problems for fast and slow pointers]() -- [Pattern 3: Sliding Window]() - - [Practice problems for sliding window]() -- [Pattern 3: Sliding Window]() - - [Practice problems for sliding window]() -- [Pattern 4: Merge Interval]() - - [Practice problems for merge intervals]() -- [Pattern 5: In-place Reversal of a Linked List]() - - [Practice problems for in-place reversal of a linked list]() -- [Pattern 6: Two Heaps]() - - [Practice problems for two heaps]() -- [Pattern 7: K-way Merge]() - - [Practice problems for k-way Merge]() -- [Pattern 8: Top K Elements]() - - [Practice problems for Top K Elements]() +- [Pattern 1: Two Pointers](https://github.com/akgmage/data-structures-and-algorithms#pattern-1-two-pointers) + - [Practice problems for two pointers](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-two-pointers) +- [Pattern 2: Fast and Slow Pointers](https://github.com/akgmage/data-structures-and-algorithms#pattern-2-fast-and-slow-pointers) + - [Practice problems for fast and slow pointers](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-fast-and-slow-pointers) +- [Pattern 3: Sliding Window](https://github.com/akgmage/data-structures-and-algorithms#pattern-3-sliding-window) + - [Practice problems for sliding window](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-sliding-window) +- [Pattern 4: Merge Interval](https://github.com/akgmage/data-structures-and-algorithms#pattern-4-merge-interval) + - [Practice problems for merge intervals](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-merge-intervals) +- [Pattern 5: In-place Reversal of a Linked List](https://github.com/akgmage/data-structures-and-algorithms#pattern-5-in-place-reversal-of-a-linked-list) + - [Practice problems for in-place reversal of a linked list](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-in-place-reversal-of-a-linked-list) +- [Pattern 6: Two Heaps](https://github.com/akgmage/data-structures-and-algorithms#pattern-6-two-heaps) + - [Practice problems for two heaps](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-two-heaps) +- [Pattern 7: K-way Merge](https://github.com/akgmage/data-structures-and-algorithms#pattern-7-k-way-merge) + - [Practice problems for k-way Merge](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-k-way-merge) +- [Pattern 8: Top K Elements](https://github.com/akgmage/data-structures-and-algorithms#pattern-8-top-k-elements) + - [Practice problems for Top K Elements](https://github.com/akgmage/data-structures-and-algorithms#practice-problems-for-top-k-elements) # Intro From 6846d491207994e1915b15ba82179b7226909b95 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Apr 2023 15:15:14 +0530 Subject: [PATCH 0576/1894] modify comments and rename file --- ...plement Queue data structure in Javascript | 108 ----------------- Queue/queue.js | 110 ++++++++++++++++++ 2 files changed, 110 insertions(+), 108 deletions(-) delete mode 100644 Queue/Implement Queue data structure in Javascript create mode 100644 Queue/queue.js diff --git a/Queue/Implement Queue data structure in Javascript b/Queue/Implement Queue data structure in Javascript deleted file mode 100644 index 3948ac85..00000000 --- a/Queue/Implement Queue data structure in Javascript +++ /dev/null @@ -1,108 +0,0 @@ -1. Here's an implementation of a Queue data structure in JavaScript using an array: - - class Queue { - constructor() { - this.items = []; - } - - enqueue(element) { - this.items.push(element); - } - - dequeue() { - if (this.isEmpty()) { - return "Underflow"; - } - return this.items.shift(); - } - - front() { - if (this.isEmpty()) { - return "No elements in Queue"; - } - return this.items[0]; - } - - isEmpty() { - return this.items.length === 0; - } - - printQueue() { - let str = ""; - for (let i = 0; i < this.items.length; i++) { - str += this.items[i] + " "; - } - return str; - } - } - -The enqueue method adds an element to the end of the queue, while dequeue removes and returns the element at the front of the queue. -The front method returns the element at the front of the queue without removing it, while the isEmpty method returns true if the queue is empty and false otherwise. -The printQueue method returns a string representation of the elements in the queue. - - -2. Here's an implementation of a Queue data structure in JavaScript using a linked list: - - class Node { - constructor(data) { - this.data = data; - this.next = null; - } - } - - class Queue { - constructor() { - this.front = null; - this.rear = null; - this.size = 0; - } - - enqueue(data) { - let newNode = new Node(data); - if (this.rear === null) { - this.front = newNode; - this.rear = newNode; - } else { - this.rear.next = newNode; - this.rear = newNode; - } - this.size++; - } - - dequeue() { - if (this.front === null) { - return "Underflow"; - } - let removedNode = this.front; - this.front = this.front.next; - if (this.front === null) { - this.rear = null; - } - this.size--; - return removedNode.data; - } - - isEmpty() { - return this.size === 0; - } - - getFront() { - return this.front ? this.front.data : "No elements in Queue"; - } - - printQueue() { - let str = ""; - let temp = this.front; - while (temp) { - str += temp.data + " "; - temp = temp.next; - } - return str; - } - } - - -In this implementation, we define a Node class to represent each element in the queue, and a Queue class that maintains a front and rear pointer to the first and last nodes in the linked list. -The enqueue method adds a new node to the end of the linked list, while the dequeue method removes and returns the node at the front of the linked list. -The isEmpty method checks if the queue is empty, and the getFront method returns the data of the first node in the linked list without removing it. -The printQueue method returns a string representation of the elements in the queue. diff --git a/Queue/queue.js b/Queue/queue.js new file mode 100644 index 00000000..0df4b905 --- /dev/null +++ b/Queue/queue.js @@ -0,0 +1,110 @@ +// 1. Queue Using Array: +// 2. Queue Using LinkedList: +/* + In this implementation, we use an array to store the elements of the queue, and we keep track of the front and rear indices, as well as the current size of the queue. + The enqueue operation adds an item to the rear of the queue, while the dequeue operation removes an item from the front of the queue. + The isEmpty and isFull methods check whether the queue is empty or full, respectively, while the size method returns the current size of the queue. + +*/ +// 1. Queue Using Array: +class Queue { + constructor() { + this.items = []; + } + + enqueue(element) { + this.items.push(element); + } + + dequeue() { + if (this.isEmpty()) { + return "Underflow"; + } + return this.items.shift(); + } + + front() { + if (this.isEmpty()) { + return "No elements in Queue"; + } + return this.items[0]; + } + + isEmpty() { + return this.items.length === 0; + } + + printQueue() { + let str = ""; + for (let i = 0; i < this.items.length; i++) { + str += this.items[i] + " "; + } + return str; + } +} + +// Here's an example implementation of a Queue data structure in Java using a linked list +/* + In this implementation, we use a linked list to store the elements of the queue, and we keep track of the front and rear nodes, as well as the current size of the queue. + The enqueue operation adds a new node to the rear of the linked list, while the dequeue operation removes the head node from the linked list. + The isEmpty method checks whether the queue is empty, while the size method returns the current size of the queue. + Note that this implementation uses generics to allow the queue to store elements of any type. +*/ +// 2. Queue Using LinkedList: +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Queue { + constructor() { + this.front = null; + this.rear = null; + this.size = 0; + } + + enqueue(data) { + let newNode = new Node(data); + if (this.rear === null) { + this.front = newNode; + this.rear = newNode; + } else { + this.rear.next = newNode; + this.rear = newNode; + } + this.size++; + } + + dequeue() { + if (this.front === null) { + return "Underflow"; + } + let removedNode = this.front; + this.front = this.front.next; + if (this.front === null) { + this.rear = null; + } + this.size--; + return removedNode.data; + } + + isEmpty() { + return this.size === 0; + } + + getFront() { + return this.front ? this.front.data : "No elements in Queue"; + } + + printQueue() { + let str = ""; + let temp = this.front; + while (temp) { + str += temp.data + " "; + temp = temp.next; + } + return str; + } +} From 728470f3a569fa86bc2df51796a515fbf5da8c37 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Apr 2023 11:47:06 +0530 Subject: [PATCH 0577/1894] add zero sum subarray --- Hash Table/zero_sum_subarray.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hash Table/zero_sum_subarray.go diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go new file mode 100644 index 00000000..f4275daf --- /dev/null +++ b/Hash Table/zero_sum_subarray.go @@ -0,0 +1,24 @@ +/* + You're given a list of integers nums. Write a function that returns a boolean representing + whether there exists a zero-sum subarray of nums + + Sample Input : = [-5, -5, 2, 3, -2] + Output : True + The subarray [-5, 2, 3] has a sum of 0 +*/ + +package main + +func ZeroSumSubarray(nums []int) bool { + sums := map[int]bool{0: true} + currentSum := 0 + for _, num := range nums { + currentSum += num + if _, sumIsInSet := sums[currentSum]; sumIsInSet { + return true + } + sums[currentSum] = true + print(currentSum , " ") + } + return false +} From 167f0fdd20d0fcfd4ade25dd559b58685e383ad1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Apr 2023 11:48:43 +0530 Subject: [PATCH 0578/1894] add approach --- Hash Table/zero_sum_subarray.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go index f4275daf..4086f5f1 100644 --- a/Hash Table/zero_sum_subarray.go +++ b/Hash Table/zero_sum_subarray.go @@ -6,7 +6,16 @@ Output : True The subarray [-5, 2, 3] has a sum of 0 */ +/* +Approach: + A good way to approach this problem is to first think of a simpler version. + How would you check if the entire array sum is zero? + + If the entire array does not sum to zero, then you need to check if there are + any smaller subarrays that sum to zero. For this, it can be helpful to keep + track of all of the sums from [0, i], where i is every index in the array. +*/ package main func ZeroSumSubarray(nums []int) bool { From a808b45a2a343db6eff571e417a3b20f5d0ecdda Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Apr 2023 11:49:15 +0530 Subject: [PATCH 0579/1894] add time and space complexity --- Hash Table/zero_sum_subarray.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go index 4086f5f1..e8588b1e 100644 --- a/Hash Table/zero_sum_subarray.go +++ b/Hash Table/zero_sum_subarray.go @@ -15,6 +15,8 @@ Approach: If the entire array does not sum to zero, then you need to check if there are any smaller subarrays that sum to zero. For this, it can be helpful to keep track of all of the sums from [0, i], where i is every index in the array. + + After recording all sums from [0, i], what would it mean if a sum is repeated? */ package main From 0ea227e2aa157ec7ec07ede0f1f9d1eadd9f5d9d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Apr 2023 11:52:14 +0530 Subject: [PATCH 0580/1894] add main func with test cases --- Hash Table/zero_sum_subarray.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go index e8588b1e..5bd80d40 100644 --- a/Hash Table/zero_sum_subarray.go +++ b/Hash Table/zero_sum_subarray.go @@ -1,25 +1,28 @@ /* - You're given a list of integers nums. Write a function that returns a boolean representing + You're given a list of integers nums. Write a function that returns a boolean representing whether there exists a zero-sum subarray of nums Sample Input : = [-5, -5, 2, 3, -2] Output : True - The subarray [-5, 2, 3] has a sum of 0 + The subarray [-5, 2, 3] has a sum of 0 */ /* Approach: A good way to approach this problem is to first think of a simpler version. How would you check if the entire array sum is zero? - + If the entire array does not sum to zero, then you need to check if there are any smaller subarrays that sum to zero. For this, it can be helpful to keep track of all of the sums from [0, i], where i is every index in the array. - + After recording all sums from [0, i], what would it mean if a sum is repeated? */ +// Time and Space complexity : O(n) time | O(n) space - where n is the length of nums package main +import "fmt" + func ZeroSumSubarray(nums []int) bool { sums := map[int]bool{0: true} currentSum := 0 @@ -29,7 +32,13 @@ func ZeroSumSubarray(nums []int) bool { return true } sums[currentSum] = true - print(currentSum , " ") } return false } + +func main() { + nums := []int{-5, -5, 2, 3, -2} + fmt.Println(ZeroSumSubarray(nums)) + nums = []int{1, 2, 3, 4, 5} + fmt.Println(ZeroSumSubarray(nums)) +} \ No newline at end of file From 9d2ed9c13267b237a6126fba084694724315ce1c Mon Sep 17 00:00:00 2001 From: Sarvesh788 <101782944+Sarvesh788@users.noreply.github.com> Date: Sun, 2 Apr 2023 12:47:32 +0530 Subject: [PATCH 0581/1894] Added 2 pointer approach to find if given string is palindrome in c++ --- Strings/check_palindrome.cpp | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Strings/check_palindrome.cpp diff --git a/Strings/check_palindrome.cpp b/Strings/check_palindrome.cpp new file mode 100644 index 00000000..93f344c6 --- /dev/null +++ b/Strings/check_palindrome.cpp @@ -0,0 +1,39 @@ +#include +#include + +using namespace std; + +// 2 pointer approach to find if a number is palindrome or not +// Time complexity O(n), Space complexity O(1). + +int palindrome_checker(string str) // palindrome checker function +{ + int left = 0; + int right = str.length() - 1; // initializing left and right variables + while(left < right) + { + if(str[left] != str[right]) + { + return 0; + } + left = left + 1; // updating left and right variables + right = right - 1; + } + return 1; +} + +int main() +{ + string str; + cin>>str; + int isPal = palindrome_checker(str); // calling palindrome checker function + if(isPal == 1) + { + cout<<"String is palindrome"; + } + else + { + cout<<"String is not palindrome"; + } + return 0; +} \ No newline at end of file From 1fd90e4b7af772e3c3a6aba46e2d33b35cc07de9 Mon Sep 17 00:00:00 2001 From: Tyler Le Date: Sun, 2 Apr 2023 11:51:40 -0700 Subject: [PATCH 0582/1894] dijkstra python code --- Graphs/Graphs_Dijkstras.py | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Graphs/Graphs_Dijkstras.py diff --git a/Graphs/Graphs_Dijkstras.py b/Graphs/Graphs_Dijkstras.py new file mode 100644 index 00000000..46911f56 --- /dev/null +++ b/Graphs/Graphs_Dijkstras.py @@ -0,0 +1,44 @@ +def dijkstra(graph, start): + # Create a dictionary to store the shortest distances to each node + shortest_distances = {node: float('inf') for node in graph} + shortest_distances[start] = 0 + + # Create a set to store nodes that have been processed + processed_nodes = set() + + # Create a priority queue to store nodes and their distances + queue = [(start, 0)] + + while queue: + # Get the node with the smallest distance from the start node + current_node, current_distance = min(queue, key=lambda x: x[1]) + queue.remove((current_node, current_distance)) + + # If we've already processed this node, skip it + if current_node in processed_nodes: + continue + + # Mark this node as processed + processed_nodes.add(current_node) + + # Update the shortest distances to all neighboring nodes + for neighbor, weight in graph[current_node].items(): + distance = current_distance + weight + if distance < shortest_distances[neighbor]: + shortest_distances[neighbor] = distance + queue.append((neighbor, distance)) + + return shortest_distances + +# Example usage +graph = { + 'A': {'B': 5, 'C': 1}, + 'B': {'A': 5, 'C': 2, 'D': 1}, + 'C': {'A': 1, 'B': 2, 'D': 4}, + 'D': {'B': 1, 'C': 4} +} + +start_node = 'A' +distances = dijkstra(graph, start_node) + +print(distances) From b57dee1624024b1338026f47e36072f15ebb50f4 Mon Sep 17 00:00:00 2001 From: Tyler Le Date: Sun, 2 Apr 2023 11:53:11 -0700 Subject: [PATCH 0583/1894] add contribution --- Graphs/Graphs_Dijkstras.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Graphs/Graphs_Dijkstras.py b/Graphs/Graphs_Dijkstras.py index 46911f56..928ab250 100644 --- a/Graphs/Graphs_Dijkstras.py +++ b/Graphs/Graphs_Dijkstras.py @@ -1,3 +1,6 @@ +# Graphs Dijkstras Implementation +# Program Author : Tyler Le + def dijkstra(graph, start): # Create a dictionary to store the shortest distances to each node shortest_distances = {node: float('inf') for node in graph} From 60302db4fde0f51a0228ee938123979cfbd1d9e2 Mon Sep 17 00:00:00 2001 From: Tyler Le Date: Sun, 2 Apr 2023 11:54:29 -0700 Subject: [PATCH 0584/1894] add dijjkstra purpose in comment --- Graphs/Graphs_Dijkstras.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Graphs/Graphs_Dijkstras.py b/Graphs/Graphs_Dijkstras.py index 928ab250..e435d96b 100644 --- a/Graphs/Graphs_Dijkstras.py +++ b/Graphs/Graphs_Dijkstras.py @@ -1,6 +1,10 @@ # Graphs Dijkstras Implementation # Program Author : Tyler Le +# Dijkstra's algorithm is a graph search algorithm +# that solves the single-source shortest path problem +# for a graph with non-negative edge weights + def dijkstra(graph, start): # Create a dictionary to store the shortest distances to each node shortest_distances = {node: float('inf') for node in graph} From d2d4f839aadeb19d82e1f086879c855324893134 Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Mon, 3 Apr 2023 20:24:15 +0530 Subject: [PATCH 0585/1894] Dijkstras algorithm in javascript initial commit --- Graphs/Graphs_dijkstras.js | 141 +++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 Graphs/Graphs_dijkstras.js diff --git a/Graphs/Graphs_dijkstras.js b/Graphs/Graphs_dijkstras.js new file mode 100644 index 00000000..f3cdf50e --- /dev/null +++ b/Graphs/Graphs_dijkstras.js @@ -0,0 +1,141 @@ +// A class representing a priority queue +class PriorityQueue { + constructor() { + this.items = [] + } + + // Adds an item to the priority queue with a given priority + enqueue(item, priority) { + let added = false + + for (let i = 0; i < this.items.length; i++) { + if (priority < this.items[i].priority) { + this.items.splice(i, 0, { item, priority }) + added = true + break + } + } + + if (!added) this.items.push({ item, priority }) + } + + // Removes and returns the item with minimum priority from the priority queue + dequeue() { + if (this.isEmpty()) return null + + return this.items.shift() + } + + // Returns true if the priority queue is empty, false otherwise + isEmpty() { + return this.items.length === 0 + } + + // Returns the number of items in the priority queue + size() { + return this.items.length + } +} + +// Performs Dijkstra's shortest path algorithm on a given graph with a specified start node +function dijkstra(graph, n, start) { + const visited = new Array(n) // An array to keep track of visited nodes + visited.fill(false) + + const distances = new Array(n) // An array to store the distances from the start node to each node in the graph based on indices + distances.fill(Number.POSITIVE_INFINITY) + distances[start] = 0 + + // An array to store the previous node in the shortest path to each node in the graph based on indices + const prev = new Array(n) + prev.fill(null) + + const pq = new PriorityQueue() //Creating a new priority queue + pq.enqueue(start, 0) // Initializing the priority queue + + while (!pq.isEmpty()) { + const val = pq.dequeue() // Dequeue the node with the lowest priority + const idx = val.item // Get the index of the dequeued node + const min = val.priority // Get the distance of the dequeued node + visited[idx] = true // Mark the node as visited + + if (distances[idx] < min) continue // If the distance of the dequeued node is less than the minimum distance, continue to the next iteration of the loop + + // Iterate over the neighbors of the dequeued/current node + for (let edge of graph[idx]) { + if (visited[edge]) continue // If the destination node of the edge has already been visited, continue to the next iteration of the loop + + const newDist = distances[idx] + edge.weight // Calculate the new distance to the destination node + + // If the new distance is less than the current distance to the destination node, update the previous node, distance, and add the destination node to the priority queue + if (newDist < distances[edge.node]) { + prev[edge.node] = idx + distances[edge.node] = newDist + pq.enqueue(edge.node, newDist) + } + } + } + + // Return the distances and previous nodes arrays in an object + return { distances, prev } +} + +// Finds the shortest path between the start and end nodes in the given graph using Dijkstra's algorithm +function findShortestPath(graph, n, start, end) { + + // check if start node is present in the graph, if not, throw error. + if (!graph.hasOwnProperty(start)) { + throw new Error(`Start node ${start} not found in graph`) + } + + // check if end node is present in the graph, if not, throw error. + if (!graph.hasOwnProperty(end)) { + throw new Error(`End node ${end} not found in graph`) + } + + const res = dijkstra(graph, n, start) // Run Dijkstra's algorithm to get the shortest distances and paths from the start node to all other nodes + const distances = res.distances // Extract the distances array from the result of Dijkstra's algorithm + const prev = res.prev // Extract the previous nodes array from the result of Dijkstra's algorithm + const path = [] // Initialize an empty array to store the shortest path from the start to end node + + // If the end node is not reachable from the start node, return an empty path + if (distances[parseInt(end)] == Number.POSITIVE_INFINITY) return path + + // Traverse the previous nodes array backwards from the end node to the start node to construct the shortest path + for (let i = end; i !== null; i = prev[i]) path.unshift(i) + + // Return the shortest path + return path +} + +// Sample Use Case +// The graph will be represented in form of an adjacency list. +/* + The graph will be in form of an object where each key represents the nodes and each value will be an array of the neighbors of the node. + + The array in values will be an object array, where each object has the node, which is the neighbor, and weight, which is the distance to that neighbor from the current node. +*/ +const graph = { + 0: [{ node: 1, weight: 10 }], + 1: [ + { node: 0, weight: 10 }, + { node: 2, weight: 10 }, + { node: 3, weight: 5 }, + ], + 2: [{ node: 1, weight: 10 }], + 3: [ + { node: 1, weight: 5 }, + { node: 4, weight: 10 }, + { node: 5, weight: 10 }, + ], + 4: [ + { node: 3, weight: 10 }, + { node: 5, weight: 10 }, + ], + 5: [ + { node: 3, weight: 10 }, + { node: 4, weight: 10 }, + ], +} + +console.log(findShortestPath(graph, 6, 2, 5)) \ No newline at end of file From d3d2eedd64ee2777ad7e0ca24b9da2e962b51740 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 22:54:42 +0530 Subject: [PATCH 0586/1894] add semorpnilap pairs --- Searching/semordnilap.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Searching/semordnilap.go diff --git a/Searching/semordnilap.go b/Searching/semordnilap.go new file mode 100644 index 00000000..1d0e1fdf --- /dev/null +++ b/Searching/semordnilap.go @@ -0,0 +1,35 @@ +/* + Write a function that takes in a list of unique strings and returns a list of + semordnilap pairs. + + A semordnilap pair is defined as a set of different strings where the reverse + of one word is the same as the forward version of the other. For example the + words "diaper" and "repaid" are a semordnilap pair, as are the words + "palindromes" and "semordnilap". +*/ +package main + +func Semordnilap(words []string) [][]string { + result := [][]string{} + wordSet := make(map[string]bool) + for _, word := range words { + wordSet[word] = true + } + for _, word := range words { + reverse := reverse(word) + if _, wordInSet := wordSet[reverse]; wordInSet && word != reverse { + result = append(result, []string{word, reverse}) + delete(wordSet, word) + delete(wordSet, reverse) + } + } + return result +} + +func reverse(s string) string { + x := []byte{} + for i := len(s) - 1; i >= 0; i-- { + x = append(x, s[i]) + } + return string(x) +} From 98a60e7e47aa1a188173e6c9fe669bdbbb421b09 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 22:55:29 +0530 Subject: [PATCH 0587/1894] add sample io --- Searching/semordnilap.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Searching/semordnilap.go b/Searching/semordnilap.go index 1d0e1fdf..44063515 100644 --- a/Searching/semordnilap.go +++ b/Searching/semordnilap.go @@ -7,6 +7,9 @@ words "diaper" and "repaid" are a semordnilap pair, as are the words "palindromes" and "semordnilap". */ + +// Sample Input : = ["diaper", "abc", "test", "cba", "repaid"] +// Output : package main func Semordnilap(words []string) [][]string { From 615d52bfc08d1810512e99238d02bfcfef62f553 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 22:56:13 +0530 Subject: [PATCH 0588/1894] add time and space complexity --- Searching/semordnilap.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Searching/semordnilap.go b/Searching/semordnilap.go index 44063515..3d798635 100644 --- a/Searching/semordnilap.go +++ b/Searching/semordnilap.go @@ -9,7 +9,8 @@ */ // Sample Input : = ["diaper", "abc", "test", "cba", "repaid"] -// Output : +// Output : [["diaper", "repaid"], ["abc", "cba"]] +// Time and Space complexity : O(n * m) time | O(n * m) space - where n is the number of words and m is the length of the longest word package main func Semordnilap(words []string) [][]string { From 4c85ebad4ee7035207e13868059aa7d7ad81f2c0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 22:57:06 +0530 Subject: [PATCH 0589/1894] add approach --- Searching/semordnilap.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Searching/semordnilap.go b/Searching/semordnilap.go index 3d798635..a31f6389 100644 --- a/Searching/semordnilap.go +++ b/Searching/semordnilap.go @@ -15,10 +15,14 @@ package main func Semordnilap(words []string) [][]string { result := [][]string{} + // crete word set wordSet := make(map[string]bool) for _, word := range words { wordSet[word] = true } + + // After creating the set of words, try iterating through the original array. For + // each word, can you check if its semordnilap pair is in the word list for _, word := range words { reverse := reverse(word) if _, wordInSet := wordSet[reverse]; wordInSet && word != reverse { From 35545cafa9ee8ad2b588a197b41b0ffc9665b7e2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 23:01:57 +0530 Subject: [PATCH 0590/1894] add zero sum subarray in c++ --- Hash Table/zero_sum_subarray.cpp | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Hash Table/zero_sum_subarray.cpp diff --git a/Hash Table/zero_sum_subarray.cpp b/Hash Table/zero_sum_subarray.cpp new file mode 100644 index 00000000..aa253634 --- /dev/null +++ b/Hash Table/zero_sum_subarray.cpp @@ -0,0 +1,39 @@ +#include +#include +#include + +using namespace std; + +vector zeroSumSubarray(vector& nums) { + vector result; + unordered_map mp; + int sum = 0; + mp[0] = -1; + + for (int i = 0; i < nums.size(); i++) { + sum += nums[i]; + if (mp.find(sum) != mp.end()) { + result.push_back(mp[sum] + 1); + result.push_back(i); + break; + } + mp[sum] = i; + } + + return result; +} + +int main() { + vector nums = {4, 2, -3, 1, 6}; + vector result = zeroSumSubarray(nums); + if (result.empty()) { + cout << "No zero sum subarray found." << endl; + } else { + cout << "Zero sum subarray found: "; + for (int i = result[0]; i <= result[1]; i++) { + cout << nums[i] << " "; + } + cout << endl; + } + return 0; +} From ed8e4da7dd58aa9306f79fd26963b8153b05176b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 23:02:06 +0530 Subject: [PATCH 0591/1894] add comments --- Hash Table/zero_sum_subarray.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Hash Table/zero_sum_subarray.cpp b/Hash Table/zero_sum_subarray.cpp index aa253634..8a6dd8e7 100644 --- a/Hash Table/zero_sum_subarray.cpp +++ b/Hash Table/zero_sum_subarray.cpp @@ -1,3 +1,25 @@ +/* + You're given a list of integers nums. Write a function that returns a boolean representing + whether there exists a zero-sum subarray of nums + + Sample Input : = [-5, -5, 2, 3, -2] + Output : True + The subarray [-5, 2, 3] has a sum of 0 +*/ +/* +Approach: + + A good way to approach this problem is to first think of a simpler version. + How would you check if the entire array sum is zero? + + If the entire array does not sum to zero, then you need to check if there are + any smaller subarrays that sum to zero. For this, it can be helpful to keep + track of all of the sums from [0, i], where i is every index in the array. + + After recording all sums from [0, i], what would it mean if a sum is repeated? +*/ +// Time and Space complexity : O(n) time | O(n) space - where n is the length of nums + #include #include #include From 6b7638182d1a53009935235d47e4c88d0ec04e43 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 23:07:04 +0530 Subject: [PATCH 0592/1894] update approach --- Hash Table/zero_sum_subarray.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Hash Table/zero_sum_subarray.cpp b/Hash Table/zero_sum_subarray.cpp index 8a6dd8e7..4d1a809c 100644 --- a/Hash Table/zero_sum_subarray.cpp +++ b/Hash Table/zero_sum_subarray.cpp @@ -19,7 +19,18 @@ After recording all sums from [0, i], what would it mean if a sum is repeated? */ // Time and Space complexity : O(n) time | O(n) space - where n is the length of nums - +/* +This implementation uses an unordered map to keep track of the prefix sum of the input array nums. +We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the +subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the +input array nums, adding each element to the running sum sum and checking if the current sum is +already in the map. If it is, then we've found a subarray whose sum is 0, so we add the starting and +ending indices of the subarray to the result vector and break out of the loop. +If we reach the end of the loop without finding a zero sum subarray, then we return an empty vector. +Note that this implementation assumes that there is only one zero sum subarray in the input array. +If there could be multiple zero sum subarrays, then we would need to modify the implementation to +return all of them. +*/ #include #include #include From e70cb533a2c82bb680dd33fe258adccb329d3051 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 23:07:10 +0530 Subject: [PATCH 0593/1894] add approach --- Hash Table/zero_sum_subarray.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go index 5bd80d40..11e31112 100644 --- a/Hash Table/zero_sum_subarray.go +++ b/Hash Table/zero_sum_subarray.go @@ -9,16 +9,20 @@ /* Approach: - A good way to approach this problem is to first think of a simpler version. - How would you check if the entire array sum is zero? + Time and Space complexity : O(n) time | O(n) space - where n is the length of nums - If the entire array does not sum to zero, then you need to check if there are - any smaller subarrays that sum to zero. For this, it can be helpful to keep - track of all of the sums from [0, i], where i is every index in the array. - - After recording all sums from [0, i], what would it mean if a sum is repeated? + This implementation uses an unordered map to keep track of the prefix sum of the input array nums. + We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the + subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the + input array nums, adding each element to the running sum sum and checking if the current sum is + already in the map. If it is, then we've found a subarray whose sum is 0, so we add the starting and + ending indices of the subarray to the result vector and break out of the loop. + If we reach the end of the loop without finding a zero sum subarray, then we return an empty vector. + Note that this implementation assumes that there is only one zero sum subarray in the input array. + If there could be multiple zero sum subarrays, then we would need to modify the implementation to + return all of them. +*/ */ -// Time and Space complexity : O(n) time | O(n) space - where n is the length of nums package main import "fmt" From 98ae1b8b27b0313d184e688f77b8f53837a3bd3e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Apr 2023 23:08:00 +0530 Subject: [PATCH 0594/1894] update approach --- Hash Table/zero_sum_subarray.cpp | 36 +++++++++++--------------------- Hash Table/zero_sum_subarray.go | 6 +----- 2 files changed, 13 insertions(+), 29 deletions(-) diff --git a/Hash Table/zero_sum_subarray.cpp b/Hash Table/zero_sum_subarray.cpp index 4d1a809c..3e833125 100644 --- a/Hash Table/zero_sum_subarray.cpp +++ b/Hash Table/zero_sum_subarray.cpp @@ -5,31 +5,19 @@ Sample Input : = [-5, -5, 2, 3, -2] Output : True The subarray [-5, 2, 3] has a sum of 0 -*/ -/* -Approach: - - A good way to approach this problem is to first think of a simpler version. - How would you check if the entire array sum is zero? - If the entire array does not sum to zero, then you need to check if there are - any smaller subarrays that sum to zero. For this, it can be helpful to keep - track of all of the sums from [0, i], where i is every index in the array. - - After recording all sums from [0, i], what would it mean if a sum is repeated? -*/ -// Time and Space complexity : O(n) time | O(n) space - where n is the length of nums -/* -This implementation uses an unordered map to keep track of the prefix sum of the input array nums. -We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the -subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the -input array nums, adding each element to the running sum sum and checking if the current sum is -already in the map. If it is, then we've found a subarray whose sum is 0, so we add the starting and -ending indices of the subarray to the result vector and break out of the loop. -If we reach the end of the loop without finding a zero sum subarray, then we return an empty vector. -Note that this implementation assumes that there is only one zero sum subarray in the input array. -If there could be multiple zero sum subarrays, then we would need to modify the implementation to -return all of them. + Approach: + Time and Space complexity : O(n) time | O(n) space - where n is the length of nums + This implementation uses an unordered map to keep track of the prefix sum of the input array nums. + We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the + subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the + input array nums, adding each element to the running sum sum and checking if the current sum is + already in the map. If it is, then we've found a subarray whose sum is 0, so we add the starting and + ending indices of the subarray to the result vector and break out of the loop. + If we reach the end of the loop without finding a zero sum subarray, then we return an empty vector. + Note that this implementation assumes that there is only one zero sum subarray in the input array. + If there could be multiple zero sum subarrays, then we would need to modify the implementation to + return all of them. */ #include #include diff --git a/Hash Table/zero_sum_subarray.go b/Hash Table/zero_sum_subarray.go index 11e31112..9551c557 100644 --- a/Hash Table/zero_sum_subarray.go +++ b/Hash Table/zero_sum_subarray.go @@ -5,12 +5,9 @@ Sample Input : = [-5, -5, 2, 3, -2] Output : True The subarray [-5, 2, 3] has a sum of 0 -*/ -/* -Approach: + Approach: Time and Space complexity : O(n) time | O(n) space - where n is the length of nums - This implementation uses an unordered map to keep track of the prefix sum of the input array nums. We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the @@ -22,7 +19,6 @@ Approach: If there could be multiple zero sum subarrays, then we would need to modify the implementation to return all of them. */ -*/ package main import "fmt" From 76aaaab456256b19009ac20ad32d0616cb350bf4 Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Tue, 4 Apr 2023 20:51:23 +0530 Subject: [PATCH 0595/1894] Initial commit for middle of the linked list in js --- Linked List/linked_list_middle.js | 57 +++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Linked List/linked_list_middle.js diff --git a/Linked List/linked_list_middle.js b/Linked List/linked_list_middle.js new file mode 100644 index 00000000..3b06c422 --- /dev/null +++ b/Linked List/linked_list_middle.js @@ -0,0 +1,57 @@ +/* + Given the head of a singly linked list, return the middle node of the linked list. + + If there are two middle nodes, return the second middle node. + + Example 1: + + Input: head = [1,2,3,4,5] + Output: [3,4,5] + Explanation: The middle node of the list is node 3. + + Example 2: + + Input: head = [1,2,3,4,5,6] + Output: [4,5,6] + Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. + + Constraints: + + The number of nodes in the list is in the range [1, 100]. + 1 <= Node.val <= 100 +*/ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var middleNode = function(head) { + let curr = head // Initialize the current node to the head + let size = 0 // Initialize the size to 0 + + // Traverse the Linked List + while (curr) { + size += 1 // Keep track of the size of the Linked List + curr = curr.next + } // curr is equal to null at the end of the loop + + let mid = Math.floor(size / 2) + 1 // Calculate the middle of the List + let count = 0 + curr = head // Reset current to head + + // Traverse the Linked List + while (curr) { + count += 1 // Keep track of the number of visited nodes in the List + + if (count === mid) return curr // When middle node found, return it + + curr = curr.next + } +}; \ No newline at end of file From c8c5bb39f58a6b5230deb676d5d0246969bff09d Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Tue, 4 Apr 2023 21:04:34 +0530 Subject: [PATCH 0596/1894] BFS in js Initial commit --- Graphs/Graphs_bfs.js | 67 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Graphs/Graphs_bfs.js diff --git a/Graphs/Graphs_bfs.js b/Graphs/Graphs_bfs.js new file mode 100644 index 00000000..f6cf01b3 --- /dev/null +++ b/Graphs/Graphs_bfs.js @@ -0,0 +1,67 @@ +// Define a function that takes a graph and a starting node as input +function bfs(graph, startNode) { + // Initialize an empty object to keep track of visited nodes + const visited = {} + // Initialize a queue with the starting node + const queue = [startNode] + + // Mark the starting node as visited + visited[startNode] = true + + // While there are nodes in the queue + while (queue.length > 0) { + // Get the next node from the front of the queue + const currentNode = queue.shift() + // Log the current node to the console (or do something else with it) + console.log(currentNode) + + // Get the adjacent nodes of the current node from the graph + const adjacentNodes = graph[currentNode] + + // For each adjacent node + for (let i = 0; i < adjacentNodes.length; i++) { + // Get the adjacent node + const adjacentNode = adjacentNodes[i].node + + // If the adjacent node has not been visited + if (!visited[adjacentNode]) { + // Mark the adjacent node as visited + visited[adjacentNode] = true + // Add the adjacent node to the back of the queue + queue.push(adjacentNode) + } + } + } + } + +// SAMPLE USE CASE +// The graph will be represented in form of an adjacency list. +/* + The graph will be in form of an object where each key represents the nodes and each value will be an array of the neighbors of the node. + + The array in values will be an object array, where each object has the node, which is the neighbor, and weight, which is the distance to that neighbor from the current node. +*/ +const graph = { + 0: [{ node: 1, weight: 10 }], + 1: [ + { node: 0, weight: 10 }, + { node: 2, weight: 10 }, + { node: 3, weight: 5 }, + ], + 2: [{ node: 1, weight: 10 }], + 3: [ + { node: 1, weight: 5 }, + { node: 4, weight: 10 }, + { node: 5, weight: 10 }, + ], + 4: [ + { node: 3, weight: 10 }, + { node: 5, weight: 10 }, + ], + 5: [ + { node: 3, weight: 10 }, + { node: 4, weight: 10 }, + ], +} + +bfs(graph, 2) \ No newline at end of file From 544574a6f0abb7b4b971cb41a22f14d315eba188 Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Tue, 4 Apr 2023 21:14:12 +0530 Subject: [PATCH 0597/1894] DFS in javascript Initial Commit --- Graphs/Graphs_dfs.js | 65 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Graphs/Graphs_dfs.js diff --git a/Graphs/Graphs_dfs.js b/Graphs/Graphs_dfs.js new file mode 100644 index 00000000..4b0dee62 --- /dev/null +++ b/Graphs/Graphs_dfs.js @@ -0,0 +1,65 @@ +// Takes in a graph object and a starting node +function dfs(graph, startNode) { + // Initialize an empty visited object + const visited = {} + + // Call the dfsHelper function with the starting node, the visited object, and the graph object + dfsHelper(startNode, visited, graph) +} + +// Recursive helper function for the DFS algorithm +// Takes in a current node, a visited object, and a graph object +function dfsHelper(node, visited, graph) { + // Mark the current node as visited by adding it to the visited object + visited[node] = true + + // Print the current node (or perform some other action) + console.log(node) + + // Get the adjacent nodes of the current node from the graph object + const adjacentNodes = graph[node] + + // Iterate over the adjacent nodes + for (let i = 0; i < adjacentNodes.length; i++) { + // Get the node of the current adjacent node + const adjacentNode = adjacentNodes[i].node + + // If the adjacent node has not been visited yet, recursively call dfsHelper with the adjacent node + if (!visited[adjacentNode]) { + dfsHelper(adjacentNode, visited, graph) + } + } +} + +// SAMPLE USE CASE +// The graph will be represented in form of an adjacency list. +/* + The graph will be in form of an object where each key represents the nodes and each value will be an array of the neighbors of the node. + + The array in values will be an object array, where each object has the node, which is the neighbor, and weight, which is the distance to that neighbor from the current node. +*/ + +const graph = { + 0: [{ node: 1, weight: 10 }], + 1: [ + { node: 0, weight: 10 }, + { node: 2, weight: 10 }, + { node: 3, weight: 5 }, + ], + 2: [{ node: 1, weight: 10 }], + 3: [ + { node: 1, weight: 5 }, + { node: 4, weight: 10 }, + { node: 5, weight: 10 }, + ], + 4: [ + { node: 3, weight: 10 }, + { node: 5, weight: 10 }, + ], + 5: [ + { node: 3, weight: 10 }, + { node: 4, weight: 10 }, + ], +} + +dfs(graph, 0) \ No newline at end of file From a46111a07a88f073bba44a24a2452e1c4c2ec782 Mon Sep 17 00:00:00 2001 From: Mahesh Kumar Date: Tue, 4 Apr 2023 22:10:30 +0530 Subject: [PATCH 0598/1894] I have added ZeroSumSubarray Solution --- Hash Table/ZeroSumSubarray.java | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Hash Table/ZeroSumSubarray.java diff --git a/Hash Table/ZeroSumSubarray.java b/Hash Table/ZeroSumSubarray.java new file mode 100644 index 00000000..0fd2a8cd --- /dev/null +++ b/Hash Table/ZeroSumSubarray.java @@ -0,0 +1,40 @@ +/* +Q -> Hash Table: You're given a list of integers nums. +Write a function that returns a boolean representing whether there exists a zero-sum subarray of nums in Java +*/ + +//Here's a Java code that implements a solution to find if there is a zero-sum subarray in the given list of +// integers using a hash table. + +import java.util.*; + +public class ZeroSumSubarray { + + public static boolean hasZeroSumSubarray(int[] nums) { + Set set = new HashSet<>(); + int sum = 0; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + if (sum == 0 || set.contains(sum)) { + return true; + } + set.add(sum); + } + return false; + } + + public static void main(String[] args) { + int[] nums = {4, -3, 2, 1, 8}; + boolean hasZeroSumSubarray = hasZeroSumSubarray(nums); + System.out.println(hasZeroSumSubarray); + } +} + +/* +Explanation:- + +The above code uses a HashSet to keep track of the prefix sum of the elements of the input array. At each index, it checks if the sum up to that index has already been seen before in the HashSet. +If it has been seen, it means that there exists a subarray with a zero sum. If the sum equals zero, then the subarray starts from the beginning of the array. +The time complexity of this algorithm is O(n), where n is the size of the input array, since we traverse the input array only once. +The space complexity is also O(n), since the HashSet can contain up to n elements in the worst case. + */ From 2594f3c242147c675c8a6871520312be5ccf6f83 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Apr 2023 22:35:33 +0530 Subject: [PATCH 0599/1894] add two sum in js --- Hash Table/two_sum.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Hash Table/two_sum.js diff --git a/Hash Table/two_sum.js b/Hash Table/two_sum.js new file mode 100644 index 00000000..50d8a33f --- /dev/null +++ b/Hash Table/two_sum.js @@ -0,0 +1,42 @@ +/* + Write a function that takes in a non-empty array of distinct integers and an + integer representing a target sum. If any two numbers in the input array sum + up to the target sum, the function should return them in an array, in any + order. If no two numbers sum up to the target sum, the function should return + an empty array. + Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 + Output: [-1 11] +*/ +function twoNumberSum(nums, target) { + // Create a new Map object to store the indices of the elements in the array + const map = new Map(); + + // Loop through the array + for (let i = 0; i < nums.length; i++) { + // Calculate the complement of the current element with respect to the target sum + const complement = target - nums[i]; + + // Check if the complement is already in the map + if (map.has(complement)) { + // If the complement is in the map, return the indices of the two elements that sum up to the target + return [map.get(complement), i]; + } + + // If the complement is not in the map, add the current element and its index to the map + map.set(nums[i], i); + } + + // If no two elements sum up to the target, return an empty array + return []; +} + +// Example usage +const nums = [2, 7, 11, 15]; +const target = 9; +const result = twoNumberSum(nums, target); + +if (result.length > 0) { + console.log(`Indices of the two numbers that sum up to ${target}: ${result}`); +} else { + console.log(`No two numbers found that sum up to ${target}.`); +} From 297d4f7c456028e157ea8af4ac4e2ddee89fd0ad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Apr 2023 22:35:40 +0530 Subject: [PATCH 0600/1894] modify two sum in c++ --- Hash Table/two_sum.cpp | 67 +++++++++++++++++++++++++++--------------- 1 file changed, 43 insertions(+), 24 deletions(-) diff --git a/Hash Table/two_sum.cpp b/Hash Table/two_sum.cpp index 9f068cc2..21cfceb9 100644 --- a/Hash Table/two_sum.cpp +++ b/Hash Table/two_sum.cpp @@ -7,29 +7,48 @@ Sample Input: [2, 1, 3, -1, 11, 5, 4, 0] Target: 10 Output: [-1 11] */ -// Two Pointer approach -// sort the given array, set i as initial index and j as last -// add element at i and j and compate with target, if it matches then return -// if element is greater then target decrease index of j by 1 -// if element is lesser then target increase index of i by 1 -class Solution { -public: - vector twoSum(vector& nums, int target) { - unordered_map mp; - vector result; // result vector - for(int i = 0; i < nums.size(); i++){ - // lets say first element in our array is 3, and target sum is 10 - // then we will look for 7 in our map, if its present then we simply return 7 and 3 - int to_find = target - nums[i]; - // if the required value is found then store result - if(mp.find(to_find) != mp.end()){ - result.push_back(mp[to_find]); - result.push_back(i); - return result; - } - // keep track of what value in array we have seen so far - mp[nums[i]] = i; +#include +#include +#include + +std::vector twoNumberSum(std::vector& nums, int target) { + // Create an unordered_map to store the indices of the elements in the vector + std::unordered_map map; + + // Loop through the vector + for (int i = 0; i < nums.size(); i++) { + // Calculate the complement of the current element with respect to the target sum + int complement = target - nums[i]; + + // Check if the complement is already in the map + if (map.count(complement) > 0) { + // If the complement is in the map, return the indices of the two elements that sum up to the target + return { map[complement], i }; } - return result; + + // If the complement is not in the map, add the current element and its index to the map + map[nums[i]] = i; } -}; \ No newline at end of file + + // If no two elements sum up to the target, return an empty vector + return {}; +} + +int main() { + // Example usage + std::vector nums = { 2, 7, 11, 15 }; + int target = 9; + std::vector result = twoNumberSum(nums, target); + + if (result.size() > 0) { + std::cout << "Indices of the two numbers that sum up to " << target << ": "; + for (int i : result) { + std::cout << i << " "; + } + std::cout << std::endl; + } else { + std::cout << "No two numbers found that sum up to " << target << "." << std::endl; + } + + return 0; +} From 35455383e88e643ca9c1dc1f671d9fedb88d9aa8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Apr 2023 22:38:35 +0530 Subject: [PATCH 0601/1894] update triplet sum in c++ --- Arrays/triplet_sum.cpp | 83 +++++++++++++++++++++++++++--------------- 1 file changed, 54 insertions(+), 29 deletions(-) diff --git a/Arrays/triplet_sum.cpp b/Arrays/triplet_sum.cpp index c7c2d45d..6935b4e7 100644 --- a/Arrays/triplet_sum.cpp +++ b/Arrays/triplet_sum.cpp @@ -4,37 +4,62 @@ determine if there are any three integers in nums whose sum equals the target. Return TRUE if three such integers are found in the array. Otherwise, return FALSE. */ -#include -using namespace std; -string findTriplet(int arr[], int n, int target) -{ - int l, r; - /* Sort the elements */ - sort(arr, arr + n); - /* start with the first element */ - for (int i = 0; i < n - 2; i++) { - l = i + 1; // index of the first element - r = n - 1; // last element - while (l < r) { - if (arr[i] + arr[l] + arr[r] == target) { - return "TRUE"; +#include +#include +#include + +std::vector> threeNumberSum(std::vector& nums, int targetSum) { + // Sort the input array in non-decreasing order + std::sort(nums.begin(), nums.end()); + + std::vector> triplets; + + // Loop through the array + for (int i = 0; i < nums.size() - 2; i++) { + int left = i + 1; + int right = nums.size() - 1; + + // While the left index is less than the right index + while (left < right) { + int currentSum = nums[i] + nums[left] + nums[right]; + + if (currentSum == targetSum) { + // If the current triplet sums up to the target sum, add it to the result vector + triplets.push_back({ nums[i], nums[left], nums[right] }); + + // Move the left and right indices towards the center to find other triplets + left++; + right--; + } else if (currentSum < targetSum) { + // If the current triplet sums up to less than the target sum, move the left index towards the center to find larger numbers + left++; + } else { + // If the current triplet sums up to more than the target sum, move the right index towards the center to find smaller numbers + right--; } - else if (arr[i] + arr[l] + arr[r] < target) - l++; - else - // A[i] + A[l] + A[r] is greater than target - r--; } } - // If no triplet was found - return "FALSE"; + + return triplets; } -int main() -{ - int arr[] = { 1, 2, 3, 4, 5, 6}; - int target = 9; - int n = sizeof(arr) / sizeof(arr[0]); - cout< nums = { 12, 3, 1, 2, -6, 5, -8, 6 }; + int targetSum = 0; + + std::vector> triplets = threeNumberSum(nums, targetSum); + + for (std::vector& triplet : triplets) { + std::cout << "["; + for (int i = 0; i < triplet.size(); i++) { + std::cout << triplet[i]; + if (i < triplet.size() - 1) { + std::cout << ", "; + } + } + std::cout << "]" << std::endl; + } + + return 0; +} From ab8fccecac331f31407025b626e2773c0950b142 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Apr 2023 22:39:20 +0530 Subject: [PATCH 0602/1894] update three number sum for java --- Arrays/triplet_sum.java | 86 ++++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 36 deletions(-) diff --git a/Arrays/triplet_sum.java b/Arrays/triplet_sum.java index 1a77c27e..5eb72674 100644 --- a/Arrays/triplet_sum.java +++ b/Arrays/triplet_sum.java @@ -4,47 +4,61 @@ Return TRUE if three such integers are found in the array. Otherwise, return FALSE. */ -import java.util.*; -class FindTriplet { - boolean findTriplet(int arr[], int n, int sum) - { - int l, r; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; - /* Sort the elements */ - Arrays.sort(arr); +public class ThreeNumberSum { - /* Now fix the first element one by one and find the - other two elements */ - for (int i = 0; i < n - 2; i++) { - - l = i + 1; // index of the first element - r = n - 1; // index of the last element - while (l < r) { - if (arr[i] + arr[l] + arr[r] == sum) { - return true; + public static List> threeNumberSum(int[] nums, int targetSum) { + Arrays.sort(nums); // Sort the input array in non-decreasing order + List> triplets = new ArrayList<>(); + + // Loop through the array + for (int i = 0; i < nums.length - 2; i++) { + int left = i + 1; + int right = nums.length - 1; + + // While the left index is less than the right index + while (left < right) { + int currentSum = nums[i] + nums[left] + nums[right]; + + if (currentSum == targetSum) { + // If the current triplet sums up to the target sum, add it to the result list + triplets.add(Arrays.asList(nums[i], nums[left], nums[right])); + + // Move the left and right indices towards the center to find other triplets + left++; + right--; + } else if (currentSum < targetSum) { + // If the current triplet sums up to less than the target sum, move the left index towards the center to find larger numbers + left++; + } else { + // If the current triplet sums up to more than the target sum, move the right index towards the center to find smaller numbers + right--; } - else if (arr[i] + arr[l] + arr[r] < sum) - l++; - - else - // arr[i] + arr[l] + arr[r] is greater than sum - r--; } } - - // If no triplet was found - return false; + + return triplets; } - - public static void main(String[] args) - { - - FindTriplet triplet = new FindTriplet(); - int[] arr = { 1, 2, 3, 4, 5, 6 }; - int sum = 9; - int n = arr.length; - System.out.println(triplet.findTriplet(arr, n, sum)); - } + public static void main(String[] args) { + // Example usage + int[] nums = { 12, 3, 1, 2, -6, 5, -8, 6 }; + int targetSum = 0; + + List> triplets = threeNumberSum(nums, targetSum); + + for (List triplet : triplets) { + System.out.print("["); + for (int i = 0; i < triplet.size(); i++) { + System.out.print(triplet.get(i)); + if (i < triplet.size() - 1) { + System.out.print(", "); + } + } + System.out.println("]"); + } + } } - From 312c42235b1fba0ea3a9e0f417285b93ce86616e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Apr 2023 22:41:33 +0530 Subject: [PATCH 0603/1894] add explanation --- Arrays/triplet_sum.cpp | 12 +++++++++++- Arrays/triplet_sum.java | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Arrays/triplet_sum.cpp b/Arrays/triplet_sum.cpp index 6935b4e7..0dfa6c78 100644 --- a/Arrays/triplet_sum.cpp +++ b/Arrays/triplet_sum.cpp @@ -7,7 +7,17 @@ Return TRUE if three such integers are found in the array. Otherwise, return FAL #include #include #include - +/* + This implementation uses the two pointer technique to find all triplets in the input array that sum up to the target sum. + We first sort the input array in non-decreasing order to simplify the process of finding triplets. We then loop through + the array and use two pointers, one starting from the left and one starting from the right, to find triplets that sum up + to the target sum. For each iteration of the loop, we set the left pointer to the index immediately to the right of the + current index, and the right pointer to the index of the last element in the array. We then move the left and right pointers + towards the center, checking at each step whether the triplet formed by the current indices sums up to the target sum. + If it does, we add the triplet to the result vector and continue searching for other triplets. + If the sum is less than the target sum, we move the left pointer towards the center to find larger numbers. + If the sum is greater than the target sum, we move the right pointer towards the center to find smaller numbers. +*/ std::vector> threeNumberSum(std::vector& nums, int targetSum) { // Sort the input array in non-decreasing order std::sort(nums.begin(), nums.end()); diff --git a/Arrays/triplet_sum.java b/Arrays/triplet_sum.java index 5eb72674..bf8faf11 100644 --- a/Arrays/triplet_sum.java +++ b/Arrays/triplet_sum.java @@ -8,6 +8,18 @@ import java.util.Arrays; import java.util.List; +/* +We sort the input array in non-decreasing order using the Arrays.sort() method, and then loop through +the array using a for loop. We use two pointers, one starting from the left and one starting from the right, +to find triplets that sum up to the target sum. For each iteration of the loop, we set the left pointer to +the index immediately to the right of the current index, and the right pointer to the index of the last +element in the array. We then move the left and right pointers towards the center, checking at each step +whether the triplet formed by the current indices sums up to the target sum. If it does, we add the triplet +to the result list and continue searching for other triplets. If the sum is less than the target sum, we +move the left pointer towards the center to find larger numbers. If the sum is greater than the target +sum, we move the right pointer towards the center to find smaller numbers. +Finally, we print out the result list using a nested for loop to iterate through each triplet and each element in each triplet. +*/ public class ThreeNumberSum { public static List> threeNumberSum(int[] nums, int targetSum) { From b5706b5e78bdad1b7805eae2e12f34f5f25c747a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:13:50 +0530 Subject: [PATCH 0604/1894] update link for javascript solution for two sum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8c46e9e..40095bf9 100644 --- a/README.md +++ b/README.md @@ -539,7 +539,7 @@ The pointers can be used to iterate the data structure in one or both directions ## Practice problems for two pointers -- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) +- Two sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Hash%20Table/two_sum.js) - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) From d4d209a8af92f5e591e0b2396671a9bd080340b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:21:14 +0530 Subject: [PATCH 0605/1894] add valid pallindrome in python --- Strings/is_pallindrome.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Strings/is_pallindrome.py diff --git a/Strings/is_pallindrome.py b/Strings/is_pallindrome.py new file mode 100644 index 00000000..98d8c2c1 --- /dev/null +++ b/Strings/is_pallindrome.py @@ -0,0 +1,27 @@ +# Valid Palindrome +''' + 1 The isPalindrome() function takes a string s as input. + 2 The first line of the function converts the string to lowercase and + removes all non-alphanumeric characters. This is achieved using a list comprehension, + where each character in s is checked if it is alphanumeric. + If it is, it is added to a new string, otherwise it is ignored. + The resulting string only contains alphanumeric characters in lowercase. + 3 We then loop through the string from the beginning to the middle character + (the // operator divides the length of the string by 2 and rounds down to the nearest integer). + For each character, we compare it to its corresponding character from the end of the string + (i.e., the len(s) - i - 1-th character), to check if they are the same. + 4 If at any point we find two characters that are not the same, we know that the string is not a + palindrome and return False. + 5 If we complete the loop without finding any mismatches, we know that the string is a palindrome + and return True. +''' +def isPalindrome(s): + # Convert string to lowercase and remove all non-alphanumeric characters + s = "".join(c.lower() for c in s if c.isalnum()) + + # Loop through the string and compare each character to its corresponding character from the end + for i in range(len(s) // 2): + if s[i] != s[len(s) - i - 1]: + return False + + return True From c79221ba252d3fd811f122bbff78187e0e5cdb92 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:21:55 +0530 Subject: [PATCH 0606/1894] update link for valid pallindrome in python --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40095bf9..2d337819 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp)[Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) From 801a4c576b7d5aa2d60fb78fe6724e750f690568 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:23:31 +0530 Subject: [PATCH 0607/1894] add is pallindrome in java --- Strings/is_pallindrome.java | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Strings/is_pallindrome.java diff --git a/Strings/is_pallindrome.java b/Strings/is_pallindrome.java new file mode 100644 index 00000000..c9cabbd7 --- /dev/null +++ b/Strings/is_pallindrome.java @@ -0,0 +1,33 @@ +# Valid Palindrome +''' + 1 The isPalindrome() function takes a string s as input. + 2 The first line of the function converts the string to lowercase and + removes all non-alphanumeric characters. This is achieved using a list comprehension, + where each character in s is checked if it is alphanumeric. + If it is, it is added to a new string, otherwise it is ignored. + The resulting string only contains alphanumeric characters in lowercase. + 3 We then loop through the string from the beginning to the middle character + (the // operator divides the length of the string by 2 and rounds down to the nearest integer). + For each character, we compare it to its corresponding character from the end of the string + (i.e., the len(s) - i - 1-th character), to check if they are the same. + 4 If at any point we find two characters that are not the same, we know that the string is not a + palindrome and return False. + 5 If we complete the loop without finding any mismatches, we know that the string is a palindrome + and return True. +''' +public static boolean isPalindrome(String s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (!Character.isLetterOrDigit(s.charAt(left))) { + left++; + } else if (!Character.isLetterOrDigit(s.charAt(right))) { + right--; + } else if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { + return false; + } else { + left++; + right--; + } + } + return true; +} From 596a4e389bcff304aa5256361f4b08f5e80c69d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:24:11 +0530 Subject: [PATCH 0608/1894] update link for java version of valid pallindrome --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d337819..52af6562 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp)[Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp)[Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) From 11774e62a781b09eb62c6d260f8a10264540ae9a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 08:26:55 +0530 Subject: [PATCH 0609/1894] update comments --- Strings/is_pallindrome.java | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/Strings/is_pallindrome.java b/Strings/is_pallindrome.java index c9cabbd7..8bec3d76 100644 --- a/Strings/is_pallindrome.java +++ b/Strings/is_pallindrome.java @@ -1,20 +1,15 @@ -# Valid Palindrome -''' - 1 The isPalindrome() function takes a string s as input. - 2 The first line of the function converts the string to lowercase and - removes all non-alphanumeric characters. This is achieved using a list comprehension, - where each character in s is checked if it is alphanumeric. - If it is, it is added to a new string, otherwise it is ignored. - The resulting string only contains alphanumeric characters in lowercase. - 3 We then loop through the string from the beginning to the middle character - (the // operator divides the length of the string by 2 and rounds down to the nearest integer). - For each character, we compare it to its corresponding character from the end of the string - (i.e., the len(s) - i - 1-th character), to check if they are the same. - 4 If at any point we find two characters that are not the same, we know that the string is not a - palindrome and return False. - 5 If we complete the loop without finding any mismatches, we know that the string is a palindrome - and return True. -''' +/* Valid Palindrome + +1 We define a method isPalindrome that takes a String argument s and returns a boolean value indicating whether the string is a palindrome or not. +2 We initialize two variables left and right to point to the beginning and end of the string respectively. +3 We enter a while loop that continues until left is less than right. +4 If the character at s[left] is not a letter or digit, we increment left. +5 If the character at s[right] is not a letter or digit, we decrement right. +6 If the characters at s[left] and s[right] are not equal, we return false as the string is not a palindrome. +7 If the characters are equal, we increment left and decrement right. +8 If the while loop completes without finding a mismatched pair of characters, we return true as the string is a palindrome. + +*/ public static boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { From 6acf1559b8e3de1eaa7125dbb8120402bc1039df Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Apr 2023 22:58:51 +0530 Subject: [PATCH 0610/1894] add space bw c++ and python --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52af6562..de39209e 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp)[Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) From aa24fc1f047c6beeabffea9aff908cd9bf174a27 Mon Sep 17 00:00:00 2001 From: Tyler Le Date: Wed, 5 Apr 2023 19:05:51 -0700 Subject: [PATCH 0611/1894] k closest --- Heaps/k_closest.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Heaps/k_closest.py diff --git a/Heaps/k_closest.py b/Heaps/k_closest.py new file mode 100644 index 00000000..dda20a07 --- /dev/null +++ b/Heaps/k_closest.py @@ -0,0 +1,17 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + min_heap = [] + + # For each point, find distance from origin + for x,y in points: + dist = sqrt(x**2 + y**2) + min_heap.append([dist,x,y]) + + # Pop 'k' smallest distances + heapify(min_heap) + res = [] + for _ in range(k): + _,x,y = heappop(min_heap) + res.append([x,y]) + + return res \ No newline at end of file From 40759a9c9720e963d59ce36dd0bf3d54d1546289 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:35:01 +0530 Subject: [PATCH 0612/1894] add zero sum subarray in python --- Hash Table/zero_sum_subarray.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Hash Table/zero_sum_subarray.py diff --git a/Hash Table/zero_sum_subarray.py b/Hash Table/zero_sum_subarray.py new file mode 100644 index 00000000..62d6626f --- /dev/null +++ b/Hash Table/zero_sum_subarray.py @@ -0,0 +1,20 @@ +def zero_sum_subarray(nums): + # Initialize a set to keep track of previously encountered prefix sums. + prefix_sums = set() + prefix_sum = 0 + + # Loop through each number in the array. + for num in nums: + # Add the current number to the running prefix sum. + prefix_sum += num + + # If the current prefix sum is in the set of previous prefix sums, + # then we have found a subarray whose sum is zero. + if prefix_sum in prefix_sums: + return True + + # Add the current prefix sum to the set of previous prefix sums. + prefix_sums.add(prefix_sum) + + # If no subarray whose sum is zero was found, return False. + return False From d88f69d200e7721c5cae30fbeea6ba1d14cb2e71 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:35:46 +0530 Subject: [PATCH 0613/1894] add description --- Hash Table/zero_sum_subarray.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Hash Table/zero_sum_subarray.py b/Hash Table/zero_sum_subarray.py index 62d6626f..aec5aedd 100644 --- a/Hash Table/zero_sum_subarray.py +++ b/Hash Table/zero_sum_subarray.py @@ -1,3 +1,24 @@ +''' + You're given a list of integers nums. Write a function that returns a boolean representing + whether there exists a zero-sum subarray of nums + + Sample Input : = [-5, -5, 2, 3, -2] + Output : True + The subarray [-5, 2, 3] has a sum of 0 + + Approach: + Time and Space complexity : O(n) time | O(n) space - where n is the length of nums + This implementation uses an unordered map to keep track of the prefix sum of the input array nums. + We initialize the map with a key-value pair of 0 and -1, since a prefix sum of 0 indicates that the + subarray from index 0 to -1 (i.e., an empty subarray) has a sum of 0. We then iterate through the + input array nums, adding each element to the running sum sum and checking if the current sum is + already in the map. If it is, then we've found a subarray whose sum is 0, so we add the starting and + ending indices of the subarray to the result vector and break out of the loop. + If we reach the end of the loop without finding a zero sum subarray, then we return an empty vector. + Note that this implementation assumes that there is only one zero sum subarray in the input array. + If there could be multiple zero sum subarrays, then we would need to modify the implementation to + return all of them. +''' def zero_sum_subarray(nums): # Initialize a set to keep track of previously encountered prefix sums. prefix_sums = set() From ccd4b45e2c658877cf647fe7367141ad479872a0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:43:13 +0530 Subject: [PATCH 0614/1894] add zero sum subarray in js --- Hash Table/zero_sum_subarray.js | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hash Table/zero_sum_subarray.js diff --git a/Hash Table/zero_sum_subarray.js b/Hash Table/zero_sum_subarray.js new file mode 100644 index 00000000..6840a0cb --- /dev/null +++ b/Hash Table/zero_sum_subarray.js @@ -0,0 +1,35 @@ +/* + You're given a list of integers nums. Write a function that returns a boolean representing + whether there exists a zero-sum subarray of nums + + Sample Input : = [-5, -5, 2, 3, -2] + Output : True + The subarray [-5, 2, 3] has a sum of 0 + + Time and Space complexity : O(n) time | O(n) space - where n is the length of nums + + Approach: + The function takes in an array of integers nums. It initializes a set sums to keep track of the subarray sums we've seen so far, + and a variable currentSum to keep track of the current sum as we loop through the array. + + We then loop through each number in the array, adding the current number to the current sum. + We check if the current sum is zero or if we've seen it before (i.e. if it's already in the sums set). + If so, we've found a zero-sum subarray, so we return true. + + If we loop through the entire array without finding a zero-sum subarray, we return false. +*/ +function hasZeroSumSubarray(nums) { + const sums = new Set(); // Initialize a set to keep track of the subarray sums + let currentSum = 0; // Initialize a variable to keep track of the current sum + + for (const num of nums) { + // Loop through each number in the array + currentSum += num; // Add the current number to the current sum + if (currentSum === 0 || sums.has(currentSum)) { + // Check if the current sum is zero or if we've seen it before + return true; // If so, we've found a zero-sum subarray, so return true + } + sums.add(currentSum); // Add the current sum to the set of subarray sums + } + return false; // If we loop through the entire array without finding a zero-sum subarray, return false +} From ee72b22cbd8d16bedab8c344b59c262157f2439d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:47:18 +0530 Subject: [PATCH 0615/1894] rename file --- Hash Table/{ZeroSumSubarray.java => zero_sum_subarray.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash Table/{ZeroSumSubarray.java => zero_sum_subarray.java} (100%) diff --git a/Hash Table/ZeroSumSubarray.java b/Hash Table/zero_sum_subarray.java similarity index 100% rename from Hash Table/ZeroSumSubarray.java rename to Hash Table/zero_sum_subarray.java From e36bc875a450f9227dc2da0efb045110aaed1ade Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:51:08 +0530 Subject: [PATCH 0616/1894] add queue data structure in c++ --- Queue/queue.cpp | 83 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Queue/queue.cpp diff --git a/Queue/queue.cpp b/Queue/queue.cpp new file mode 100644 index 00000000..4610de9c --- /dev/null +++ b/Queue/queue.cpp @@ -0,0 +1,83 @@ +// Implement Queue data structure in C++ +#include +using namespace std; + +const int MAX_SIZE = 100; // maximum size of the queue + +class Queue { +private: + int front, rear; + int arr[MAX_SIZE]; +public: + Queue() { + front = -1; // initialize front and rear to -1 to indicate the queue is empty + rear = -1; + } + + bool isFull() { + return rear == MAX_SIZE - 1; // check if the rear index is at the maximum size + } + + bool isEmpty() { + return front == -1 && rear == -1; // check if both front and rear indices are at -1, indicating an empty queue + } + + void enqueue(int x) { + if (isFull()) { + cout << "Error: Queue is full" << endl; + return; + } + if (isEmpty()) { + front = rear = 0; // if the queue is empty, set both front and rear to 0 to add the first element + } + else { + rear++; // increment rear to add the new element + } + arr[rear] = x; // add the new element to the rear of the queue + } + + void dequeue() { + if (isEmpty()) { + cout << "Error: Queue is empty" << endl; + return; + } + if (front == rear) { + front = rear = -1; // if the queue has only one element, set both front and rear indices to -1 to indicate an empty queue + } + else { + front++; // increment front to remove the element + } + } + + int peek() { + if (isEmpty()) { + cout << "Error: Queue is empty" << endl; + return -1; + } + return arr[front]; // return the element at the front of the queue + } + + void print() { + if (isEmpty()) { + cout << "Queue is empty" << endl; + return; + } + cout << "Queue: "; + for (int i = front; i <= rear; i++) { + cout << arr[i] << " "; // print each element in the queue from front to rear + } + cout << endl; + } +}; + +int main() { + Queue q; + q.enqueue(1); + q.enqueue(2); + q.enqueue(3); + q.print(); // output: Queue: 1 2 3 + q.dequeue(); + q.print(); // output: Queue: 2 3 + cout << "Front element: " << q.peek() << endl; // output: Front element: 2 + return 0; +} From 2ed94a9da4fccf8eed65211239492fb69b21e397 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Apr 2023 22:51:51 +0530 Subject: [PATCH 0617/1894] add description --- Queue/queue.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Queue/queue.cpp b/Queue/queue.cpp index 4610de9c..83ab8424 100644 --- a/Queue/queue.cpp +++ b/Queue/queue.cpp @@ -1,4 +1,13 @@ // Implement Queue data structure in C++ +/* + In this implementation, the Queue class has private member variables front, rear, and arr to keep track of the front and rear + indices of the queue and the elements in the queue, respectively. The class also has public member functions isFull(), isEmpty(), + enqueue(), dequeue(), peek(), and print() for checking if the queue is full or empty, adding elements to the rear of the queue, + removing elements from the front of the queue, peeking at the element at the front of the queue, and printing the elements in the + queue, respectively. The main() function demonstrates how to use the Queue class by creating a new queue object q, adding three + elements to the queue, removing one element from the front of the queue, peeking at the element at the front of the queue, and + printing the elements in the queue +*/ #include using namespace std; From e10c90e5a9d00e2ea574efaf68dda0b8a26b10e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:04:32 +0530 Subject: [PATCH 0618/1894] add stack in c++ --- Stacks/stack.cpp | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Stacks/stack.cpp diff --git a/Stacks/stack.cpp b/Stacks/stack.cpp new file mode 100644 index 00000000..8473677b --- /dev/null +++ b/Stacks/stack.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +const int MAX_SIZE = 100; // Maximum size of stack + +class Stack { +private: + int top; // Index of topmost element in stack + int arr[MAX_SIZE]; // Array to store elements of stack +public: + Stack() { + top = -1; // Initialize top index to -1, indicating empty stack + } + + // Pushes an element onto the top of the stack + void push(int x) { + if (top == MAX_SIZE - 1) { // Check if stack is full + cout << "Stack Overflow\n"; + return; + } + arr[++top] = x; // Increment top index and add element to array + } + + // Removes and returns the topmost element from the stack + int pop() { + if (top == -1) { // Check if stack is empty + cout << "Stack Underflow\n"; + return -1; + } + int val = arr[top]; // Store topmost element in a variable + top--; // Decrement top index to remove element from stack + return val; // Return topmost element + } + + // Returns the topmost element in the stack without removing it + int peek() { + if (top == -1) { // Check if stack is empty + cout << "Stack Underflow\n"; + return -1; + } + return arr[top]; // Return topmost element + } + + // Returns true if stack is empty, false otherwise + bool isEmpty() { + return top == -1; + } +}; + +int main() { + Stack s; + + // Push some elements onto the stack + s.push(5); + s.push(10); + s.push(15); + + // Print the topmost element without removing it + cout << "Top element: " << s.peek() << endl; + + // Pop an element from the stack and print it + cout << "Popped element: " << s.pop() << endl; + + // Check if stack is empty + cout << "Is stack empty? " << (s.isEmpty() ? "Yes" : "No") << endl; + + return 0; +} From 5dacfdf8278bcfb308654a346c42aad124833fe6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:05:34 +0530 Subject: [PATCH 0619/1894] add description --- Stacks/stack.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Stacks/stack.cpp b/Stacks/stack.cpp index 8473677b..ed8dafea 100644 --- a/Stacks/stack.cpp +++ b/Stacks/stack.cpp @@ -1,3 +1,12 @@ +// Implemenmtation of stack data structure +/* + This implementation creates a class Stack that has a private integer top to keep track of the index + of the topmost element in the stack, and an integer array arr to store the elements of the stack. + The push, pop, peek, and isEmpty methods are used to add elements to, remove elements from, view + the topmost element in, and check if the stack is empty, respectively. The main function creates + an instance of Stack and demonstrates the use of the stack by pushing some elements onto it, + printing the topmost element, popping an element from the stack, and checking if the stack is empty. +*/ #include using namespace std; From e02b2870f237dbe82a10ad3297402e75d0a46836 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:06:39 +0530 Subject: [PATCH 0620/1894] add stack in java --- Stacks/stack.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Stacks/stack.java diff --git a/Stacks/stack.java b/Stacks/stack.java new file mode 100644 index 00000000..efee753c --- /dev/null +++ b/Stacks/stack.java @@ -0,0 +1,63 @@ +public class Stack { + // array to store elements of the stack + private T[] elements; + // top index of the stack + private int top; + + // constructor to initialize the stack with a given capacity + public Stack(int capacity) { + // create a new array of type T with the given capacity + elements = (T[]) new Object[capacity]; + // initialize top index to -1 + top = -1; + } + + // push an element onto the top of the stack + public void push(T element) { + // check if the stack is full + if (top == elements.length - 1) { + // if the stack is full, throw an exception + throw new RuntimeException("Stack overflow"); + } + // increment top index + top++; + // insert the element at the top index + elements[top] = element; + } + + // pop the top element from the stack and return it + public T pop() { + // check if the stack is empty + if (top == -1) { + // if the stack is empty, throw an exception + throw new RuntimeException("Stack underflow"); + } + // get the top element + T element = elements[top]; + // decrement top index + top--; + // return the top element + return element; + } + + // return the top element of the stack without removing it + public T peek() { + // check if the stack is empty + if (top == -1) { + // if the stack is empty, throw an exception + throw new RuntimeException("Stack underflow"); + } + // return the top element + return elements[top]; + } + + // return true if the stack is empty, false otherwise + public boolean isEmpty() { + return top == -1; + } + + // return the size of the stack + public int size() { + return top + 1; + } +} From baaa38e5e0c31207d0c10184ffbbf8613f142011 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:07:26 +0530 Subject: [PATCH 0621/1894] add description --- Stacks/stack.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Stacks/stack.java b/Stacks/stack.java index efee753c..05afc9f1 100644 --- a/Stacks/stack.java +++ b/Stacks/stack.java @@ -1,3 +1,10 @@ +// Implemenmtation of stack data structure +/* + This implementation uses a generic type T to allow the stack to store elements of any type. + The stack is implemented using an array and has methods for pushing, popping, peeking, checking + if the stack is empty, and getting the size of the stack. The comments explain each step of the + implementation. +*/ public class Stack { // array to store elements of the stack private T[] elements; From 6d5914206a7e0df722150d6dec8dcc4898bf8844 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:08:26 +0530 Subject: [PATCH 0622/1894] add stack in python --- Stacks/stack.py | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Stacks/stack.py diff --git a/Stacks/stack.py b/Stacks/stack.py new file mode 100644 index 00000000..19f3fe69 --- /dev/null +++ b/Stacks/stack.py @@ -0,0 +1,64 @@ +class Stack: + """ + Stack class implementation using list in Python + """ + def __init__(self): + """ + Constructor function to initialize an empty stack + """ + self.items = [] + + def is_empty(self): + """ + Check if stack is empty + + Returns: + bool: True if stack is empty, False otherwise + """ + return len(self.items) == 0 + + def push(self, item): + """ + Push an item onto the stack + + Args: + item: Item to be pushed onto the stack + """ + self.items.append(item) + + def pop(self): + """ + Remove and return the top item from the stack + + Returns: + item: Top item from the stack + + Raises: + IndexError: If stack is empty + """ + if self.is_empty(): + raise IndexError("Stack is empty") + return self.items.pop() + + def peek(self): + """ + Return the top item from the stack without removing it + + Returns: + item: Top item from the stack + + Raises: + IndexError: If stack is empty + """ + if self.is_empty(): + raise IndexError("Stack is empty") + return self.items[-1] + + def size(self): + """ + Return the number of items in the stack + + Returns: + int: Number of items in the stack + """ + return len(self.items) From fbac63f09fd9fd95c1553a72b7f8e69ed88bc7bb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:09:16 +0530 Subject: [PATCH 0623/1894] add description --- Stacks/stack.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Stacks/stack.py b/Stacks/stack.py index 19f3fe69..5b23b597 100644 --- a/Stacks/stack.py +++ b/Stacks/stack.py @@ -1,3 +1,15 @@ +# Implemenmtation of stack data structure +''' + In this implementation, the Stack class contains the following methods: + + __init__: Constructor function to initialize an empty stack. + is_empty: Check if stack is empty. + push: Push an item onto the stack. + pop: Remove and return the top item from the stack. + peek: Return the top item from the stack without removing it. + size: Return the number of items in the stack. + Each method includes a docstring that explains what it does, along with any arguments and return values. +''' class Stack: """ Stack class implementation using list in Python From 05aa3d1c098157a2e44c6aacea78d14f2d20bee5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:11:18 +0530 Subject: [PATCH 0624/1894] add stack in js --- Stacks/stack.js | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Stacks/stack.js diff --git a/Stacks/stack.js b/Stacks/stack.js new file mode 100644 index 00000000..ce1bf275 --- /dev/null +++ b/Stacks/stack.js @@ -0,0 +1,64 @@ +class Stack { + constructor() { + this.items = []; // initializing an empty array + } + + // push function to add an element to the stack + push(element) { + this.items.push(element); + } + + // pop function to remove the topmost element from the stack + pop() { + // checking if the stack is empty + if (this.items.length === 0) + return "Underflow"; + return this.items.pop(); + } + + // peek function to get the topmost element of the stack without removing it + peek() { + // checking if the stack is empty + if (this.items.length === 0) + return "No elements in Stack"; + return this.items[this.items.length - 1]; + } + + // isEmpty function to check if the stack is empty + isEmpty() { + return this.items.length === 0; + } + + // printStack function to print the entire stack + printStack() { + let str = ""; + for (let i = 0; i < this.items.length; i++) { + str += this.items[i] + " "; + } + return str; + } + } + + // creating an instance of the Stack class + let stack = new Stack(); + + // adding elements to the stack + stack.push(10); + stack.push(20); + stack.push(30); + + // printing the stack + console.log(stack.printStack()); // Output: 10 20 30 + + // removing the topmost element from the stack + stack.pop(); + + // printing the stack + console.log(stack.printStack()); // Output: 10 20 + + // checking the topmost element of the stack + console.log(stack.peek()); // Output: 20 + + // checking if the stack is empty + console.log(stack.isEmpty()); // Output: false + \ No newline at end of file From b8e634311fe3197adcb056544aad203bae9d635e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:12:14 +0530 Subject: [PATCH 0625/1894] add description --- Stacks/stack.js | 132 ++++++++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 61 deletions(-) diff --git a/Stacks/stack.js b/Stacks/stack.js index ce1bf275..30239f1f 100644 --- a/Stacks/stack.js +++ b/Stacks/stack.js @@ -1,64 +1,74 @@ +// Implemenmtation of stack data structure +/* + We define a class called Stack with an empty array items to store the stack elements. + The class has four methods: + push(item): Adds an item to the top of the stack by using the push method of the Array object. + pop(): Removes and returns the item at the top of the stack using the pop method of the Array object. + peek(): Returns the item at the top of the stack without removing it using the slice method of the Array object. + isEmpty(): Returns true if the stack is empty, false otherwise by checking the length of the items array. + + This implementation uses the built-in Array object of JavaScript to implement the stack data structure. + The push, pop, and slice methods are used to manipulate the items array to add, remove, and access the + top item of the stack, respectively. The isEmpty method simply checks if the items array is empty or not. +*/ class Stack { - constructor() { - this.items = []; // initializing an empty array - } - - // push function to add an element to the stack - push(element) { - this.items.push(element); - } - - // pop function to remove the topmost element from the stack - pop() { - // checking if the stack is empty - if (this.items.length === 0) - return "Underflow"; - return this.items.pop(); - } - - // peek function to get the topmost element of the stack without removing it - peek() { - // checking if the stack is empty - if (this.items.length === 0) - return "No elements in Stack"; - return this.items[this.items.length - 1]; - } - - // isEmpty function to check if the stack is empty - isEmpty() { - return this.items.length === 0; - } - - // printStack function to print the entire stack - printStack() { - let str = ""; - for (let i = 0; i < this.items.length; i++) { - str += this.items[i] + " "; - } - return str; + constructor() { + this.items = []; // initializing an empty array + } + + // push function to add an element to the stack + push(element) { + this.items.push(element); + } + + // pop function to remove the topmost element from the stack + pop() { + // checking if the stack is empty + if (this.items.length === 0) return "Underflow"; + return this.items.pop(); + } + + // peek function to get the topmost element of the stack without removing it + peek() { + // checking if the stack is empty + if (this.items.length === 0) return "No elements in Stack"; + return this.items[this.items.length - 1]; + } + + // isEmpty function to check if the stack is empty + isEmpty() { + return this.items.length === 0; + } + + // printStack function to print the entire stack + printStack() { + let str = ""; + for (let i = 0; i < this.items.length; i++) { + str += this.items[i] + " "; } + return str; } - - // creating an instance of the Stack class - let stack = new Stack(); - - // adding elements to the stack - stack.push(10); - stack.push(20); - stack.push(30); - - // printing the stack - console.log(stack.printStack()); // Output: 10 20 30 - - // removing the topmost element from the stack - stack.pop(); - - // printing the stack - console.log(stack.printStack()); // Output: 10 20 - - // checking the topmost element of the stack - console.log(stack.peek()); // Output: 20 - - // checking if the stack is empty - console.log(stack.isEmpty()); // Output: false - \ No newline at end of file +} + +// creating an instance of the Stack class +let stack = new Stack(); + +// adding elements to the stack +stack.push(10); +stack.push(20); +stack.push(30); + +// printing the stack +console.log(stack.printStack()); // Output: 10 20 30 + +// removing the topmost element from the stack +stack.pop(); + +// printing the stack +console.log(stack.printStack()); // Output: 10 20 + +// checking the topmost element of the stack +console.log(stack.peek()); // Output: 20 + +// checking if the stack is empty +console.log(stack.isEmpty()); // Output: false From fa58c70b93cd44b63ff314311c48786a39e0184d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:17:45 +0530 Subject: [PATCH 0626/1894] add description --- Queue/queue.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Queue/queue.py diff --git a/Queue/queue.py b/Queue/queue.py new file mode 100644 index 00000000..815ed6d6 --- /dev/null +++ b/Queue/queue.py @@ -0,0 +1,53 @@ +# Implement Queue Data Structure +''' + This implementation uses a Python list to store the items in the queue. The __init__() method initializes + an empty list. The is_empty() method checks whether the list is empty or not by checking the length of + the list. The enqueue() method adds an item to the back of the queue by appending it to the end of the + list. The dequeue() method removes and returns the item at the front of the queue by using the pop() + method to remove the first item in the list. If the list is empty, the method raises an IndexError. + The peek() method returns the item at the front of the queue without removing it by returning the + first item in the list. If the list is empty, the method raises an IndexError. The size() method + returns the number of items in the list by returning the length of the list. +''' +class Queue: + def __init__(self): + """ + Initializes an empty queue. + """ + self.items = [] + + def is_empty(self): + """ + Returns True if the queue is empty, False otherwise. + """ + return len(self.items) == 0 + + def enqueue(self, item): + """ + Adds the given item to the back of the queue. + """ + self.items.append(item) + + def dequeue(self): + """ + Removes and returns the item at the front of the queue. + If the queue is empty, raises an IndexError. + """ + if self.is_empty(): + raise IndexError("Queue is empty") + return self.items.pop(0) + + def peek(self): + """ + Returns the item at the front of the queue without removing it. + If the queue is empty, raises an IndexError. + """ + if self.is_empty(): + raise IndexError("Queue is empty") + return self.items[0] + + def size(self): + """ + Returns the number of items in the queue. + """ + return len(self.items) From 4aa6d735dc79d9784741bfc67143e44759ac5bac Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:19:38 +0530 Subject: [PATCH 0627/1894] add sll in python --- Linked List/linked_list.py | 70 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Linked List/linked_list.py diff --git a/Linked List/linked_list.py b/Linked List/linked_list.py new file mode 100644 index 00000000..d3788a07 --- /dev/null +++ b/Linked List/linked_list.py @@ -0,0 +1,70 @@ +# Implementation of Singly Linked List in Python +# Define a class to represent a node in the linked list +class Node: + def __init__(self, data): + # Each node has two attributes: data and a reference to the next node + self.data = data + self.next = None + +# Define a class to represent the linked list itself +class LinkedList: + def __init__(self): + # Each linked list has one attribute: the head node (which initially is None) + self.head = None + + # Method to insert a new node at the beginning of the linked list + def insert_at_beginning(self, data): + # Create a new node + new_node = Node(data) + + # Set the next node of the new node to be the current head node + new_node.next = self.head + + # Set the head node to be the new node + self.head = new_node + + # Method to insert a new node at the end of the linked list + def insert_at_end(self, data): + # Create a new node + new_node = Node(data) + + # If the list is empty, set the head node to be the new node + if self.head is None: + self.head = new_node + return + + # Traverse to the last node in the list + current_node = self.head + while current_node.next: + current_node = current_node.next + + # Set the next node of the last node to be the new node + current_node.next = new_node + + # Method to delete the first occurrence of a node with the given data + def delete_node(self, data): + # If the list is empty, do nothing + if self.head is None: + return + + # If the node to be deleted is the head node, set the head node to be the next node + if self.head.data == data: + self.head = self.head.next + return + + # Traverse the list to find the node to be deleted + current_node = self.head + while current_node.next: + if current_node.next.data == data: + current_node.next = current_node.next.next + return + current_node = current_node.next + + # Method to print the linked list + def print_list(self): + # Traverse the list and print each node's data + current_node = self.head + while current_node: + print(current_node.data, end=" -> ") + current_node = current_node.next + print("None") From d17649eb06da0f91a6092122e6c48f2747fc0f86 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Apr 2023 20:20:35 +0530 Subject: [PATCH 0628/1894] add description --- Linked List/linked_list.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Linked List/linked_list.py b/Linked List/linked_list.py index d3788a07..6af19fc8 100644 --- a/Linked List/linked_list.py +++ b/Linked List/linked_list.py @@ -1,4 +1,16 @@ # Implementation of Singly Linked List in Python +''' + This implementation defines a Node class to represent a node in the linked list, and a LinkedList + class to represent the linked list itself. The LinkedList class has methods to insert nodes at the + beginning or end of the list, delete nodes from the list, and print the list. Each node has two + attributes: its data and a reference to the next node in the list (next). + The LinkedList class has one attribute: the head node of the list (head). When a new node is + inserted at the beginning of the list, its next attribute is set to the current head node, and the + head attribute is set to the new node. When a new node is inserted at the end of the list, it is + appended to the last node's next attribute. When a node is deleted, the list is traversed to find + the node with the given data, and its next attribute is set to the node after it. Finally, the + print_list method traverses the list and prints each node's data. +''' # Define a class to represent a node in the linked list class Node: def __init__(self, data): From 6b06cf568726b9f0bca235588d947b4b97c6800b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:48:52 +0530 Subject: [PATCH 0629/1894] add rotate clockwise --- 2D Arrays (Matrix)/rotate_matrix.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 2D Arrays (Matrix)/rotate_matrix.js diff --git a/2D Arrays (Matrix)/rotate_matrix.js b/2D Arrays (Matrix)/rotate_matrix.js new file mode 100644 index 00000000..cd5f20b4 --- /dev/null +++ b/2D Arrays (Matrix)/rotate_matrix.js @@ -0,0 +1,22 @@ +function rotateClockwise(matrix) { + // Get the number of rows and columns in the matrix + const rows = matrix.length; + const cols = matrix[0].length; + + // Create a new matrix to store the rotated matrix + const rotated = []; + + // Iterate over the columns in reverse order and create a new row in the rotated matrix + for (let j = cols - 1; j >= 0; j--) { + const newRow = []; + // Iterate over each row in the matrix and add the corresponding element to the new row + for (let i = 0; i < rows; i++) { + newRow.push(matrix[i][j]); + } + // Add the new row to the rotated matrix + rotated.push(newRow); + } + + // Return the rotated matrix + return rotated; +} From 51192984c7edf4454ef6d5a07908e09286ae1f01 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:49:04 +0530 Subject: [PATCH 0630/1894] add rotate anticlock wise --- 2D Arrays (Matrix)/rotate_matrix.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/2D Arrays (Matrix)/rotate_matrix.js b/2D Arrays (Matrix)/rotate_matrix.js index cd5f20b4..4dfde0bf 100644 --- a/2D Arrays (Matrix)/rotate_matrix.js +++ b/2D Arrays (Matrix)/rotate_matrix.js @@ -20,3 +20,26 @@ function rotateClockwise(matrix) { // Return the rotated matrix return rotated; } + +function rotateAntiClockwise(matrix) { + // Get the number of rows and columns in the matrix + const rows = matrix.length; + const cols = matrix[0].length; + + // Create a new matrix to store the rotated matrix + const rotated = []; + + // Iterate over the columns in reverse order and create a new row in the rotated matrix + for (let j = 0; j < cols; j++) { + const newRow = []; + // Iterate over each row in the matrix in reverse order and add the corresponding element to the new row + for (let i = rows - 1; i >= 0; i--) { + newRow.push(matrix[i][j]); + } + // Add the new row to the rotated matrix + rotated.push(newRow); + } + + // Return the rotated matrix + return rotated; +} From 6f87cc3d39a8f015b901314ff4614c0333b110fd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:50:20 +0530 Subject: [PATCH 0631/1894] add description --- 2D Arrays (Matrix)/rotate_matrix.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/2D Arrays (Matrix)/rotate_matrix.js b/2D Arrays (Matrix)/rotate_matrix.js index 4dfde0bf..7994d733 100644 --- a/2D Arrays (Matrix)/rotate_matrix.js +++ b/2D Arrays (Matrix)/rotate_matrix.js @@ -1,3 +1,15 @@ +// Rotate clockwise and anti-clockwise +/* + Here, we first get the number of rows and columns in the matrix. Then, for rotating the matrix clockwise, + we iterate over the columns in reverse order and create a new row in the rotated matrix by iterating + over each row in the original matrix and adding the corresponding element to the new row. + Finally, we add the new row to the rotated matrix. + + For rotating the matrix anti-clockwise, we again iterate over the columns but this time in the + forward order and create a new row in the rotated matrix by iterating over each row in the original + matrix in reverse order and adding the corresponding element to the new row. Finally, we add the + new row to the rotated matrix. +*/ function rotateClockwise(matrix) { // Get the number of rows and columns in the matrix const rows = matrix.length; From 9add998036e93bc48cfb974d8b18c157a57f93bc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:53:02 +0530 Subject: [PATCH 0632/1894] add matrix rotate clockwise and anticlockwise --- 2D Arrays (Matrix)/rotate_matrix.cpp | 60 ++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2D Arrays (Matrix)/rotate_matrix.cpp diff --git a/2D Arrays (Matrix)/rotate_matrix.cpp b/2D Arrays (Matrix)/rotate_matrix.cpp new file mode 100644 index 00000000..49eebf7b --- /dev/null +++ b/2D Arrays (Matrix)/rotate_matrix.cpp @@ -0,0 +1,60 @@ +#include +#include + +using namespace std; + +// Function to rotate the image by 90 degrees clockwise +void rotateClockwise(vector>& image) { + int n = image.size(); + for (int i = 0; i < n / 2; i++) { + for (int j = i; j < n - i - 1; j++) { + int temp = image[i][j]; + image[i][j] = image[n - j - 1][i]; + image[n - j - 1][i] = image[n - i - 1][n - j - 1]; + image[n - i - 1][n - j - 1] = image[j][n - i - 1]; + image[j][n - i - 1] = temp; + } + } +} + +// Function to rotate the image by 90 degrees counterclockwise +void rotateCounterclockwise(vector>& image) { + int n = image.size(); + for (int i = 0; i < n / 2; i++) { + for (int j = i; j < n - i - 1; j++) { + int temp = image[i][j]; + image[i][j] = image[j][n - i - 1]; + image[j][n - i - 1] = image[n - i - 1][n - j - 1]; + image[n - i - 1][n - j - 1] = image[n - j - 1][i]; + image[n - j - 1][i] = temp; + } + } +} + +// Function to print the image +void printImage(vector>& image) { + for (auto row : image) { + for (auto pixel : row) { + cout << pixel << " "; + } + cout << endl; + } +} + +// Driver code +int main() { + vector> image = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + + cout << "Original Image:" << endl; + printImage(image); + + rotateClockwise(image); + cout << "Image rotated by 90 degrees clockwise:" << endl; + printImage(image); + + rotateCounterclockwise(image); + cout << "Image rotated by 90 degrees counterclockwise:" << endl; + printImage(image); + + return 0; +} From fb9466a8f5404a6ec302ca243ca4df1d419720b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:54:39 +0530 Subject: [PATCH 0633/1894] add description --- 2D Arrays (Matrix)/rotate_matrix.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/2D Arrays (Matrix)/rotate_matrix.cpp b/2D Arrays (Matrix)/rotate_matrix.cpp index 49eebf7b..cde9ccf4 100644 --- a/2D Arrays (Matrix)/rotate_matrix.cpp +++ b/2D Arrays (Matrix)/rotate_matrix.cpp @@ -1,3 +1,15 @@ +// Rotate clockwise and anti-clockwise +/* + Here, we first get the number of rows and columns in the matrix. Then, for rotating the matrix clockwise, + we iterate over the columns in reverse order and create a new row in the rotated matrix by iterating + over each row in the original matrix and adding the corresponding element to the new row. + Finally, we add the new row to the rotated matrix. + + For rotating the matrix anti-clockwise, we again iterate over the columns but this time in the + forward order and create a new row in the rotated matrix by iterating over each row in the original + matrix in reverse order and adding the corresponding element to the new row. Finally, we add the + new row to the rotated matrix. +*/ #include #include From 8304389c6ebb05a908442d146cde8ef59dc0bda4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:54:54 +0530 Subject: [PATCH 0634/1894] add matrix rotate clockwise and anticlockwise in go --- 2D Arrays (Matrix)/rotate_matrix.go | 50 +++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 2D Arrays (Matrix)/rotate_matrix.go diff --git a/2D Arrays (Matrix)/rotate_matrix.go b/2D Arrays (Matrix)/rotate_matrix.go new file mode 100644 index 00000000..cf5055bf --- /dev/null +++ b/2D Arrays (Matrix)/rotate_matrix.go @@ -0,0 +1,50 @@ +package main + +import "fmt" + +func rotateClockwise(image [][]int) [][]int { + n := len(image) + rotated := make([][]int, n) + for i := 0; i < n; i++ { + rotated[i] = make([]int, n) + for j := 0; j < n; j++ { + rotated[i][j] = image[n-j-1][i] + } + } + return rotated +} + +func rotateCounterClockwise(image [][]int) [][]int { + n := len(image) + rotated := make([][]int, n) + for i := 0; i < n; i++ { + rotated[i] = make([]int, n) + for j := 0; j < n; j++ { + rotated[i][j] = image[j][n-i-1] + } + } + return rotated +} + +func main() { + // example image + image := [][]int{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + } + + // rotate clockwise + rotatedClockwise := rotateClockwise(image) + fmt.Println("Rotated Clockwise:") + for _, row := range rotatedClockwise { + fmt.Println(row) + } + + // rotate counterclockwise + rotatedCounterClockwise := rotateCounterClockwise(image) + fmt.Println("Rotated Counterclockwise:") + for _, row := range rotatedCounterClockwise { + fmt.Println(row) + } +} From 535585c0b20db07bc7d2080f40e078e3110cb2aa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:56:39 +0530 Subject: [PATCH 0635/1894] update description --- 2D Arrays (Matrix)/rotate_matrix.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/2D Arrays (Matrix)/rotate_matrix.cpp b/2D Arrays (Matrix)/rotate_matrix.cpp index cde9ccf4..47704d9b 100644 --- a/2D Arrays (Matrix)/rotate_matrix.cpp +++ b/2D Arrays (Matrix)/rotate_matrix.cpp @@ -1,14 +1,14 @@ // Rotate clockwise and anti-clockwise /* - Here, we first get the number of rows and columns in the matrix. Then, for rotating the matrix clockwise, - we iterate over the columns in reverse order and create a new row in the rotated matrix by iterating - over each row in the original matrix and adding the corresponding element to the new row. - Finally, we add the new row to the rotated matrix. +This implementation first defines two functions, rotateClockwise and rotateCounterclockwise, +to rotate the image by 90 degrees clockwise and counterclockwise, respectively. +Each function takes a 2D vector image as input and modifies it in place. - For rotating the matrix anti-clockwise, we again iterate over the columns but this time in the - forward order and create a new row in the rotated matrix by iterating over each row in the original - matrix in reverse order and adding the corresponding element to the new row. Finally, we add the - new row to the rotated matrix. +The printImage function is used to print the image for demonstration purposes. + +Finally, the main function initializes an example image, prints it, rotates +it by 90 degrees clockwise, prints it again, rotates it by 90 degrees counterclockwise, +and prints it one last time to verify that the rotations worked as expected. */ #include #include From d6ec9555fe44d8b9ab555cabeb7bfde66038b0db Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 17:56:47 +0530 Subject: [PATCH 0636/1894] add description --- 2D Arrays (Matrix)/rotate_matrix.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/2D Arrays (Matrix)/rotate_matrix.go b/2D Arrays (Matrix)/rotate_matrix.go index cf5055bf..3a3abfe6 100644 --- a/2D Arrays (Matrix)/rotate_matrix.go +++ b/2D Arrays (Matrix)/rotate_matrix.go @@ -1,3 +1,15 @@ +/* + The rotateClockwise function takes an image array as input and returns the image rotated by 90 degrees clockwise. + It creates a new rotated array with the same dimensions as the original image, and then iterates over + each element of the image, assigning it to a new position in the rotated array. + + The rotateCounterClockwise function works similarly, but it rotates the image counterclockwise instead. + The n-j-1 and n-i-1 indices are used to swap the rows and columns, respectively. + + In the main function, we create an example image, and then call the rotateClockwise and + rotateCounterClockwise functions to rotate the image by 90 degrees in each direction. + Finally, we print the rotated images. +*/ package main import "fmt" From d7fcb401a2678c4185bad9442db1bf49b3e93599 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 18:00:31 +0530 Subject: [PATCH 0637/1894] add heading --- 2D Arrays (Matrix)/rotate_matrix.go | 1 + 1 file changed, 1 insertion(+) diff --git a/2D Arrays (Matrix)/rotate_matrix.go b/2D Arrays (Matrix)/rotate_matrix.go index 3a3abfe6..5acb8558 100644 --- a/2D Arrays (Matrix)/rotate_matrix.go +++ b/2D Arrays (Matrix)/rotate_matrix.go @@ -1,3 +1,4 @@ +// Rotate clockwise and anti-clockwise /* The rotateClockwise function takes an image array as input and returns the image rotated by 90 degrees clockwise. It creates a new rotated array with the same dimensions as the original image, and then iterates over From e6fb274bcb3dfdc3c1c91071a052ea51b89f3d14 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 18:00:44 +0530 Subject: [PATCH 0638/1894] add matrix clockwise and anticlockwise in java --- 2D Arrays (Matrix)/rotate_matrix.java | 70 +++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 2D Arrays (Matrix)/rotate_matrix.java diff --git a/2D Arrays (Matrix)/rotate_matrix.java b/2D Arrays (Matrix)/rotate_matrix.java new file mode 100644 index 00000000..89676238 --- /dev/null +++ b/2D Arrays (Matrix)/rotate_matrix.java @@ -0,0 +1,70 @@ +// Rotate clockwise and anti-clockwise +/* + This program takes a 2D array (matrix) and performs two types of 90-degree rotations: clockwise and + anti-clockwise. The rotateClockwise method takes a matrix and returns a new matrix with its + elements rotated 90 degrees clockwise. The rotateAntiClockwise method takes a matrix and + returns a new matrix with its elements rotated 90 degrees anti-clockwise. + + The printMatrix method is used to print the matrix elements in a readable format. + Finally, the main method initializes a test matrix and performs the two rotations on it. +*/ +public class RotateMatrix { + + // Rotate matrix by 90 degrees clockwise + public static int[][] rotateClockwise(int[][] matrix) { + int n = matrix.length; + int[][] result = new int[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + result[i][j] = matrix[n - j - 1][i]; + } + } + + return result; + } + + // Rotate matrix by 90 degrees anti-clockwise + public static int[][] rotateAntiClockwise(int[][] matrix) { + int n = matrix.length; + int[][] result = new int[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + result[i][j] = matrix[j][n - i - 1]; + } + } + + return result; + } + + // Print matrix + public static void printMatrix(int[][] matrix) { + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[i].length; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } + + // Test program + public static void main(String[] args) { + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + + System.out.println("Original Matrix:"); + printMatrix(matrix); + + int[][] rotatedClockwise = rotateClockwise(matrix); + System.out.println("Matrix after 90 degree clockwise rotation:"); + printMatrix(rotatedClockwise); + + int[][] rotatedAntiClockwise = rotateAntiClockwise(matrix); + System.out.println("Matrix after 90 degree anti-clockwise rotation:"); + printMatrix(rotatedAntiClockwise); + } +} From 160051d4bbf6b370068797ad6c6d3c09bd6e105b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 18:03:14 +0530 Subject: [PATCH 0639/1894] add description --- 2D Arrays (Matrix)/rotate_matrix.py | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 2D Arrays (Matrix)/rotate_matrix.py diff --git a/2D Arrays (Matrix)/rotate_matrix.py b/2D Arrays (Matrix)/rotate_matrix.py new file mode 100644 index 00000000..0c8b07fa --- /dev/null +++ b/2D Arrays (Matrix)/rotate_matrix.py @@ -0,0 +1,46 @@ +# Rotate clockwise and anti-clockwise +''' + The rotate_clockwise() function takes a matrix as input and returns the matrix rotated by 90 degrees + clockwise. It does this by first transposing the matrix (swapping the elements across the diagonal), + and then reversing each row of the transposed matrix. + + The rotate_counterclockwise() function takes a matrix as input and returns the matrix rotated by 90 + degrees counterclockwise. It also transposes the matrix first, and then reverses each column of + the transposed matrix. + + Both functions use two nested loops to iterate through the matrix and perform the required operations. + The n variable represents the size of the matrix, and is used to control the range of the loops. +''' +def rotate_clockwise(matrix): + """ + Function to rotate the given matrix by 90 degrees clockwise + """ + n = len(matrix) + # Transpose the matrix + for i in range(n): + for j in range(i, n): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] + + # Reverse each row to get the final rotated matrix + for i in range(n): + matrix[i] = matrix[i][::-1] + + return matrix + + +def rotate_counterclockwise(matrix): + """ + Function to rotate the given matrix by 90 degrees counterclockwise + """ + n = len(matrix) + # Transpose the matrix + for i in range(n): + for j in range(i, n): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] + + # Reverse each column to get the final rotated matrix + for i in range(n//2): + for j in range(n): + matrix[j][i], matrix[j][n-i-1] = matrix[j][n-i-1], matrix[j][i] + + return matrix From 192fd223fb7223f6cb7081dde38d0d496a746528 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Apr 2023 18:04:43 +0530 Subject: [PATCH 0640/1894] remove duplicate program --- .../matrix_rotate_90_anti_clockwise.cpp | 36 ------------------- .../matrix_rotate_90_clockwise.cpp | 36 ------------------- 2 files changed, 72 deletions(-) delete mode 100644 2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp delete mode 100644 2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp diff --git a/2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp b/2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp deleted file mode 100644 index 6a3b1af0..00000000 --- a/2D Arrays (Matrix)/matrix_rotate_90_anti_clockwise.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -using namespace std; -int main(){ - int Mat[10][10], R, C, value = 1; - cin >> R >> C; - // creating matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - Mat[i][j] = value++; - } - } - // Transposing matrix - for(int i = 0; i < R; i++){ - for(int j = i + 1; j < C; j++){ - swap(Mat[i][j], Mat[j][i]); - } - } - //Rotate matrix 90 degrees anti clockwise - for(int i = 0; i < R; i++){ - int start = 0; - int end = C-1; - while(start < end){ - swap(Mat[start][i], Mat[end][i]); - start++; - end--; - } - } - // Display matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - return 0; -} \ No newline at end of file diff --git a/2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp b/2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp deleted file mode 100644 index cb300cbd..00000000 --- a/2D Arrays (Matrix)/matrix_rotate_90_clockwise.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -using namespace std; -int main(){ - int Mat[10][10], R, C, value = 1; - cin >> R >> C; - // creating matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - Mat[i][j] = value++; - } - } - // Transposing matrix - for(int i = 0; i < R; i++){ - for(int j = i + 1; j < C; j++){ - swap(Mat[i][j], Mat[j][i]); - } - } - //Rotate matrix 90 degrees clockwise - for(int i = 0; i < R; i++){ - int start = 0; - int end = C-1; - while(start < end){ - swap(Mat[i][start], Mat[i][end]); - start++; - end--; - } - } - // Display matrix - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - return 0; -} \ No newline at end of file From 99b8d6321ec896a69a0a951cb78616e246d23240 Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Sun, 9 Apr 2023 22:56:26 +0530 Subject: [PATCH 0641/1894] Linked List in js --- Linked List/linked_list.js | 226 +++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 Linked List/linked_list.js diff --git a/Linked List/linked_list.js b/Linked List/linked_list.js new file mode 100644 index 00000000..4c771140 --- /dev/null +++ b/Linked List/linked_list.js @@ -0,0 +1,226 @@ +/* + insertAtTail (val) + insertAtHead (val) + deleteAtTail () + deleteAtHead () + getLength () + print () + getAtIdx (idx) + putAtIdx (val, idx) + deleteAtIdx (idx) + search (val) + toArray () + reverse () +*/ + +class Node { + constructor(val) { + this.val = val + this.next = null + } +} + +class LinkedList { + constructor() { + this.head = null + this.tail = null + this.length = 0 + } + + insertAtTail(val) { + const node = new Node(val) + + if (!this.head) { + this.head = node + this.tail = node + this.length++ + } else { + this.tail.next = node + this.tail = node + this.length++ + } + } + + insertAtHead(val) { + const node = new Node(val) + + if (!this.head) { + this.head = node + this.tail = node + this.length++ + } else { + node.next = this.head + this.head = node + this.length++ + } + } + + print() { + if (this.length === 0) console.log ("Empty Linked List!") + else { + let curr = this.head + let str = '' + + while (curr) { + str += curr.val + ' -> ' + curr = curr.next + } + + console.log(str + 'null') + } + } + + deleteAtTail() { + if (!this.head) console.log("Empty Linked List!") + + else { + let curr = this.head + let prev = this.head + + while (curr.next) { + prev = curr + curr = curr.next + } + + prev.next = null + this.tail = prev + this.length-- + } + } + + deleteAtHead() { + if (!this.head) console.log("Empty Linked List!") + + else { + let curr = this.head + this.head = curr.next + this.length-- + } + } + + + getLength() { + return this.length + } + + getAtIdx (idx) { + if (idx >= this.length || idx < 0) throw new Error ("Index out of bounds") + + else { + let currIdx = 0 + let curr = this.head + + while (currIdx < idx) { + currIdx++ + curr = curr.next + } + + return curr.val + } + } + + putAtIdx (val, idx) { + if (idx > this.length || idx < 0) throw new Error ("Index out of bounds") + + const node = new Node (val) + + if (!this.head) { + this.head = node + this.length++ + return + } + + let currIdx = 0 + let curr = this.head + let prev = this.head + + while (currIdx < idx) { + currIdx++ + prev = curr + curr = curr.next + } + + prev.next = node + node.next = curr + this.length++ + } + + deleteAtIdx (idx) { + if (idx >= this.length || idx < 0) throw new Error ("Index out of bounds") + + else { + let currIdx = 0 + let curr = this.head + let prev = this.head + + while (currIdx < idx) { + currIdx++ + prev = curr + curr = curr.next + } + + prev.next = curr.next + this.length-- + } + } + + search (val) { + if (!this.head) return "Empty Linked List!" + if (!this.head.next && this.head.val !== val) return null + if (!this.head.next && this.head.val === val) return 0 + + let currIdx = 0 + let curr = this.head + + while (curr) { + if (curr.val === val) return currIdx + currIdx++ + curr = curr.next + } + + return null + } + + toArray () { + const arr = [] + if (!this.head) return null + + let curr = this.head + + while (curr) { + arr.push (curr.val) + curr = curr.next + } + + return arr + } + + reverse () { + if (!this.head) throw new Error ("Empty Linked List") + if (!this.head.next) return + + let prev = null + let curr = this.head + let next = curr.next + + while (curr) { + next = curr.next + curr.next = prev + prev = curr + curr = next + } + + this.head = prev + } +} + +// SAMPLE USECASE + +const list = new LinkedList() +list.insertAtTail (10) +list.insertAtTail (20) +list.insertAtTail (30) +list.insertAtTail (40) +list.insertAtTail (50) +list.reverse () +list.print () \ No newline at end of file From fbf6dad28c12e739f0dfc3989cbec0681c3939ef Mon Sep 17 00:00:00 2001 From: Nirzar Bhatt Date: Sun, 9 Apr 2023 23:02:59 +0530 Subject: [PATCH 0642/1894] Doubly linked list in js --- Linked List/doubly_linked_list.js | 190 ++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 Linked List/doubly_linked_list.js diff --git a/Linked List/doubly_linked_list.js b/Linked List/doubly_linked_list.js new file mode 100644 index 00000000..f3dea4c7 --- /dev/null +++ b/Linked List/doubly_linked_list.js @@ -0,0 +1,190 @@ +class Node { + constructor(val) { + this.val = val + this.prev = null + this.next = null + } +} + +class DoublyLinkedList { + constructor() { + this.head = null + this.tail = null + this.length = 0 + } + + insertAtTail(val) { + const node = new Node(val) + + if (!this.head) { + this.head = node + this.tail = node + this.length++ + } else { + node.prev = this.tail + this.tail.next = node + this.tail = node + this.length++ + } + } + + insertAtHead(val) { + const node = new Node(val) + + if (!this.head) { + this.head = node + this.tail = node + this.length++ + } else { + node.next = this.head + this.head.prev = node + this.head = node + this.length++ + } + } + + deleteAtTail() { + if (!this.head) throw new Error("Empty Linked List!") + + if (this.length === 1) { + this.head = null + this.tail = null + this.length-- + } else { + this.tail = this.tail.prev + this.tail.next = null + this.length-- + } + } + + deleteAtHead() { + if (!this.head) throw new Error("Empty Linked List!") + + if (this.length === 1) { + this.head = null + this.tail = null + this.length-- + } else { + this.head = this.head.next + this.head.prev = null + this.length-- + } + } + + print() { + if (!this.head) console.log("Empty Linked List!") + + else { + let curr = this.head + let str = "null <- " + while (curr) { + str += curr.val + if (curr.next) { + str += " <-> " + } else { + str += " -> null" + } + curr = curr.next + } + console.log(str) + } + } + + getLength() { + return this.length + } + + getAtIdx(idx) { + if (idx >= this.length || idx < 0) throw new Error("Index out of bounds!") + + else { + let currIdx = 0 + let curr = this.head + + while (currIdx < idx) { + curr = curr.next + currIdx++ + } + + return curr.val + } + } + + putAtIdx(val, idx) { + if (idx > this.length || idx < 0) throw new Error("Index out of bounds!") + + const node = new Node(val) + + if (idx === 0) { + this.head.prev = node + node.next = this.head + this.head = node + } else { + let currIdx = 0 + let curr = this.head + + while (currIdx < idx) { + curr = curr.next + currIdx++ + } + + node.next = curr + node.prev = curr.prev + curr.prev.next = node + } + + this.length++ + } + + deleteAtIdx(idx) { + if (idx >= this.length || idx < 0) throw new Error("Index out of bounds!") + + let currIdx = 0 + let curr = this.head + + while (currIdx < idx) { + curr = curr.next + currIdx++ + } + + curr.prev.next = curr.next + curr.next.prev = curr.prev + this.length-- + } + + search(val) { + let curr = this.head + let currIdx = 0 + + while (curr) { + if (curr.val === val) return currIdx + + curr = curr.next + currIdx++ + } + + return "Value not found" + } + + toArray() { + let arr = [] + + let curr = this.head + + while (curr) { + arr.push(curr.val) + curr = curr.next + } + + return arr + } +} + +// SAMPLE USECASE +const list = new DoublyLinkedList () +list.insertAtHead (10) +list.insertAtTail (20) +list.insertAtHead (30) +list.insertAtTail (40) +list.putAtIdx (100, 2) +list.print () \ No newline at end of file From af4ee2682feaaccb9d57a82fd31607ee0a4d3ec1 Mon Sep 17 00:00:00 2001 From: deanrtaylor1 Date: Mon, 10 Apr 2023 13:24:30 +0700 Subject: [PATCH 0643/1894] added singly linked list in go (requested in issue #980) --- Linked List/singly_linked_list.go | 297 ++++++++++++++++++++++++++++++ 1 file changed, 297 insertions(+) create mode 100644 Linked List/singly_linked_list.go diff --git a/Linked List/singly_linked_list.go b/Linked List/singly_linked_list.go new file mode 100644 index 00000000..13f87e40 --- /dev/null +++ b/Linked List/singly_linked_list.go @@ -0,0 +1,297 @@ +package main + +import ( + "errors" + "fmt" +) + +/* + insertAtTail (val) + insertAtHead (val) + deleteAtTail () + deleteAtHead () + getLength () + print () + getAtIdx (idx) + replaceAtIdx (val, idx) + deleteAtIdx (idx) + search (val) + toArray () + reverse () +*/ + +// struct for a node type, we use interface{} to allow for any type of value, you could replace this +// with another value if you want to have more control over the type of value that can be inserted +type node struct { + val interface{} + next *node +} + +// struct for the linked list type +type linkedList struct { + head *node + tail *node + length int +} + +// constructor for a node type +func newNode(val interface{}) *node { + return &node{val: val, next: nil} +} + +// constructor for a linked list type +func newLinkedList() *linkedList { + return &linkedList{head: nil, tail: nil, length: 0} +} + +// function for linked lists to check if the linked list is empty +func (l *linkedList) IsEmpty() bool { + return l.head == nil +} + +// function for linked lists to insert a value at the tail of the linked list +func (l *linkedList) insertAtTail(val interface{}) { + node := newNode(val) + if l.IsEmpty() { + l.head = node + l.tail = l.head + l.length += 1 + return + } else { + node := node + l.tail.next = node + l.tail = node + l.length += 1 + } +} + +// function for linked lists to insert a value at the head of the linked list + +func (l *linkedList) insertAtHead(val interface{}) { + // create a new node + node := newNode(val) + // check if the list is empty + if l.IsEmpty() { + // if it is, set the head and tail to the new node and increase the length + l.head = node + l.tail = l.head + l.length += 1 + return + } else { + // if it is not, set the new node's next to the current head and set the head to the new node + node.next = l.head + l.head = node + l.length += 1 + } + +} + +func (l *linkedList) print() { + c := l.head + for c != nil { + fmt.Printf("%v", c.val) + if c.next == nil { + fmt.Println() + break + } + c = c.next + + fmt.Print(" -> ") + } + fmt.Printf("Current Length: %v\n", l.length) + +} + +// function for linked lists to delete a node at the tail of the linked list +func (l *linkedList) deleteAtTail() { + if l.IsEmpty() { + fmt.Println("Empty List") + return + } + + if l.head.next == nil { + l.head = nil + l.tail = nil + l.length -= 1 + return + } + + c := l.head + for { + if c.next.next == nil { + c.next = nil + l.tail = c + l.length -= 1 + return + } + c = c.next + } + +} + +// function for linked lists to delete a node at the head of the linked list +func (l *linkedList) deleteAtHead() { + if l.IsEmpty() { + fmt.Println("Empty List") + return + } + + if l.head.next == nil { + l.head = nil + l.tail = nil + l.length -= 1 + return + } + + l.head = l.head.next + l.length -= 1 +} + +// function for linked lists to get the length of the linked list +func (l *linkedList) getLength() int { + return l.length +} + +// function of a linked list to get the value at a given index +func (l *linkedList) getAtIdx(idx int) (interface{}, error) { + if idx >= l.length { + return nil, errors.New("index out of range") + } + + c := l.head + for i := 0; i < idx; i++ { + c = c.next + } + + return c.val, nil +} + +// function of a linked list to replace the value at a given index +// index starts at 0 +func (l *linkedList) replaceAtIdx(val interface{}, idx int) error { + if idx >= l.length { + return errors.New("index out of range") + } + + c := l.head + for i := 0; i < idx; i++ { + c = c.next + } + + c.val = val + return nil +} + +// function of a linked list to delete the value at a given index +func (l *linkedList) deleteAtIdx(idx int) error { + if idx >= l.length { + return errors.New("index out of range") + } + + c := l.head + for i := 0; i < idx-1; i++ { + c = c.next + } + + c.next = c.next.next + l.length -= 1 + return nil +} + +// function to find the index of a given value +// returns -1 and an error if the value is not found +func (l *linkedList) search(val interface{}) (int, error) { + c := l.head + for i := 0; i < l.length; i++ { + if c.val == val { + return i, nil + } + c = c.next + } + + return -1, errors.New("value not found") +} + +// function to convert a linked list to an array +func (l *linkedList) toArray() []interface{} { + arr := make([]interface{}, l.length) + c := l.head + for i := 0; i < l.length; i++ { + arr[i] = c.val + c = c.next + } + + return arr +} + +// function to reverse the linked list +// This is a recursive implementation to show something different +func (l *linkedList) reverse() error { + if l.IsEmpty() { + return errors.New("Empty List") + } + l.head = reverseListRecursive(l.head) + return nil +} + +// recursive function to reverse a linked list recursively +func reverseListRecursive(head *node) *node { + if head == nil || head.next == nil { + return head + } + + rest := reverseListRecursive(head.next) + head.next.next = head + head.next = nil + + return rest +} + +// example of a linked list +func main() { + list := newLinkedList() + + list.insertAtHead(1) + list.insertAtTail(2) + list.insertAtTail(3) + list.insertAtTail(4) + list.insertAtTail(5) + list.insertAtTail(6) + list.insertAtTail(7) + list.insertAtTail(8) + list.insertAtTail(9) + list.insertAtTail(10) + list.insertAtTail(11) + list.print() + + list.deleteAtTail() + list.print() + + err := list.replaceAtIdx(9000, 4) + if err != nil { + fmt.Println(err) + } + list.print() + + i, err := list.search(9000) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(i) + } + + err = list.reverse() + if err != nil { + fmt.Println(err) + } + + list.print() + idx, err := list.search(3) + if err != nil { + fmt.Println(err) + } else { + fmt.Println(idx) + } + fmt.Println(list.toArray()) + +} From 65ee1312430ea3a1526511de0160d6825463b9a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:00:58 +0530 Subject: [PATCH 0644/1894] add quick sort in go --- sorting/quick_sort.go | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sorting/quick_sort.go diff --git a/sorting/quick_sort.go b/sorting/quick_sort.go new file mode 100644 index 00000000..ac95dde6 --- /dev/null +++ b/sorting/quick_sort.go @@ -0,0 +1,48 @@ +package main + +import "fmt" + +// Quicksort function to sort an array of integers in ascending order +func quicksort(arr []int, left, right int) { + // Choose pivot element (middle element in this case) + pivot := arr[(left+right)/2] + + // Initialize two pointers to left and right ends of subarray + i := left + j := right + + // Partition array into two subarrays: elements less than pivot + // go to the left subarray and elements greater than pivot go to + // the right subarray. Repeat until subarrays have length 0 or 1. + for i <= j { + // Find first element in left subarray greater than pivot + for arr[i] < pivot { + i++ + } + // Find first element in right subarray less than pivot + for arr[j] > pivot { + j-- + } + // Swap elements at i and j if they are in the wrong subarray + if i <= j { + arr[i], arr[j] = arr[j], arr[i] + i++ + j-- + } + } + + // Recursively sort left and right subarrays + if left < j { + quicksort(arr, left, j) + } + if i < right { + quicksort(arr, i, right) + } +} + +func main() { + // Example usage + arr := []int{3, 7, 1, 8, 4, 2, 9, 5, 6} + quicksort(arr, 0, len(arr)-1) + fmt.Println(arr) // Output: [1 2 3 4 5 6 7 8 9] +} From e4d69e632cca9f9cef2b4723e5a7392a2fef3148 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:03:11 +0530 Subject: [PATCH 0645/1894] add description --- sorting/quick_sort.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/sorting/quick_sort.go b/sorting/quick_sort.go index ac95dde6..6cdddec1 100644 --- a/sorting/quick_sort.go +++ b/sorting/quick_sort.go @@ -1,3 +1,22 @@ +// Quicksort +/* + In this implementation, we use the standard algorithm for quicksort: + + 1. Choose a pivot element (we choose the middle element in this case) + 2. Partition the array into two subarrays: elements less than the pivot go to the left subarray, + and elements greater than the pivot go to the right subarray + 3. Recursively sort the left and right subarrays using the same algorithm + + The quicksort function takes three arguments: the array to be sorted, the left index of the subarray, + and the right index of the subarray. We start by choosing the pivot element (in this case, the middle element), + initializing two pointers to the left and right ends of the subarray, and then partitioning the array into two + subarrays by moving elements less than the pivot to the left subarray and elements greater than the pivot to + the right subarray. We repeat this process until the subarrays have length 0 or 1. + + Once the subarrays are partitioned, we recursively sort the left and right subarrays using the quicksort function. + We use two conditional statements to check if the left or right subarray has length greater than 1 and call quicksort + on that subarray if it does. Finally, the sorted array is returned. +*/ package main import "fmt" From 9fdc7b6352878f43855647effcc9fb4b25ff38ac Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:04:30 +0530 Subject: [PATCH 0646/1894] add quicksort in python --- sorting/quick_sort.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 sorting/quick_sort.py diff --git a/sorting/quick_sort.py b/sorting/quick_sort.py new file mode 100644 index 00000000..fc022268 --- /dev/null +++ b/sorting/quick_sort.py @@ -0,0 +1,27 @@ +def quicksort(arr): + """ + Sorts an array using quicksort algorithm. + + Args: + arr: A list of comparable elements to be sorted. + + Returns: + The sorted list. + """ + # Base case: an empty or single-element list is already sorted. + if len(arr) < 2: + return arr + + # Choose a pivot element and partition the list around it. + pivot_index = len(arr) // 2 + pivot = arr[pivot_index] + left, right = [], [] + for i in range(len(arr)): + if i != pivot_index: + if arr[i] < pivot: + left.append(arr[i]) + else: + right.append(arr[i]) + + # Recursively sort the left and right partitions. + return quicksort(left) + [pivot] + quicksort(right) From 2ad7a62e966ac299f86a12b9c48280f2c779732f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:04:42 +0530 Subject: [PATCH 0647/1894] add description --- sorting/quick_sort.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sorting/quick_sort.py b/sorting/quick_sort.py index fc022268..38df5859 100644 --- a/sorting/quick_sort.py +++ b/sorting/quick_sort.py @@ -1,3 +1,15 @@ +''' + The basic idea of quicksort is to divide the input array into two partitions, with one partition + consisting of all elements smaller than a chosen pivot element, and the other partition consisting + of all elements larger than the pivot. This process is then recursively applied to the smaller + partitions until the entire array is sorted. + + In this implementation, we first handle the base case where the array has 0 or 1 element, + which is already sorted. Then, we choose the pivot element as the middle element of the array, + and partition the array into two subarrays based on whether each element is less than or greater + than the pivot. We then recursively sort the left and right subarrays using the same quicksort + function, and concatenate the results together along with the pivot element to get the final sorted array. +''' def quicksort(arr): """ Sorts an array using quicksort algorithm. From 5defed779d6f8f8bfa39dde06f7167255c5f54eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:05:37 +0530 Subject: [PATCH 0648/1894] add time and space complexity --- sorting/quick_sort.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sorting/quick_sort.py b/sorting/quick_sort.py index 38df5859..3d3e0221 100644 --- a/sorting/quick_sort.py +++ b/sorting/quick_sort.py @@ -10,6 +10,11 @@ than the pivot. We then recursively sort the left and right subarrays using the same quicksort function, and concatenate the results together along with the pivot element to get the final sorted array. ''' +''' Time and Space complexity + The time complexity of quicksort is O(n log n) on average and O(n^2) in the worst case. + The space complexity of quicksort is O(log n) on average and O(n) in the worst case. + The worst case occurs when the partition process divides the input array into two subarrays of unequal size. +''' def quicksort(arr): """ Sorts an array using quicksort algorithm. From 065c02d0b27ae828c3ee74ea576c4c9af5e50160 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:07:04 +0530 Subject: [PATCH 0649/1894] add quick sort in js --- sorting/quick_sort.js | 52 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 sorting/quick_sort.js diff --git a/sorting/quick_sort.js b/sorting/quick_sort.js new file mode 100644 index 00000000..8fe91596 --- /dev/null +++ b/sorting/quick_sort.js @@ -0,0 +1,52 @@ +/** + * This function implements the quicksort algorithm to sort an array in place. + * @param {Array} arr - The array to be sorted. + * @param {number} low - The lower index of the subarray to be sorted. + * @param {number} high - The higher index of the subarray to be sorted. + * @returns {void} + */ +function quickSort(arr, low, high) { + if (low < high) { + // Partition the array around the pivot element and get the index of the pivot. + const pivotIndex = partition(arr, low, high); + + // Recursively sort the subarrays on either side of the pivot. + quickSort(arr, low, pivotIndex - 1); + quickSort(arr, pivotIndex + 1, high); + } +} + +/** + * This function partitions an array around a pivot element and returns the index of the pivot. + * @param {Array} arr - The array to be partitioned. + * @param {number} low - The lower index of the subarray to be partitioned. + * @param {number} high - The higher index of the subarray to be partitioned. + * @returns {number} - The index of the pivot element. + */ +function partition(arr, low, high) { + // Choose the rightmost element as the pivot. + const pivot = arr[high]; + + // Initialize the index of the smaller element. + let i = low - 1; + + // Iterate over the subarray and partition it. + for (let j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + + // Swap arr[i] and arr[j]. + const temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + // Swap arr[i+1] and arr[high] (or the pivot). + const temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + + // Return the index of the pivot. + return i + 1; +} From 1573b198059f86361f486a0f92aed438891ad73a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:08:25 +0530 Subject: [PATCH 0650/1894] add description --- sorting/quick_sort.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sorting/quick_sort.js b/sorting/quick_sort.js index 8fe91596..98dd1ae0 100644 --- a/sorting/quick_sort.js +++ b/sorting/quick_sort.js @@ -1,3 +1,17 @@ +/* + The quickSort function implements the quicksort algorithm, which takes an array arr and the indices low and high + of the subarray to be sorted. If low is less than high, the array is partitioned around a pivot element using the + partition function, and the subarrays on either side of the pivot are recursively sorted using the quickSort function. + + The partition function takes an array arr and the indices low and high of the subarray to be partitioned. + It chooses the rightmost element as the pivot, initializes the index of the smaller element to low - 1, and + iterates over the subarray. If an element arr[j] is less than the pivot, it is swapped with the element arr[i+1] + and the index i is incremented. Finally, the pivot element is swapped with the element arr[i+1], + and the index i+1 is returned as the index of the pivot. + + The time complexity of quicksort is O(n log n) on average, and O(n^2) in the worst case. The space complexity + is O(log n) on average, and O(n) in the worst case. +*/ /** * This function implements the quicksort algorithm to sort an array in place. * @param {Array} arr - The array to be sorted. From 99d30d31acd23329248e2eb5f84e87d7334f1bc6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Apr 2023 13:10:21 +0530 Subject: [PATCH 0651/1894] update links in readme for quicksort --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de39209e..88b563e9 100644 --- a/README.md +++ b/README.md @@ -274,7 +274,7 @@ Even though languages have built-in sorting method, sorting is a great example o - Insertion Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/insertion_sort.py) - Selection Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/selection_sort.py) - Merge Sort [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.js) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/merge_sort.py) -- Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) +- Quick Sort [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.cpp) [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.js) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/sorting/quick_sort.java) # Binary Search From 8356d2f227e994b71e28dbeacf807dae96357eb6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:34:58 +0530 Subject: [PATCH 0652/1894] add bfs in go --- Graphs/graphs_bfs.go | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Graphs/graphs_bfs.go diff --git a/Graphs/graphs_bfs.go b/Graphs/graphs_bfs.go new file mode 100644 index 00000000..a4dc9026 --- /dev/null +++ b/Graphs/graphs_bfs.go @@ -0,0 +1,66 @@ +package main + +import "fmt" + +// Define a Graph struct to represent a graph +type Graph struct { + vertices int // Number of vertices in the graph + edges [][]int // Adjacency list to store edges + visited []bool // Track if a vertex is visited or not +} + +// Function to add an edge to the graph +func (g *Graph) addEdge(u, v int) { + // Add edge from u to v + g.edges[u] = append(g.edges[u], v) + // Add edge from v to u + g.edges[v] = append(g.edges[v], u) +} + +// Function to perform Breadth First Search +func BFS(g *Graph, start int) { + // Create a queue for BFS + queue := []int{} + // Mark the start node as visited and enqueue it + g.visited[start] = true + queue = append(queue, start) + + for len(queue) != 0 { + // Dequeue a vertex from the queue + currVertex := queue[0] + queue = queue[1:] + fmt.Printf("%d ", currVertex) + + // Get all adjacent vertices of the dequeued vertex currVertex + // If an adjacent vertex has not been visited, mark it as visited and enqueue it + for _, adjVertex := range g.edges[currVertex] { + if !g.visited[adjVertex] { + g.visited[adjVertex] = true + queue = append(queue, adjVertex) + } + } + } +} + +func main() { + // Create a new graph with 5 vertices + g := Graph{ + vertices: 5, + edges: make([][]int, 5), + // Initially all vertices are unvisited + visited: make([]bool, 5), + } + + // Add edges to the graph + g.addEdge(0, 1) + g.addEdge(0, 2) + g.addEdge(1, 2) + g.addEdge(2, 0) + g.addEdge(2, 3) + g.addEdge(3, 3) + + // Perform BFS starting from vertex 2 + fmt.Println("BFS starting from vertex 2:") + BFS(&g, 2) +} + From 30213e36e525e9987e1a83bcdc4aa59b6999d891 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:36:39 +0530 Subject: [PATCH 0653/1894] add description --- Graphs/graphs_bfs.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Graphs/graphs_bfs.go b/Graphs/graphs_bfs.go index a4dc9026..24ac1cf9 100644 --- a/Graphs/graphs_bfs.go +++ b/Graphs/graphs_bfs.go @@ -1,3 +1,18 @@ +/* + In this implementation, we define a Graph struct that represents a graph with a given number of vertices, + edges, and a visited array to keep track of visited vertices. We also define two methods - addEdge to + add an edge to the graph and BFS to perform the BFS algorithm. + + In the BFS method, we start by creating a queue to store the vertices to visit. We mark the start node + as visited and enqueue it. Then, while the queue is not empty, we dequeue a vertex from the queue, + print it out, and get all its adjacent vertices. For each adjacent vertex, if it hasn't been visited, + we mark it as visited and enqueue it. This continues until all reachable vertices have been visited. + + In the main function, we create a new Graph with 5 vertices and add edges to it. We then perform + BFS starting from vertex 2, and print out the visited vertices. The output of this program will be: + BFS starting from vertex 2: + 2 0 3 1 +*/ package main import "fmt" From 6f4ea048abe54759f8d588b2ac5e95b6f63c3123 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:37:25 +0530 Subject: [PATCH 0654/1894] add heading --- Graphs/graphs_bfs.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/graphs_bfs.go b/Graphs/graphs_bfs.go index 24ac1cf9..c8324810 100644 --- a/Graphs/graphs_bfs.go +++ b/Graphs/graphs_bfs.go @@ -1,3 +1,4 @@ +// Breadth First Search /* In this implementation, we define a Graph struct that represents a graph with a given number of vertices, edges, and a visited array to keep track of visited vertices. We also define two methods - addEdge to From 85cb84c13ba2662b42b67c5595e02caf32e585aa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:37:56 +0530 Subject: [PATCH 0655/1894] add time and space complexity --- Graphs/graphs_bfs.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/Graphs/graphs_bfs.go b/Graphs/graphs_bfs.go index c8324810..dd953c69 100644 --- a/Graphs/graphs_bfs.go +++ b/Graphs/graphs_bfs.go @@ -1,18 +1,23 @@ // Breadth First Search /* - In this implementation, we define a Graph struct that represents a graph with a given number of vertices, - edges, and a visited array to keep track of visited vertices. We also define two methods - addEdge to + In this implementation, we define a Graph struct that represents a graph with a given number of vertices, + edges, and a visited array to keep track of visited vertices. We also define two methods - addEdge to add an edge to the graph and BFS to perform the BFS algorithm. - In the BFS method, we start by creating a queue to store the vertices to visit. We mark the start node - as visited and enqueue it. Then, while the queue is not empty, we dequeue a vertex from the queue, - print it out, and get all its adjacent vertices. For each adjacent vertex, if it hasn't been visited, + In the BFS method, we start by creating a queue to store the vertices to visit. We mark the start node + as visited and enqueue it. Then, while the queue is not empty, we dequeue a vertex from the queue, + print it out, and get all its adjacent vertices. For each adjacent vertex, if it hasn't been visited, we mark it as visited and enqueue it. This continues until all reachable vertices have been visited. - In the main function, we create a new Graph with 5 vertices and add edges to it. We then perform + In the main function, we create a new Graph with 5 vertices and add edges to it. We then perform BFS starting from vertex 2, and print out the visited vertices. The output of this program will be: BFS starting from vertex 2: 2 0 3 1 + + The time complexity of BFS (Breadth-First Search) algorithm is O(V + E), where V is the number of + vertices and E is the number of edges in the graph. This is because BFS traverses all the vertices + and edges of the graph exactly once, and the time taken to visit each vertex and edge is constant. + Therefore, the time complexity of BFS is proportional to the size of the graph. */ package main From 7801705e9f29b5714501c2100d92b428cc6f6363 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:43:44 +0530 Subject: [PATCH 0656/1894] add dfs in go --- Graphs/graphs_dfs.go | 69 +++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index 84a25273..8739535b 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -1,43 +1,46 @@ -/* - DFS on a graph - Sample Input - A - / | \ - B C D - / \ / \ - E F G H - / \ \ - I J K - Output: ["A", "B", "E", "F", "I", "J", "C", "D", "G", "K", "H"] -*/ -/* - Start at the root Node and try simply calling the depthFirstSearch method on all of its children Nodes. - Then, call the depthFirstSearch method on all children Nodes of each child node. - Keep applying this logic until the entire graph has been traversed. - Don't forget to add the current Node's name to the input array at every call of depthFirstSearch. - - Time and Space complexity: O(v + e) time | O(v) space - where v is the number of vertices of the input graph and e is the number of edges of the input graph -*/ - package main import "fmt" +// Node represents a single node in the graph type Node struct { - Name string - Children []*Node + value int + visited bool + neighbors []*Node } -func (n *Node) DepthFirstSearch(array []string) []string { - return n.dfsHelper(array) -} +// DFS traverses the graph starting from the given node using Depth First Search +func DFS(node *Node) { + // Mark the current node as visited + node.visited = true -func (n *Node) dfsHelper(array []string) []string { - array = append(array, n.Name) - - for _, child := range n.Children { - fmt.Println(child.Name, " -->") - array = child.dfsHelper(array) + // Print the value of the current node + fmt.Printf("%d ", node.value) + + // Visit each of the neighboring nodes + for _, neighbor := range node.neighbors { + // If the neighbor has not been visited yet, visit it recursively + if !neighbor.visited { + DFS(neighbor) + } } - return array +} + +func main() { + // Create the nodes of the graph + node1 := &Node{value: 1} + node2 := &Node{value: 2} + node3 := &Node{value: 3} + node4 := &Node{value: 4} + node5 := &Node{value: 5} + + // Add the neighbors for each node + node1.neighbors = []*Node{node2, node3} + node2.neighbors = []*Node{node1, node4, node5} + node3.neighbors = []*Node{node1, node5} + node4.neighbors = []*Node{node2} + node5.neighbors = []*Node{node2, node3} + + // Start the DFS traversal from node1 + DFS(node1) } From b11a97f0c56eddc01578eb50ae3cc6cbb4bf7ee8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:45:17 +0530 Subject: [PATCH 0657/1894] add description --- Graphs/graphs_dfs.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index 8739535b..0dab1736 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -1,3 +1,10 @@ +/* + This implementation represents a graph as a collection of nodes, where each node has a value and a list of + neighboring nodes. The DFS algorithm is implemented recursively by starting from the given node, marking + it as visited, and printing its value. Then, the algorithm recursively visits each of the neighboring + nodes that have not been visited yet. The time complexity of DFS is O(V + E), where V is the number of + vertices (nodes) in the graph and E is the number of edges between the vertices. +*/ package main import "fmt" From 856ee59c410c33289c5c307c80324ba184a7c15f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:45:43 +0530 Subject: [PATCH 0658/1894] add sample io --- Graphs/graphs_dfs.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index 0dab1736..dd4ebc83 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -4,6 +4,15 @@ it as visited, and printing its value. Then, the algorithm recursively visits each of the neighboring nodes that have not been visited yet. The time complexity of DFS is O(V + E), where V is the number of vertices (nodes) in the graph and E is the number of edges between the vertices. + + Sample Input : graph = { + 'A': ['B', 'C'], + 'B': ['D', 'E'], + 'C': ['F'], + 'D': [], + 'E': ['F'], + 'F': [] +} */ package main From dd69d42cfdc39910b9a587433295174797961bf2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:47:00 +0530 Subject: [PATCH 0659/1894] add time and space complexity --- Graphs/graphs_dfs.go | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index dd4ebc83..70043dba 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -1,18 +1,25 @@ /* - This implementation represents a graph as a collection of nodes, where each node has a value and a list of - neighboring nodes. The DFS algorithm is implemented recursively by starting from the given node, marking - it as visited, and printing its value. Then, the algorithm recursively visits each of the neighboring - nodes that have not been visited yet. The time complexity of DFS is O(V + E), where V is the number of - vertices (nodes) in the graph and E is the number of edges between the vertices. - - Sample Input : graph = { - 'A': ['B', 'C'], - 'B': ['D', 'E'], - 'C': ['F'], - 'D': [], - 'E': ['F'], - 'F': [] -} + This implementation represents a graph as a collection of nodes, where each node has a value and a list of + neighboring nodes. The DFS algorithm is implemented recursively by starting from the given node, marking + it as visited, and printing its value. Then, the algorithm recursively visits each of the neighboring + nodes that have not been visited yet. The time complexity of DFS is O(V + E), where V is the number of + vertices (nodes) in the graph and E is the number of edges between the vertices. + + Sample Input : graph = { + 'A': ['B', 'C'], + 'B': ['D', 'E'], + 'C': ['F'], + 'D': [], + 'E': ['F'], + 'F': [] + } + Output : DFS Traversal: A B D E F C + Here, we have a graph represented as an adjacency list, with nodes A, B, C, D, E, and F and their respective neighbors. + The DFS traversal starts at node A and visits each node in the graph, outputting the final order in which the nodes were visited. + + The time complexity of the DFS algorithm is O(V + E), where V is the number of vertices (nodes) and E is the number of + edges in the graph. This is because the algorithm visits every vertex and every edge once. + */ package main From 60cd2965480d21da1109fd66a6dea5c6c939f2cd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:47:43 +0530 Subject: [PATCH 0660/1894] add space complexity --- Graphs/graphs_dfs.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Graphs/graphs_dfs.go b/Graphs/graphs_dfs.go index 70043dba..48e7adf0 100644 --- a/Graphs/graphs_dfs.go +++ b/Graphs/graphs_dfs.go @@ -20,6 +20,10 @@ The time complexity of the DFS algorithm is O(V + E), where V is the number of vertices (nodes) and E is the number of edges in the graph. This is because the algorithm visits every vertex and every edge once. + The space complexity of DFS depends on the maximum depth of the recursion stack. In the worst case, where the tree or + graph is completely unbalanced, the recursion stack can reach a depth of O(n), where n is the number of nodes in the graph. + Therefore, the space complexity of DFS is O(n). + */ package main From 58342dfb32cfba672f7f433050b50d91a7f0cafd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:48:06 +0530 Subject: [PATCH 0661/1894] add space complexity --- Graphs/graphs_bfs.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Graphs/graphs_bfs.go b/Graphs/graphs_bfs.go index dd953c69..a48bab3b 100644 --- a/Graphs/graphs_bfs.go +++ b/Graphs/graphs_bfs.go @@ -18,6 +18,10 @@ vertices and E is the number of edges in the graph. This is because BFS traverses all the vertices and edges of the graph exactly once, and the time taken to visit each vertex and edge is constant. Therefore, the time complexity of BFS is proportional to the size of the graph. + + The space complexity of BFS is O(|V|), where |V| is the number of vertices in the graph. + This is because in the worst case scenario, we would need to store all vertices in the queue + before we finish traversing the graph. */ package main From a199df029f054278f445a56e0623e300d9763b03 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:51:11 +0530 Subject: [PATCH 0662/1894] add count unique digits --- Math/count_unique_digits,go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Math/count_unique_digits,go diff --git a/Math/count_unique_digits,go b/Math/count_unique_digits,go new file mode 100644 index 00000000..d5f8bb97 --- /dev/null +++ b/Math/count_unique_digits,go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" +) + +func countNumbersWithUniqueDigits(n int) int { + // Base case: n = 0, only 1 possible number (0) + if n == 0 { + return 1 + } + + // For n > 0, initialize count to 10 (digits 0-9) + count := 10 + + // Calculate count for 2 to n digits + for i := 2; i <= n; i++ { + // For each number of digits, calculate the number of possible unique numbers + // First digit can be 1-9 (9 choices), subsequent digits can be any of the remaining 9-1 = 8 choices + // Multiply the choices together to get the total number of possible unique numbers + // Add this count to the total count + currCount := 9 + for j := 1; j < i; j++ { + currCount *= 10 - j + } + count += currCount + } + + return count +} + +func main() { + // Test case with n = 2 + fmt.Println(countNumbersWithUniqueDigits(2)) // Output: 91 +} From 14e4430b83c8ee1a30855acb97a219095f3d45b0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:51:54 +0530 Subject: [PATCH 0663/1894] add description --- Math/count_unique_digits,go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Math/count_unique_digits,go b/Math/count_unique_digits,go index d5f8bb97..e0c75765 100644 --- a/Math/count_unique_digits,go +++ b/Math/count_unique_digits,go @@ -1,7 +1,20 @@ +/* + This function takes an integer n as input and returns the count of all positive numbers with unique digits that have n + digits or less. The function first handles the base case where n = 0 (only 1 possible number, 0). For n > 0, + the function initializes the count to 10 (digits 0-9), and then iterates through each number of digits from 2 to n. + For each number of digits, the function calculates the number of possible unique numbers and adds it to the total count. + The number of possible unique numbers for i digits is calculated by first choosing the first digit (9 choices) and then + choosing each subsequent digit (8 choices for the second digit, 7 choices for the third digit, and so on). + The product of all these choices is the total number of possible unique numbers for i digits. + This calculation is repeated for each number of digits from 2 to n, and the total count is returned at the end. + + For example, if n = 2, the function should return 91. There are 10 possible numbers with 1 digit (0-9), and + 91 possible numbers with 2 digits (10-99) that have unique digits +*/ package main import ( - "fmt" + "fmt" ) func countNumbersWithUniqueDigits(n int) int { From 2f167d75e0e4969346ada44e4d9b8c087edbb23d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Apr 2023 22:52:12 +0530 Subject: [PATCH 0664/1894] add heading --- Math/count_unique_digits,go | 1 + 1 file changed, 1 insertion(+) diff --git a/Math/count_unique_digits,go b/Math/count_unique_digits,go index e0c75765..96d9bb60 100644 --- a/Math/count_unique_digits,go +++ b/Math/count_unique_digits,go @@ -1,3 +1,4 @@ +// Implementation of Count Numbers with Unique Digits /* This function takes an integer n as input and returns the count of all positive numbers with unique digits that have n digits or less. The function first handles the base case where n = 0 (only 1 possible number, 0). For n > 0, From 834b0bd7e9a324e27c716d3082a94e54c8bd915d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:09:24 +0530 Subject: [PATCH 0665/1894] add dll in go --- Linked List/double_linked_list.go | 63 +++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Linked List/double_linked_list.go diff --git a/Linked List/double_linked_list.go b/Linked List/double_linked_list.go new file mode 100644 index 00000000..22bf4d21 --- /dev/null +++ b/Linked List/double_linked_list.go @@ -0,0 +1,63 @@ +package main + +import "fmt" + +// Node represents a node in the doubly linked list +type Node struct { + data int + prev *Node + next *Node +} + +// LinkedList represents the doubly linked list +type LinkedList struct { + head *Node + tail *Node +} + +// AddNode adds a new node to the end of the doubly linked list +func (list *LinkedList) AddNode(data int) { + // Create a new node + newNode := &Node{data: data} + + // If the list is empty, set the new node as head and tail + if list.head == nil { + list.head = newNode + list.tail = newNode + return + } + + // Set the new node as the next node of the current tail + list.tail.next = newNode + + // Set the current tail as the previous node of the new node + newNode.prev = list.tail + + // Set the new node as the new tail + list.tail = newNode +} + +// PrintList prints the doubly linked list +func (list *LinkedList) PrintList() { + // Start from the head node + currNode := list.head + + // Traverse the list and print the data of each node + for currNode != nil { + fmt.Printf("%d ", currNode.data) + currNode = currNode.next + } +} + +func main() { + // Create a new doubly linked list + list := &LinkedList{} + + // Add nodes to the list + list.AddNode(1) + list.AddNode(2) + list.AddNode(3) + + // Print the list + list.PrintList() +} From 4058024a99bb31714d953191493fa0d9bbdf1029 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:10:36 +0530 Subject: [PATCH 0666/1894] add description --- Linked List/double_linked_list.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Linked List/double_linked_list.go b/Linked List/double_linked_list.go index 22bf4d21..a4092121 100644 --- a/Linked List/double_linked_list.go +++ b/Linked List/double_linked_list.go @@ -1,3 +1,16 @@ +// Implementation of a doubly linked list in Go +/* + In this implementation, we define a Node struct that contains the data as well as pointers to the previous and next nodes. + We also define a LinkedList struct that contains a pointer to the head and tail nodes. + + The AddNode method adds a new node to the end of the list. If the list is empty, the new node is set as both the head and tail. + Otherwise, the new node is added after the current tail, and the current tail is set as the previous node of the new node. + Finally, the new node is set as the new tail. + + The PrintList method traverses the list from the head node and prints the data of each node. + + In the main function, we create a new doubly linked list, add some nodes to it, and print the list. +*/ package main import "fmt" From d5aaa9911dcf482f32e3372ab81743df31ccbad9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:14:14 +0530 Subject: [PATCH 0667/1894] add reverse a linked list --- Linked List/reverse_linked_list.go | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Linked List/reverse_linked_list.go diff --git a/Linked List/reverse_linked_list.go b/Linked List/reverse_linked_list.go new file mode 100644 index 00000000..d990b3a6 --- /dev/null +++ b/Linked List/reverse_linked_list.go @@ -0,0 +1,61 @@ +package main + +import "fmt" + +// ListNode represents a node in the linked list +type ListNode struct { + Val int + Next *ListNode +} + +// ReverseListIteratively reverses a linked list iteratively +func ReverseListIteratively(head *ListNode) *ListNode { + var prev, curr *ListNode + curr = head + + for curr != nil { + nextTemp := curr.Next + curr.Next = prev + prev = curr + curr = nextTemp + } + + return prev +} + +// ReverseListRecursively reverses a linked list recursively +func ReverseListRecursively(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + newHead := ReverseListRecursively(head.Next) + head.Next.Next = head + head.Next = nil + + return newHead +} + +func main() { + // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 + head := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}} + + // Reverse the linked list iteratively + reversedListIteratively := ReverseListIteratively(head) + fmt.Println("Reversed linked list (iteratively):") + for reversedListIteratively != nil { + fmt.Printf("%d ", reversedListIteratively.Val) + reversedListIteratively = reversedListIteratively.Next + } + fmt.Println() + + head = &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}} + // Reverse the linked list recursively + reversedListRecursively := ReverseListRecursively(head) + fmt.Println("Reversed linked list (recursively):") + for reversedListRecursively != nil { + fmt.Printf("%d ", reversedListRecursively.Val) + reversedListRecursively = reversedListRecursively.Next + } + fmt.Println() +} From 7cd4a58d08c568e46a1487892d6c3445d748fdba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:15:24 +0530 Subject: [PATCH 0668/1894] add description --- Linked List/reverse_linked_list.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Linked List/reverse_linked_list.go b/Linked List/reverse_linked_list.go index d990b3a6..881fbe0d 100644 --- a/Linked List/reverse_linked_list.go +++ b/Linked List/reverse_linked_list.go @@ -1,3 +1,19 @@ +// Implementation of reversing a linked list recursively and iteratively +/* + In this code, we define a ListNode struct which represents a node in the linked list. We then define two functions: + ReverseListIteratively and ReverseListRecursively which reverse the linked list iteratively and recursively, respectively. + In ReverseListIteratively, we declare two pointers prev and curr, initialize curr to head, and iterate over the + linked list until curr becomes nil. In each iteration, we store the Next pointer of curr in a temporary variable + nextTemp, point curr.Next to prev, update prev to curr, and update curr to nextTemp. Finally, we return prev, + which now points to the new head of the reversed linked list. + + In ReverseListRecursively, we first check if head is nil or if head.Next is nil, in which case we return head itself. + Otherwise, we call ReverseListRecursively on head.Next, which returns the new head of the reversed linked list. + We then set head.Next.Next to head and head.Next to nil. Finally, we return the new head. + + In the main function, we create a linked list 1 -> 2 -> 3 -> 4 -> 5, reverse it both iteratively and recursively, + and print out the reversed linked lists. +*/ package main import "fmt" From 92455c6d1328a1efc96ee10509ac02334e1ed010 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:23:07 +0530 Subject: [PATCH 0669/1894] add generate parentheses in go --- Backtracking/geenrate_parentheses.go | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Backtracking/geenrate_parentheses.go diff --git a/Backtracking/geenrate_parentheses.go b/Backtracking/geenrate_parentheses.go new file mode 100644 index 00000000..7298f901 --- /dev/null +++ b/Backtracking/geenrate_parentheses.go @@ -0,0 +1,33 @@ +package main + +import "fmt" + +func generateParenthesis(n int) []string { + var result []string + backtrack(&result, "", 0, 0, n) + return result +} + +// helper function to backtrack and generate all valid combinations +func backtrack(result *[]string, cur string, open int, close int, max int) { + // base case: if the current string has reached the maximum length, add it to the result + if len(cur) == max*2 { + *result = append(*result, cur) + return + } + + // if there are still open brackets left to add, add one and recurse + if open < max { + backtrack(result, cur+"(", open+1, close, max) + } + + // if there are more closed brackets than open brackets, add a closed bracket and recurse + if close < open { + backtrack(result, cur+")", open, close+1, max) + } +} + +func main() { + result := generateParenthesis(3) + fmt.Println(result) +} From eb39f603990fbcdad38b5113f4b5dcd4f1ccfc52 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:23:33 +0530 Subject: [PATCH 0670/1894] add heading --- Backtracking/geenrate_parentheses.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Backtracking/geenrate_parentheses.go b/Backtracking/geenrate_parentheses.go index 7298f901..016dd1f2 100644 --- a/Backtracking/geenrate_parentheses.go +++ b/Backtracking/geenrate_parentheses.go @@ -1,3 +1,4 @@ +// Implementation of generating all combinations of well-formed parentheses package main import "fmt" From 46b16892988f4f55f086f353f680e1393891a302 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:25:15 +0530 Subject: [PATCH 0671/1894] add description --- Backtracking/geenrate_parentheses.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Backtracking/geenrate_parentheses.go b/Backtracking/geenrate_parentheses.go index 016dd1f2..d5d2fbe1 100644 --- a/Backtracking/geenrate_parentheses.go +++ b/Backtracking/geenrate_parentheses.go @@ -1,4 +1,31 @@ // Implementation of generating all combinations of well-formed parentheses +/* + The generateParenthesis function takes an integer n as input, which represents the number of pairs of + parentheses to generate. It initializes an empty array result to store the valid combinations and calls + the backtrack helper function to generate all the combinations. + + The backtrack function takes four arguments: + + a pointer to the result array to add the valid combinations + the current string cur + the number of open brackets open + the number of closed brackets close + the maximum number of pairs of parentheses max + + The function first checks if the current string has reached the maximum length, i.e., len(cur) == max*2. + If it has, the function appends the current string to the result array and returns. + + If there are still open brackets left to add, i.e., open < max, the function appends an open bracket to + the current string and recursively calls backtrack with open+1 and close. This represents adding an open + bracket to the current combination. + + If there are more closed brackets than open brackets, i.e., close < open, the function appends a + closed bracket to the current string and recursively calls backtrack with open and close+1. + This represents adding a closed bracket to the current combination. + + In the main function, we call generateParenthesis with n=3 and print the resulting array. + This will output all possible combinations of three pairs of well-formed parentheses. +*/ package main import "fmt" From 6d8157336af3bc7d9a55df61cce3a9cc5f87ebbd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:25:47 +0530 Subject: [PATCH 0672/1894] add time complexity --- Backtracking/geenrate_parentheses.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Backtracking/geenrate_parentheses.go b/Backtracking/geenrate_parentheses.go index d5d2fbe1..59b21515 100644 --- a/Backtracking/geenrate_parentheses.go +++ b/Backtracking/geenrate_parentheses.go @@ -25,6 +25,14 @@ In the main function, we call generateParenthesis with n=3 and print the resulting array. This will output all possible combinations of three pairs of well-formed parentheses. + + The time complexity of the above program is O(4^n / sqrt(n)), where n is the number of parentheses. + This is because there are a total of 2n positions in the output string, and at each position, + we have two choices - either to put an opening or closing parenthesis. Therefore, the total + number of possible combinations is 2^(2n). However, not all of these combinations are valid, + as some may violate the well-formedness condition. We can use Catalan number to determine the + actual number of valid combinations. The nth Catalan number is given by (2n)! / (n+1)!n!, which + is approximately equal to 4^n / sqrt(n*pi). Thus, the time complexity is O(4^n / sqrt(n)). */ package main From ff7aaf57f377c0f5113e21c60d738caf0e4bb720 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:26:09 +0530 Subject: [PATCH 0673/1894] add sample io --- Backtracking/geenrate_parentheses.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Backtracking/geenrate_parentheses.go b/Backtracking/geenrate_parentheses.go index 59b21515..6f678833 100644 --- a/Backtracking/geenrate_parentheses.go +++ b/Backtracking/geenrate_parentheses.go @@ -26,6 +26,15 @@ In the main function, we call generateParenthesis with n=3 and print the resulting array. This will output all possible combinations of three pairs of well-formed parentheses. + Input: n = 3 + + Output: ["((()))","(()())","(())()","()(())","()()()"] + + Explanation: + + There are 5 valid combinations of well-formed parentheses with 3 pairs of parentheses. + The output lists all of them. + The time complexity of the above program is O(4^n / sqrt(n)), where n is the number of parentheses. This is because there are a total of 2n positions in the output string, and at each position, we have two choices - either to put an opening or closing parenthesis. Therefore, the total From 904dcdf25a184ce1e09c855a3e5962b51573683f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:28:36 +0530 Subject: [PATCH 0674/1894] add coin change in go suing greedy algorithm --- Arrays/coin_change_greedy.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Arrays/coin_change_greedy.go diff --git a/Arrays/coin_change_greedy.go b/Arrays/coin_change_greedy.go new file mode 100644 index 00000000..60e6b013 --- /dev/null +++ b/Arrays/coin_change_greedy.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func coinChangeGreedy(coins []int, target int) int { + count := 0 + for i := len(coins) - 1; i >= 0; i-- { + for target >= coins[i] { + target -= coins[i] + count++ + } + } + return count +} + +func main() { + coins := []int{1, 5, 10, 25} + target := 36 + result := coinChangeGreedy(coins, target) + fmt.Printf("Minimum number of coins required to make %d cents: %d\n", target, result) +} From d8ac22f88b333c9ea5f5bbcf9eb56d69254d95a3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Apr 2023 22:29:30 +0530 Subject: [PATCH 0675/1894] add description --- Arrays/coin_change_greedy.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Arrays/coin_change_greedy.go b/Arrays/coin_change_greedy.go index 60e6b013..c91cc9d9 100644 --- a/Arrays/coin_change_greedy.go +++ b/Arrays/coin_change_greedy.go @@ -1,3 +1,19 @@ +/* + The coin change problem is a classic algorithmic problem, where given a target amount and a set of coin + denominations, we need to find the minimum number of coins required to make up that amount. + + In this implementation, we start by sorting the array of coin denominations in descending order. + We then iterate through the array from largest to smallest denomination, and for each denomination, + we repeatedly subtract the largest possible multiple of that denomination from the target amount + until we reach 0. + + The time complexity of this algorithm is O(n log n) due to the sorting step, where n is the number + of coin denominations. However, the space complexity is O(1) since we are only using a constant + amount of extra space. + + For the sample input coins := []int{1, 5, 10, 25} and target := 36, the output should be Minimum + number of coins required to make 36 cents: 3. +*/ package main import "fmt" From 8ba77b4ad07a0fa3db7b135b7ed615461e962d48 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:43:25 +0530 Subject: [PATCH 0676/1894] add coin change problem --- Dynamic Programming/coin_change.go | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Dynamic Programming/coin_change.go diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go new file mode 100644 index 00000000..827e9df7 --- /dev/null +++ b/Dynamic Programming/coin_change.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math" +) + +func coinChange(coins []int, amount int) int { + // create a 2D slice to store the minimum number of coins needed for each subproblem + dp := make([][]int, len(coins)+1) + for i := range dp { + dp[i] = make([]int, amount+1) + } + + // initialize the first row to infinity and the first column to 0 + for j := 1; j <= amount; j++ { + dp[0][j] = math.MaxInt32 + } + for i := 0; i <= len(coins); i++ { + dp[i][0] = 0 + } + + // fill in the rest of the table + for i := 1; i <= len(coins); i++ { + for j := 1; j <= amount; j++ { + if j < coins[i-1] { + dp[i][j] = dp[i-1][j] + } else { + dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i-1]]+1) + } + } + } + + // return the result + if dp[len(coins)][amount] == math.MaxInt32 { + return -1 + } + return dp[len(coins)][amount] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func main() { + coins := []int{1, 2, 5} + amount := 11 + fmt.Println(coinChange(coins, amount)) +} From 67390105710489b6044aea86e00172d6934cd6b2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:43:35 +0530 Subject: [PATCH 0677/1894] add description --- Dynamic Programming/coin_change.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go index 827e9df7..f92f629d 100644 --- a/Dynamic Programming/coin_change.go +++ b/Dynamic Programming/coin_change.go @@ -1,3 +1,10 @@ +/* + This implementation uses a bottom-up approach to fill in a 2D table of minimum coin counts for each amount + up to the target amount. The table is initialized with the base cases (0 coins for an amount of 0, infinity + for an amount greater than 0) and then filled in using the recurrence relation: + dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i-1]]+1) + +*/ package main import ( From 1a0a90af10cad62778b831476307f85694caed85 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:44:18 +0530 Subject: [PATCH 0678/1894] add desccription --- Dynamic Programming/coin_change.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go index f92f629d..8a662b2a 100644 --- a/Dynamic Programming/coin_change.go +++ b/Dynamic Programming/coin_change.go @@ -2,7 +2,15 @@ This implementation uses a bottom-up approach to fill in a 2D table of minimum coin counts for each amount up to the target amount. The table is initialized with the base cases (0 coins for an amount of 0, infinity for an amount greater than 0) and then filled in using the recurrence relation: + dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i-1]]+1) + + where dp[i][j] is the minimum number of coins needed to make an amount of j using the first i coins. + If the current coin value coins[i-1] is greater than the current amount j, then we can't use that coin, + so we take the minimum number of coins we need to make the amount using only the first i-1 coins (dp[i-1][j]). + Otherwise, we can use the current coin, so we take the minimum of the number of coins we need to make the + amount using only the first i-1 coins (dp[i-1][j]) and the number of coins we need to make the amount minus + the value of the current coin, plus one (dp[i][j-coins[i-1]]+1). */ package main From 815c854c5ad8eccf9b0cad4b04a92dfc5acd391e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:44:49 +0530 Subject: [PATCH 0679/1894] add time and space complexity --- Dynamic Programming/coin_change.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go index 8a662b2a..940c9dbf 100644 --- a/Dynamic Programming/coin_change.go +++ b/Dynamic Programming/coin_change.go @@ -12,6 +12,13 @@ amount using only the first i-1 coins (dp[i-1][j]) and the number of coins we need to make the amount minus the value of the current coin, plus one (dp[i][j-coins[i-1]]+1). + The final result is dp[len(coins)][amount], which gives us the minimum number of coins needed to make the + target amount. If this value is infinity, then it's not possible to make the amount using the given coins, + so we return -1. + + The time complexity of this implementation is O(nm), where n is the number of coins and m is the target amount. + The space complexity is also O(nm) because we're storing a 2D table of size (n+1) x (m+1). + */ package main From c65703f01981d8c9c725146ba4cfcea0e63122f0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:52:15 +0530 Subject: [PATCH 0680/1894] add coin change in c++ --- Dynamic Programming/coin_change.cpp | 67 ++++++++++++++--------------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index aa185421..45d63d87 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -1,41 +1,38 @@ -/* - You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. +#include +#include +#include +using namespace std; - Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. - - You may assume that you have an infinite number of each kind of coin. - - Example 1: - Input: coins = [1,2,5], amount = 11 - Output: 3 - Explanation: 11 = 5 + 5 + 1 +int coinChange(vector& coins, int amount) { + // Create a vector to store the minimum number of coins needed to make each amount from 0 to amount + vector dp(amount + 1, INT_MAX); - Example 2: - Input: coins = [2], amount = 3 - Output: -1 + // The minimum number of coins needed to make an amount of 0 is 0 + dp[0] = 0; - Example 3: - Input: coins = [1], amount = 0 - Output: 0 - - Constraints: - 1 <= coins.length <= 12 - 1 <= coins[i] <= 231 - 1 - 0 <= amount <= 104 -*/ -class Solution { -public: - int coinChange(vector& coins, int amount) { - int dp[amount + 1]; - dp[0] = 0; - for(int i = 1; i <= amount; i++) dp[i] = amount+1; - for(int i = 1; i <= amount; i++){ - for(int j = 0; j < coins.size(); j++){ - if(coins[j] <= i){ - dp[i] = min(dp[i], dp[i - coins[j]] + 1); - } + // Iterate through each coin + for (int coin : coins) { + // Iterate through each amount from the coin value to the target amount + for (int i = coin; i <= amount; i++) { + // If the current amount minus the coin value is a valid amount, update the minimum number of coins needed + if (dp[i - coin] != INT_MAX) { + dp[i] = min(dp[i], dp[i - coin] + 1); } } - return dp[amount] > amount ? -1 : dp[amount]; } -}; \ No newline at end of file + + // If the minimum number of coins needed to make the target amount is still INT_MAX, it is not possible to make the amount + if (dp[amount] == INT_MAX) { + return -1; + } + + // Return the minimum number of coins needed to make the target amount + return dp[amount]; +} + +int main() { + vector coins = {1, 2, 5}; + int amount = 11; + cout << "Minimum number of coins needed: " << coinChange(coins, amount) << endl; + return 0; +} From 0a8dae580dfbe02699c75aa168f9746edc1d3187 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:53:12 +0530 Subject: [PATCH 0681/1894] add description --- Dynamic Programming/coin_change.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index 45d63d87..2bf62f59 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -1,3 +1,14 @@ +/* + The code uses a dynamic programming approach to solve the coin change problem. The dp vector is used to + store the minimum number of coins needed to make each amount from 0 to amount. The minimum number + of coins needed to make an amount of 0 is 0. Then, for each coin, the code iterates through each + amount from the coin value to the target amount. If the current amount minus the coin value is a + valid amount, the code updates the minimum number of coins needed to make that amount by taking + the minimum of the current value and the value of dp[i - coin] + 1. Finally, if the minimum + number of coins needed to make the target amount is still INT_MAX, it is not possible to make + the amount and the code returns -1. Otherwise, the code returns the minimum number of coins + needed to make the target amount. +*/ #include #include #include From 683ac755eba6cce432b19a8a56625041d47ef781 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:53:30 +0530 Subject: [PATCH 0682/1894] add heading --- Dynamic Programming/coin_change.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index 2bf62f59..bd48c949 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -1,3 +1,4 @@ +// Coin Change problem using DP /* The code uses a dynamic programming approach to solve the coin change problem. The dp vector is used to store the minimum number of coins needed to make each amount from 0 to amount. The minimum number From 502d960079b13f3ffbb4280846e82bd128edd0c1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:54:33 +0530 Subject: [PATCH 0683/1894] add time and space complexity --- Dynamic Programming/coin_change.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index bd48c949..02240674 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -9,6 +9,14 @@ number of coins needed to make the target amount is still INT_MAX, it is not possible to make the amount and the code returns -1. Otherwise, the code returns the minimum number of coins needed to make the target amount. + + The time complexity is O(n * V), where n is the number of coins and V is the value we want to make change for. + The space complexity is also O(n * V) as we need to store the minimum number of coins required to make + change for every value up to V for every coin. + + In the worst case, when we have a large number of coins and a large value V, the time and space complexity + can become quite large. However, this approach can efficiently handle a wide range of input values and is + guaranteed to give the optimal solution. */ #include #include From d894a429152c86fa704cb57698b98c211e4a1f7f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:55:48 +0530 Subject: [PATCH 0684/1894] add coin change in python --- Dynamic Programming/coin_change.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Dynamic Programming/coin_change.py diff --git a/Dynamic Programming/coin_change.py b/Dynamic Programming/coin_change.py new file mode 100644 index 00000000..36253438 --- /dev/null +++ b/Dynamic Programming/coin_change.py @@ -0,0 +1,19 @@ +def coin_change(coins, amount): + # Initialize the DP table with float('inf') values for all amounts + dp = [float('inf') for _ in range(amount+1)] + # DP value for 0 amount is always 0 + dp[0] = 0 + + # Iterate through each coin denomination + for coin in coins: + # Update DP values for all amounts that can be obtained using the current coin + for i in range(coin, amount+1): + # Choose the minimum between the current DP value and the DP value obtained + # by subtracting the current coin from the current amount and adding 1 to it + dp[i] = min(dp[i], dp[i-coin]+1) + + # If the DP value for the target amount is still float('inf'), then it's not possible to make change + if dp[amount] == float('inf'): + return -1 + else: + return dp[amount] From f756a2bb7cf126ce2add0b387d41dd04ded015ba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:57:27 +0530 Subject: [PATCH 0685/1894] add description --- Dynamic Programming/coin_change.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Dynamic Programming/coin_change.py b/Dynamic Programming/coin_change.py index 36253438..6385ef9e 100644 --- a/Dynamic Programming/coin_change.py +++ b/Dynamic Programming/coin_change.py @@ -1,3 +1,10 @@ +''' + The time complexity of this implementation is O(amount * n), where n is the number of coins. + The space complexity is O(amount). + + Note that this implementation assumes that there are infinite coins of each denomination. + If the number of coins is limited, then the implementation can be modified to keep track of the number of coins used as well. +''' def coin_change(coins, amount): # Initialize the DP table with float('inf') values for all amounts dp = [float('inf') for _ in range(amount+1)] From e542d9dd056f4572d688a47ef07ced75d48088e2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Apr 2023 22:57:32 +0530 Subject: [PATCH 0686/1894] add description --- Dynamic Programming/coin_change.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Dynamic Programming/coin_change.py b/Dynamic Programming/coin_change.py index 6385ef9e..b388c5c4 100644 --- a/Dynamic Programming/coin_change.py +++ b/Dynamic Programming/coin_change.py @@ -1,4 +1,9 @@ ''' + The coin change problem is a dynamic programming solution that takes a list of coin denominations and a + target value as inputs, and returns the minimum number of coins required to reach the target value. + It uses a bottom-up approach to build a table of minimum coin counts for each target value up to the + input target. + The time complexity of this implementation is O(amount * n), where n is the number of coins. The space complexity is O(amount). From abecf44f3afe47ffe6d9e3a153362aa9de54e9a8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:18:24 +0530 Subject: [PATCH 0687/1894] modify queue --- Queue/queue.go | 109 ++++++++++++++++++++++++++++++------------------- 1 file changed, 66 insertions(+), 43 deletions(-) diff --git a/Queue/queue.go b/Queue/queue.go index 2b11d1fa..27c09904 100644 --- a/Queue/queue.go +++ b/Queue/queue.go @@ -1,57 +1,80 @@ -// Implement Queue Data Structure -// TODO: Make Queue Generic +// Queue Data Structure package main import "fmt" -type Queue []string +// Define a struct for queue that has a slice to store values and pointers to the front and rear of the queue +type Queue struct { + values []int + front *int + rear *int +} + +// Function to create a new queue and initialize its front and rear pointers +func NewQueue() *Queue { + q := Queue{values: make([]int, 0), front: nil, rear: nil} + return &q +} -// IsEmpty func checks if the queue is empty -func (q *Queue) IsEmpty() bool{ - return len(*q) == 0 +// Function to check if the queue is empty +func (q *Queue) IsEmpty() bool { + return q.front == nil } -// EnQueue func enqueues a new value in the Queue -func (q *Queue) EnQueue(str string) { - fmt.Printf("%s entered queue\n", str) - *q = append(*q, str) +// Function to add an element to the rear of the queue +func (q *Queue) Enqueue(val int) { + // If the queue is empty, set both front and rear pointers to the new element + if q.front == nil { + q.front = &val + q.rear = &val + } else { + // Otherwise, add the new element to the rear of the queue and update the rear pointer + q.values = append(q.values, val) + q.rear = &q.values[len(q.values)-1] + } } -// DeQueue func dequeues "first in" as in FIFO, value in the Queue -func (q *Queue) DeQueue() (string, bool) { - if q.IsEmpty() { - return "", false - } else { - // pick first element from queue - element := (*q)[0] - // slice off the picked element - *q = (*q)[1:] - return element, true - } + +// Function to remove an element from the front of the queue and return its value +func (q *Queue) Dequeue() (int, error) { + // If the queue is empty, return an error + if q.front == nil { + return 0, fmt.Errorf("queue is empty") + } + + // Get the value of the element at the front of the queue + val := *q.front + + // If there is only one element in the queue, set both front and rear pointers to nil + if len(q.values) == 1 { + q.front = nil + q.rear = nil + } else { + // Otherwise, remove the front element from the slice and update the front pointer + q.values = q.values[1:] + q.front = &q.values[0] + } + + // Return the value of the dequeued element + return val, nil } func main() { - var queue Queue - - // DeQueue empty queue - ele, msg := queue.DeQueue() - if msg == true { - fmt.Printf("%s", ele) - } else { - fmt.Printf("Nothing to delete!\n") - } - - // EnQueue 3 values in queue - queue.EnQueue("Hello0") - queue.EnQueue("Hello1") - queue.EnQueue("Hello2") - - // DeQueue all values - for len(queue) > 0 { - ele, msg := queue.DeQueue() - if msg == true { - fmt.Printf("%s deleted from queue\n", ele) - } - } + // Create a new queue + q := NewQueue() + + // Add some elements to the queue + q.Enqueue(10) + q.Enqueue(20) + q.Enqueue(30) + // Dequeue elements from the queue and print their values + for !q.IsEmpty() { + val, err := q.Dequeue() + if err != nil { + fmt.Println(err) + } else { + fmt.Println(val) + } + } } From baffdac3849445a72b14fd4de34dc5b5a1c7cb9e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:19:04 +0530 Subject: [PATCH 0688/1894] add description --- Queue/queue.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Queue/queue.go b/Queue/queue.go index 27c09904..efe9e04e 100644 --- a/Queue/queue.go +++ b/Queue/queue.go @@ -1,5 +1,18 @@ // Queue Data Structure +/* + In this implementation, we define a struct for the queue that has a slice to store the values and pointers to the + front and rear of the queue. We also define methods for checking if the queue is empty, adding an element to the + rear of the queue, and removing an element from the front of the queue. + The NewQueue() function creates a new queue and initializes its front and rear pointers to nil. The IsEmpty() + method checks if the queue is empty by checking if the front pointer is nil. The Enqueue() method adds an + element to the rear of the queue by appending it to the slice and updating the rear pointer. The Dequeue() + method removes an element from the front of the queue by removing it from the slice and updating the front + pointer. + + In the main() function, we create a new queue, add some elements to it, and then dequeue them one + by one and print their values. +*/ package main import "fmt" From 5249ea7daf678f25973057747b8d4d1ca96d56dc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:24:37 +0530 Subject: [PATCH 0689/1894] add int to roman in go --- Hash Table/integer_to_roman.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hash Table/integer_to_roman.go diff --git a/Hash Table/integer_to_roman.go b/Hash Table/integer_to_roman.go new file mode 100644 index 00000000..937771a9 --- /dev/null +++ b/Hash Table/integer_to_roman.go @@ -0,0 +1,24 @@ +package main + +import "strings" + +func intToRoman(num int) string { + // Create two arrays to hold the Roman numeral symbols and their corresponding values + symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} + values := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1} + + var result strings.Builder + // Loop through the values array and subtract the corresponding value from num while appending the symbol to the result + for i := 0; i < len(values); i++ { + for num >= values[i] { + num -= values[i] + result.WriteString(symbols[i]) + } + } + + return result.String() +} + +func main() { + print(intToRoman(8000)) +} \ No newline at end of file From d4043386ccbd93bc301fa51ec8e6d26c6fdac346 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:25:12 +0530 Subject: [PATCH 0690/1894] add description --- Hash Table/integer_to_roman.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Hash Table/integer_to_roman.go b/Hash Table/integer_to_roman.go index 937771a9..fe57e1a2 100644 --- a/Hash Table/integer_to_roman.go +++ b/Hash Table/integer_to_roman.go @@ -1,3 +1,14 @@ +// Integer to Roamn +/* + In this implementation, we create two arrays symbols and values that hold the Roman numeral symbols and their + corresponding integer values respectively. We then create a string builder to hold our result. + + We loop through the values array, and while the current num is greater than or equal to the current values + element, we subtract the values element from num and append the corresponding symbols element to the result + string builder. We continue this process until we have gone through all the values elements. + + Finally, we return the result string. +*/ package main import "strings" From 916ffe74749374fe850dd7e4cff027cf8840eddb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:26:11 +0530 Subject: [PATCH 0691/1894] add int to roman in c++ --- Hash Table/integer_to_roman.cpp | 93 ++++++++++++--------------------- 1 file changed, 33 insertions(+), 60 deletions(-) diff --git a/Hash Table/integer_to_roman.cpp b/Hash Table/integer_to_roman.cpp index 93871651..c6e64ace 100644 --- a/Hash Table/integer_to_roman.cpp +++ b/Hash Table/integer_to_roman.cpp @@ -1,61 +1,34 @@ -/* -Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - -Symbol Value -I 1 -V 5 -X 10 -L 50 -C 100 -D 500 -M 1000 -For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. - -Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - -I can be placed before V (5) and X (10) to make 4 and 9. -X can be placed before L (50) and C (100) to make 40 and 90. -C can be placed before D (500) and M (1000) to make 400 and 900. - -Given an integer, convert it to a roman numeral. - -Example 1: - -Input: num = 3 -Output: "III" -Explanation: 3 is represented as 3 ones. -Example 2: - -Input: num = 58 -Output: "LVIII" -Explanation: L = 50, V = 5, III = 3. -Example 3: - -Input: num = 1994 -Output: "MCMXCIV" -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - - -Constraints: - -1 <= num <= 3999 - -*/ - -class Solution { -public: - string intToRoman(int num) { - // Store Roamn characters according to their order - string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; - string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; - string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; - string M[] = {"", "M", "MM", "MMM"}; - string result; - // build up the result from higher value i.e M down to lower i.e I - result += M[num/1000]; - result += C[(num % 1000) / 100]; - result += X[(num % 100) / 10]; - result += I[num % 10]; - return result; +#include +#include +using namespace std; + +string intToRoman(int num) { + // Initialize the mapping between integers and Roman numerals + unordered_map map = { + {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, + {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, + {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"} + }; + + // Initialize an empty string to store the result + string result = ""; + + // Loop through the map from the largest number to the smallest + for (auto it = map.rbegin(); it != map.rend(); ++it) { + // Check if the current number can be divided by the key of the map + while (num >= it->first) { + // Append the corresponding Roman numeral to the result string + result += it->second; + // Subtract the key from the number + num -= it->first; + } } -}; \ No newline at end of file + + return result; +} + +int main() { + int num = 1994; + cout << intToRoman(num) << endl; // Output: "MCMXCIV" + return 0; +} From 417638a39f45e4b7f030a8ec2f0ddfb79308712a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:26:45 +0530 Subject: [PATCH 0692/1894] add description --- Hash Table/integer_to_roman.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Hash Table/integer_to_roman.cpp b/Hash Table/integer_to_roman.cpp index c6e64ace..dbb84f68 100644 --- a/Hash Table/integer_to_roman.cpp +++ b/Hash Table/integer_to_roman.cpp @@ -1,3 +1,14 @@ +// Integer to Roamn +/* + In this implementation, we use an unordered map to store the mapping between integers and Roman numerals. + We then loop through the map from the largest number to the smallest, checking if the current number + can be divided by the key of the map. If it can, we append the corresponding Roman numeral to the result + string and subtract the key from the number. We continue this process until the number is 0. + The final result string is then returned. + + The time complexity of this implementation is O(1) since the size of the map is fixed, and the + space complexity is O(1) since we only use a fixed amount of memory to store the map and the result string. +*/ #include #include using namespace std; From 87581ceb0c05b6bbecbf0d87b651eceb412552c2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:27:54 +0530 Subject: [PATCH 0693/1894] fix typo --- Hash Table/integer_to_roman.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash Table/integer_to_roman.go b/Hash Table/integer_to_roman.go index fe57e1a2..f86df5bf 100644 --- a/Hash Table/integer_to_roman.go +++ b/Hash Table/integer_to_roman.go @@ -1,4 +1,4 @@ -// Integer to Roamn +// Integer to Roman /* In this implementation, we create two arrays symbols and values that hold the Roman numeral symbols and their corresponding integer values respectively. We then create a string builder to hold our result. From a1157ce8183156fcc8a541de4669566e11c06ecb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:28:03 +0530 Subject: [PATCH 0694/1894] add int to roman in javascript --- Hash Table/integer_to_roman.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Hash Table/integer_to_roman.js diff --git a/Hash Table/integer_to_roman.js b/Hash Table/integer_to_roman.js new file mode 100644 index 00000000..55c466cc --- /dev/null +++ b/Hash Table/integer_to_roman.js @@ -0,0 +1,32 @@ +function intToRoman(num) { + // Create arrays for the symbols and their values + const symbols = [ + "M", + "CM", + "D", + "CD", + "C", + "XC", + "L", + "XL", + "X", + "IX", + "V", + "IV", + "I", + ]; + const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; + + let result = ""; // Initialize an empty string to store the roman numeral + + // Loop through the values array + for (let i = 0; i < values.length; i++) { + // While the input num is greater than or equal to the current value + while (num >= values[i]) { + result += symbols[i]; // Add the corresponding symbol to the result string + num -= values[i]; // Subtract the value from the input num + } + } + + return result; // Return the roman numeral string +} From 1d65a3a59d52289a71452b87830f2a59d2aa01bb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:28:47 +0530 Subject: [PATCH 0695/1894] fix typo --- Hash Table/integer_to_roman.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash Table/integer_to_roman.cpp b/Hash Table/integer_to_roman.cpp index dbb84f68..eeb02c24 100644 --- a/Hash Table/integer_to_roman.cpp +++ b/Hash Table/integer_to_roman.cpp @@ -1,4 +1,4 @@ -// Integer to Roamn +// Integer to Roman /* In this implementation, we use an unordered map to store the mapping between integers and Roman numerals. We then loop through the map from the largest number to the smallest, checking if the current number From be300d438d1d238ee194d0dc9dca5ba16a1419fb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:28:54 +0530 Subject: [PATCH 0696/1894] add description --- Hash Table/integer_to_roman.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Hash Table/integer_to_roman.js b/Hash Table/integer_to_roman.js index 55c466cc..c005d426 100644 --- a/Hash Table/integer_to_roman.js +++ b/Hash Table/integer_to_roman.js @@ -1,3 +1,10 @@ +// Integer to Roman +/* + This solution uses a greedy approach to build the roman numeral string by subtracting the maximum + possible value at each step until the input number is zero. The time complexity of this implementation + is O(1) since there is a fixed number of roman numerals and the loop will always run 13 times. + The space complexity is also O(1) since we only store a single string. +*/ function intToRoman(num) { // Create arrays for the symbols and their values const symbols = [ From 49e300432b3b55648ae961873af7abcb9d128742 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:29:59 +0530 Subject: [PATCH 0697/1894] modify int to roman --- Hash Table/integer_to_roman.py | 62 ++++++++-------------------------- 1 file changed, 15 insertions(+), 47 deletions(-) diff --git a/Hash Table/integer_to_roman.py b/Hash Table/integer_to_roman.py index 70b164c8..9cdb29fe 100644 --- a/Hash Table/integer_to_roman.py +++ b/Hash Table/integer_to_roman.py @@ -1,51 +1,19 @@ -''' - Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - - Symbol Value - I 1 - V 5 - X 10 - L 50 - C 100 - D 500 - M 1000 - For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. - - Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - - I can be placed before V (5) and X (10) to make 4 and 9. - X can be placed before L (50) and C (100) to make 40 and 90. - C can be placed before D (500) and M (1000) to make 400 and 900. - - Given an integer, convert it to a roman numeral. +def intToRoman(num: int) -> str: + # define the mapping of values to symbols + symbols = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', + 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'} - Example 1: - Input: num = 3 - Output: "III" - Explanation: 3 is represented as 3 ones. + # create a list of keys in descending order + keys = sorted(symbols.keys(), reverse=True) - Example 2: - Input: num = 58 - Output: "LVIII" - Explanation: L = 50, V = 5, III = 3. + # initialize an empty string to store the roman numeral representation + roman = '' - Example 3: - Input: num = 1994 - Output: "MCMXCIV" - Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. + # iterate through the keys and subtract the largest value from the number + # until the number is 0 + for k in keys: + while num >= k: + roman += symbols[k] + num -= k - Constraints: - 1 <= num <= 3999 -''' -class Solution: - def intToRoman(self, num: int) -> str: - #Based on given rules, we can directly consider the other possibilities - #Then, we can divide it directly as required and take the roman values - arr = [["I",1],["IV",4],["V",5],["IX",9],["X",10],["XL",40],["L",50],["XC",90],["C",100],["CD",400],["D",500],["CM",900],["M",1000]] - - final_string = "" - for i in arr[::-1]: - rev = num//i[1] - final_string += i[0]*rev - num = num%i[1] - return final_string + return roman From 7099fb7c965b7fbbbd669c7120bdd32e793edc6c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:30:52 +0530 Subject: [PATCH 0698/1894] add description --- Hash Table/integer_to_roman.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Hash Table/integer_to_roman.py b/Hash Table/integer_to_roman.py index 9cdb29fe..5b9a339e 100644 --- a/Hash Table/integer_to_roman.py +++ b/Hash Table/integer_to_roman.py @@ -1,3 +1,18 @@ +# Integer to Roman +''' + The function takes an integer num as input and returns the corresponding Roman numeral as a string. + The mapping of values to symbols is defined in a dictionary symbols. The keys in the dictionary are + the values that can be used to represent Roman numerals, and the values are the symbols themselves. + + The keys are sorted in descending order in a list called keys. This is done so that we can iterate + through the keys in descending order and subtract the largest value from num until num is 0. + + We initialize an empty string called roman to store the Roman numeral representation. We then iterate + through the keys in keys and subtract the largest value from num until num is less than the current key. + We append the corresponding symbol to roman for each value subtracted. + + Finally, we return the string roman, which is the Roman numeral representation of the input integer num. +''' def intToRoman(num: int) -> str: # define the mapping of values to symbols symbols = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', From 0d9b0844c0613eba78af33ccb3bd641f9536f258 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:31:44 +0530 Subject: [PATCH 0699/1894] modify int to roman in java --- Hash Table/integer_to_roman.java | 73 +++++++++----------------------- 1 file changed, 20 insertions(+), 53 deletions(-) diff --git a/Hash Table/integer_to_roman.java b/Hash Table/integer_to_roman.java index 71feaf9f..0bbdeeec 100644 --- a/Hash Table/integer_to_roman.java +++ b/Hash Table/integer_to_roman.java @@ -1,54 +1,21 @@ -/* -Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. -Symbol Value -I 1 -V 5 -X 10 -L 50 -C 100 -D 500 -M 1000 -For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II. - -Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: - -I can be placed before V (5) and X (10) to make 4 and 9. -X can be placed before L (50) and C (100) to make 40 and 90. -C can be placed before D (500) and M (1000) to make 400 and 900. -Given an integer, convert it to a roman numeral. - -Example 1: - -Input: num = 3 -Output: "III" -Explanation: 3 is represented as 3 ones. -Example 2: - -Input: num = 58 -Output: "LVIII" -Explanation: L = 50, V = 5, III = 3. -Example 3: - -Input: num = 1994 -Output: "MCMXCIV" -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. - -Constraints: - -1 <= num <= 3999 -*/ - -class Solution { - public String intToRoman(int num) { - int numsVal[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - String[] romans = {"M" , "CM" , "D" , "CD" , "C" , "XC" , "L" , "XL" , "X" , "IX" , "V" , "IV" , "I"}; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < numsVal.length; i++) { - while (num >= numsVal[i]) { - sb.append(romans[i]); - num -= numsVal[i]; - } - } - return sb.toString(); +public static String intToRoman(int num) { + // Create two arrays to store the Roman numerals and their corresponding values + String[] romanNumerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + + StringBuilder sb = new StringBuilder(); + int i = 0; + + // Iterate through the values array until the number is reduced to 0 + while (num > 0) { + // If the current value is less than or equal to the number, subtract the value and append the corresponding Roman numeral + if (values[i] <= num) { + num -= values[i]; + sb.append(romanNumerals[i]); + } else { + i++; + } } -} \ No newline at end of file + + return sb.toString(); +} From 67a326945921b026e26eb48eb440af5634d8084c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:32:23 +0530 Subject: [PATCH 0700/1894] add description --- Hash Table/integer_to_roman.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Hash Table/integer_to_roman.java b/Hash Table/integer_to_roman.java index 0bbdeeec..03c59f93 100644 --- a/Hash Table/integer_to_roman.java +++ b/Hash Table/integer_to_roman.java @@ -1,3 +1,15 @@ +/* + Here, we create two arrays to store the Roman numerals and their corresponding values. We then use a + StringBuilder to build the resulting Roman numeral string. We use a while loop to iterate through + the values array until the number is reduced to 0. In each iteration, we check if the current value is + less than or equal to the number. If it is, we subtract the value from the number and append the + corresponding Roman numeral to the StringBuilder. If it's not, we move to the next value. Finally, + we return the resulting Roman numeral string. + + The time complexity of this implementation is O(1), since the maximum number of iterations in the + while loop is 13 (the length of the values array). The space complexity is also O(1), since we only + use a StringBuilder and two constant-size arrays to store the Roman numerals and values. +*/ public static String intToRoman(int num) { // Create two arrays to store the Roman numerals and their corresponding values String[] romanNumerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; From 0592777d3c6b7665686def5085fbed852385d3b7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Apr 2023 19:32:30 +0530 Subject: [PATCH 0701/1894] add heading --- Hash Table/integer_to_roman.java | 1 + 1 file changed, 1 insertion(+) diff --git a/Hash Table/integer_to_roman.java b/Hash Table/integer_to_roman.java index 03c59f93..73c0fcdc 100644 --- a/Hash Table/integer_to_roman.java +++ b/Hash Table/integer_to_roman.java @@ -1,3 +1,4 @@ +// Integer to Roman /* Here, we create two arrays to store the Roman numerals and their corresponding values. We then use a StringBuilder to build the resulting Roman numeral string. We use a while loop to iterate through From 5dbf79e6bc4d5e0915a26e1d9e23e20692569638 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:52:47 +0530 Subject: [PATCH 0702/1894] add best time to buy and sell stock in go --- .../best_time_to_buy_and_sell_stock.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Dynamic Programming/best_time_to_buy_and_sell_stock.go diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.go b/Dynamic Programming/best_time_to_buy_and_sell_stock.go new file mode 100644 index 00000000..f7e18504 --- /dev/null +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "math" +) + +func maxProfit(prices []int) int { + minPrice := math.MaxInt32 // Initialize minimum price to maximum integer value + maxProfit := 0 // Initialize maximum profit to 0 + for _, price := range prices { + if price < minPrice { + minPrice = price // Update minimum price + } else if price-minPrice > maxProfit { + maxProfit = price - minPrice // Update maximum profit + } + } + return maxProfit // Return maximum profit +} + +func main() { + prices := []int{7, 1, 5, 3, 6, 4} + fmt.Println(maxProfit(prices)) // Output: 5 +} \ No newline at end of file From 63e21010bd9e6cce5e92d6266e137056cbe19416 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:53:47 +0530 Subject: [PATCH 0703/1894] add description --- .../best_time_to_buy_and_sell_stock.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.go b/Dynamic Programming/best_time_to_buy_and_sell_stock.go index f7e18504..13666c4d 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.go +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.go @@ -1,3 +1,14 @@ +// Best Time to buy and sell stock +/* + Explanation: + We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. + We loop through the prices array, and for each price: + If the price is less than the current minimum price, we update the minimum price. + Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. + Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit +*/ package main import ( From a6a921a8fc9acd4f34bf855f50241dd77e322d40 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:55:00 +0530 Subject: [PATCH 0704/1894] modify best time to buy and sell stocks in c++ --- .../best_time_to_buy_and_sell_stock.cpp | 64 +++++++++---------- 1 file changed, 30 insertions(+), 34 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp index a3be1898..4b9b66ca 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -1,44 +1,40 @@ +// Best Time to buy and sell stock /* - You are given an array prices where prices[i] is the price of a given stock on the ith day. - You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. - Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. - - Example 1: - Input: prices = [7,1,5,3,6,4] - Output: 5 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. - - Example 2: - Input: prices = [7,6,4,3,1] - Output: 0 - Explanation: In this case, no transactions are done and the max profit = 0. - - Constraints: - 1 <= prices.length <= 105 - 0 <= prices[i] <= 104 + Explanation: + We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. + We loop through the prices array, and for each price: + If the price is less than the current minimum price, we update the minimum price. + Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. + Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ - #include -#include #include +#include // for INT_MIN + using namespace std; - -int maxProfit(vector& prices) -{ - int minElement = prices[0], maxDiff = 0; - for (int i = 1; i < prices.size(); i++) { - - minElement = min(minElement, prices[i]); - maxDiff = max(maxDiff, prices[i] - minElement); + +int maxProfit(vector& prices) { + int minPrice = INT_MAX; // initialize to maximum value to start with + int maxProfit = 0; // initialize to 0 + + for (int i = 0; i < prices.size(); i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; // update minimum price seen so far + } else if (prices[i] - minPrice > maxProfit) { + maxProfit = prices[i] - minPrice; // update maximum profit seen so far + } } - return maxDiff; + + return maxProfit; } -int main() -{ - vector prices = { 7, 1, 5, 3, 6, 4 }; - int maxProfitEarned = maxProfit(prices); - cout << maxProfitEarned << endl; +int main() { + // example usage + vector prices {7, 1, 5, 3, 6, 4}; + int max_profit = maxProfit(prices); + cout << "Max profit: " << max_profit << endl; + return 0; } From e685c96cfc9c4d91fb9fa1281eb192cf44c5da3e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:56:57 +0530 Subject: [PATCH 0705/1894] modify best time to buy and sell stock in java --- .../best_time_to_buy_and_sell_stock.java | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.java b/Dynamic Programming/best_time_to_buy_and_sell_stock.java index 2316d8c5..7de3b1d1 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.java +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.java @@ -1,39 +1,39 @@ +// Best Time to buy and sell stock /* - You are given an array prices where prices[i] is the price of a given stock on the ith day. - You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. - Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. - - Example 1: - Input: prices = [7,1,5,3,6,4] - Output: 5 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. - - Example 2: - Input: prices = [7,6,4,3,1] - Output: 0 - Explanation: In this case, no transactions are done and the max profit = 0. - - Constraints: - 1 <= prices.length <= 105 - 0 <= prices[i] <= 104 + Explanation: + We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. + We loop through the prices array, and for each price: + If the price is less than the current minimum price, we update the minimum price. + Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. + Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ - -class Solution { +public class Solution { public int maxProfit(int[] prices) { - int minElement = prices[0]; - int maxDiff = 0; - int size = prices.length; - for (int i = 0; i < size; i++){ - minElement = Math.min(prices[i], minElement); - maxDiff = Math.max(prices[i] - minElement, maxDiff); - } - return maxDiff; + // Initialize variables to track the minimum price seen so far and the maximum profit + int minPrice = Integer.MAX_VALUE; + int maxProfit = 0; + + // Loop through the prices array + for (int i = 0; i < prices.length; i++) { + // If the current price is less than the minimum price seen so far, update the minimum price + if (prices[i] < minPrice) { + minPrice = prices[i]; + } + // If the difference between the current price and the minimum price is greater than the maximum profit seen so far, update the maximum profit + else if (prices[i] - minPrice > maxProfit) { + maxProfit = prices[i] - minPrice; + } + } + + return maxProfit; // Return the maximum profit } - + public static void main(String[] args) { - Solution solution = new Solution(); int[] prices = {7, 1, 5, 3, 6, 4}; - System.out.println(solution.maxProfit(prices)); + int maxProfit = maxProfit(prices); + System.out.println("Max Profit: " + maxProfit); } } + From b4b24e5a8c84439c3d09b37e277e685c7ba7eaa0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:59:06 +0530 Subject: [PATCH 0706/1894] modify best time to buy and sell stock in python --- .../best_time_to_buy_and_sell_stock.py | 56 ++++++------------- 1 file changed, 18 insertions(+), 38 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index 370ca79c..8927a7b6 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -1,50 +1,30 @@ +# Best Time to buy and sell stock ''' - You are given an array prices where prices[i] is the price of a given stock on the ith day. - You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. - Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. - - Example 1: - Input: prices = [7,1,5,3,6,4] - Output: 5 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. - - Example 2: - Input: prices = [7,6,4,3,1] - Output: 0 - Explanation: In this case, no transactions are done and the max profit = 0. - - Constraints: - 1 <= prices.length <= 105 - 0 <= prices[i] <= 104 + The function maxProfit takes a list of integers prices and returns the maximum profit that can be + made from buying and selling the stock represented by prices. The function works by initializing + the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. It then loops + through the prices, updating the minimum price if the current price is less than the current minimum + price, and updating the maximum profit if the difference between the current price and the minimum + price is greater than the current maximum profit. Finally, it returns the maximum profit. ''' -def maxProfit(prices): - minElement = 10000 - maxDiff = 0 - for i in range(len(prices)): - minElement = min(prices[i], minElement) - maxDiff = max(prices[i]-minElement, maxDiff) - - return maxDiff - -prices = [7,1,5,3,6,4] -print(maxProfit(prices)) - -# Optimize solution -def max_profit(prices): - min_price = prices[0] +def maxProfit(prices: List[int]) -> int: + # initialize the minimum price as maximum integer value + min_price = sys.maxsize + + # initialize the maximum profit as 0 max_profit = 0 + # loop through the prices for price in prices: + # if the current price is less than the minimum price, update the minimum price if price < min_price: min_price = price + # else if the difference between the current price and the minimum price is greater than the maximum profit, + # update the maximum profit elif price - min_price > max_profit: max_profit = price - min_price - + + # return the maximum profit return max_profit - - -print(maxProfit([7,1,5,3,6,4])) # 5 -print(maxProfit([7,6,4,3,1]))# 0 \ No newline at end of file From 67e828547a6c375072ec7d2407459073a6f834be Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 19:59:56 +0530 Subject: [PATCH 0707/1894] call maxProfit function --- Dynamic Programming/best_time_to_buy_and_sell_stock.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index 8927a7b6..d98ac3e2 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -28,3 +28,7 @@ def maxProfit(prices: List[int]) -> int: # return the maximum profit return max_profit + +prices = [7, 1, 5, 3, 6, 4] +profit = maxProfit(prices) +print(profit) # Output: 5 \ No newline at end of file From 3204ffba7de5c91a91d9a72f4a6d2997a4e52cd4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 20:02:21 +0530 Subject: [PATCH 0708/1894] modify best time to buy and sell stocks in js --- .../best_time_to_buy_and_sell_stock.js | 61 ++++++++----------- .../best_time_to_buy_and_sell_stock.py | 5 +- 2 files changed, 30 insertions(+), 36 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.js b/Dynamic Programming/best_time_to_buy_and_sell_stock.js index ac3572c7..e400ddd2 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.js +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.js @@ -1,39 +1,32 @@ +// Best Time to buy and sell stock /* - You are given an array prices where prices[i] is the price of a given stock on the ith day. - You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. - Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. - - Example 1: - Input: prices = [7,1,5,3,6,4] - Output: 5 - Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. - Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. - - Example 2: - Input: prices = [7,6,4,3,1] - Output: 0 - Explanation: In this case, no transactions are done and the max profit = 0. - - Constraints: - 1 <= prices.length <= 105 - 0 <= prices[i] <= 104 + Explanation: + We start by initializing the minimum price to the maximum integer value and the maximum profit to 0. + We loop through the prices array, and for each price: + If the price is less than the current minimum price, we update the minimum price. + Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. + Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ -function maxProfit(prices) { - - let minPrice = prices[0]; - let maxProfit = 0; - - for (let i = 1; i < prices.length; i++) { - if (prices[i] < minPrice) { - minPrice = prices[i]; - } else if (prices[i] - minPrice > maxProfit) { - maxProfit = prices[i] - minPrice; - } +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function (prices) { + let minPrice = Infinity; // keep track of minimum price seen so far + let maxProfit = 0; // keep track of maximum profit seen so far + + for (let i = 0; i < prices.length; i++) { + if (prices[i] < minPrice) { + minPrice = prices[i]; // update minimum price seen so far + } else if (prices[i] - minPrice > maxProfit) { + maxProfit = prices[i] - minPrice; // update maximum profit seen so far } - - return maxProfit; -} + } -console.log(maxProfit([7,1,5,3,6,4]))// 5 -console.log(maxProfit([7,6,4,3,1]))// 0 + return maxProfit; +}; +const prices = [7, 1, 5, 3, 6, 4]; +console.log(maxProfit(prices)); // Output: 5 diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index d98ac3e2..07d84191 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -2,8 +2,9 @@ ''' The function maxProfit takes a list of integers prices and returns the maximum profit that can be made from buying and selling the stock represented by prices. The function works by initializing - the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. It then loops - through the prices, updating the minimum price if the current price is less than the current minimum + the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. + + It then loops through the prices, updating the minimum price if the current price is less than the current minimum price, and updating the maximum profit if the difference between the current price and the minimum price is greater than the current maximum profit. Finally, it returns the maximum profit. ''' From 73563c5a0a584425c95bac4fbb893f2e16ec04d0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 20:02:48 +0530 Subject: [PATCH 0709/1894] add time and space complexity --- Dynamic Programming/best_time_to_buy_and_sell_stock.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index 07d84191..046a7c4a 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -3,10 +3,13 @@ The function maxProfit takes a list of integers prices and returns the maximum profit that can be made from buying and selling the stock represented by prices. The function works by initializing the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. - + It then loops through the prices, updating the minimum price if the current price is less than the current minimum price, and updating the maximum profit if the difference between the current price and the minimum price is greater than the current maximum profit. Finally, it returns the maximum profit. + + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit ''' From 95d92113f74685e873453b54839c8ad149336b22 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 20:03:21 +0530 Subject: [PATCH 0710/1894] add line break --- Dynamic Programming/best_time_to_buy_and_sell_stock.cpp | 1 + Dynamic Programming/best_time_to_buy_and_sell_stock.go | 1 + Dynamic Programming/best_time_to_buy_and_sell_stock.java | 1 + Dynamic Programming/best_time_to_buy_and_sell_stock.js | 1 + 4 files changed, 4 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp index 4b9b66ca..a03f9074 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -6,6 +6,7 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.go b/Dynamic Programming/best_time_to_buy_and_sell_stock.go index 13666c4d..916b5949 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.go +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.go @@ -6,6 +6,7 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.java b/Dynamic Programming/best_time_to_buy_and_sell_stock.java index 7de3b1d1..1300a1cd 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.java +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.java @@ -6,6 +6,7 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.js b/Dynamic Programming/best_time_to_buy_and_sell_stock.js index e400ddd2..72cbd63b 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.js +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.js @@ -6,6 +6,7 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ From e345be047273d8078ccc0165dd583613eefd0c81 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 20:18:58 +0530 Subject: [PATCH 0711/1894] add roman to integer in go --- Hash Table/roman_to_integer.go | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Hash Table/roman_to_integer.go diff --git a/Hash Table/roman_to_integer.go b/Hash Table/roman_to_integer.go new file mode 100644 index 00000000..6326d906 --- /dev/null +++ b/Hash Table/roman_to_integer.go @@ -0,0 +1,48 @@ +package main + +import ( + "fmt" +) + +func romanToInt(s string) int { + // Create a map to store the integer value of each Roman numeral + romanToIntMap := map[byte]int{ + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000, + } + + // Initialize the result variable to 0 + result := 0 + + // Iterate over the input string + for i := 0; i < len(s); i++ { + // Get the integer value of the current Roman numeral + val := romanToIntMap[s[i]] + + // Check if the next Roman numeral is greater than the current one + if i+1 < len(s) && romanToIntMap[s[i+1]] > val { + // If the next Roman numeral is greater, subtract the current value from the result + result -= val + } else { + // If the next Roman numeral is not greater, add the current value to the result + result += val + } + } + + // Return the final result + return result +} + + + +func main() { + input := "IV" + output := romanToInt(input) + fmt.Printf("Roman numeral %s converted to integer is: %d\n", input, output) + +} \ No newline at end of file From fb4f10fc9d8df1b174fb0d8931ec7412b5ad740f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Apr 2023 20:20:18 +0530 Subject: [PATCH 0712/1894] add time and space complexity --- Hash Table/roman_to_integer.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Hash Table/roman_to_integer.go b/Hash Table/roman_to_integer.go index 6326d906..4759ab0b 100644 --- a/Hash Table/roman_to_integer.go +++ b/Hash Table/roman_to_integer.go @@ -1,3 +1,20 @@ +// Roman To Integer +/* + This implementation converts a given Roman numeral string to its corresponding integer value. + The implementation uses a map to store the integer value of each Roman numeral, and then + iterates over the input string, checking if the next Roman numeral is greater than the + current one to determine whether to add or subtract the current value from the result. + The time complexity of this implementation is O(n), where n is the length of the input string, + since it iterates over the string only once. The space complexity is O(1), since the + implementation only uses a constant amount of extra space to store the map and result variable. + + Time complexity: O(n), where n is the length of the input string. The program iterates through + each character in the string once and performs a constant number of operations for each character. + Therefore, the time complexity is linear in the length of the input string. + + Space complexity: O(1). The program uses a constant amount of extra space to store the result + and the current and previous values. Therefore, the space complexity is constant, or O(1). +*/ package main import ( From 8bad92b0e67428f5f8485d67fd16d581d39846ae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:36:21 +0530 Subject: [PATCH 0713/1894] add group anagrams in go --- Hash Table/group_anagrams.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Hash Table/group_anagrams.go diff --git a/Hash Table/group_anagrams.go b/Hash Table/group_anagrams.go new file mode 100644 index 00000000..33a96b72 --- /dev/null +++ b/Hash Table/group_anagrams.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "sort" +) + +func groupAnagrams(strs []string) [][]string { + // Create a map to store anagrams and their grouped strings + anagramMap := make(map[string][]string) + + // Loop through each string in the input array + for _, str := range strs { + // Sort the string to create a unique key for each anagram + sortedStr := sortString(str) + // Add the string to its corresponding group in the anagramMap + anagramMap[sortedStr] = append(anagramMap[sortedStr], str) + } + + // Create a 2D slice to store the grouped anagrams + groups := make([][]string, 0, len(anagramMap)) + + // Loop through the anagramMap and append each group of anagrams to the groups slice + for _, group := range anagramMap { + groups = append(groups, group) + } + + return groups +} + +// Helper function to sort a string alphabetically +func sortString(s string) string { + sBytes := []byte(s) + sort.Slice(sBytes, func(i, j int) bool { return sBytes[i] < sBytes[j] }) + return string(sBytes) +} From a2c7acec4278115847b5815f59275d9000b4234d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:36:34 +0530 Subject: [PATCH 0714/1894] add main func --- Hash Table/group_anagrams.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Hash Table/group_anagrams.go b/Hash Table/group_anagrams.go index 33a96b72..56960342 100644 --- a/Hash Table/group_anagrams.go +++ b/Hash Table/group_anagrams.go @@ -34,3 +34,10 @@ func sortString(s string) string { sort.Slice(sBytes, func(i, j int) bool { return sBytes[i] < sBytes[j] }) return string(sBytes) } +func main() { + strs := []string{"eat", "tea", "tan", "ate", "nat", "bat"} + groups := groupAnagrams(strs) + for _, group := range groups { + fmt.Println(group) + } +} From f47ee1d73703fd168c203ae29e516e49458720c0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:37:36 +0530 Subject: [PATCH 0715/1894] add heading --- Hash Table/group_anagrams.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Hash Table/group_anagrams.go b/Hash Table/group_anagrams.go index 56960342..f1cf8a83 100644 --- a/Hash Table/group_anagrams.go +++ b/Hash Table/group_anagrams.go @@ -1,3 +1,4 @@ +// Group Anagrams package main import ( From a364b943c495cd18cffe99d390ebaafb6272821a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:38:08 +0530 Subject: [PATCH 0716/1894] add time and space complexity --- Hash Table/group_anagrams.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Hash Table/group_anagrams.go b/Hash Table/group_anagrams.go index f1cf8a83..5d53c254 100644 --- a/Hash Table/group_anagrams.go +++ b/Hash Table/group_anagrams.go @@ -1,4 +1,9 @@ // Group Anagrams +/* + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + + The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. +*/ package main import ( From cc51c5b96036c07438226c2d829faf30c367995d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:41:48 +0530 Subject: [PATCH 0717/1894] add description --- Hash Table/group_anagrams.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Hash Table/group_anagrams.go b/Hash Table/group_anagrams.go index 5d53c254..4de5b952 100644 --- a/Hash Table/group_anagrams.go +++ b/Hash Table/group_anagrams.go @@ -1,5 +1,28 @@ // Group Anagrams /* + The program takes a slice of strings as input, where each string is an element in the slice. + The goal is to group the strings into separate groups where each group contains only anagrams of each other. + + The first step in the program is to create a map where the keys are strings and the values are slices of strings. + This map will be used to store the groups of anagrams. + + Next, the program loops through each string in the input slice. For each string, the program converts + it to a slice of bytes, sorts the bytes in ascending order, and then converts the sorted slice of bytes back into a string. + This sorted string is used as the key to the map. + + If the key already exists in the map, the string is added to the slice of values associated with that key. + If the key doesn't exist, a new key-value pair is created with the key being the sorted string and the value + being a new slice containing only the current string. + + Once all the strings have been processed, the program loops through the map and appends the slice of values + associated with each key to the output slice. This output slice contains slices of strings, where each slice + is a group of anagrams. + + Finally, the program returns the output slice. + + Overall, the program uses the fact that anagrams have the same set of characters (and thus, the same sorted order of characters) \ + to group the input strings efficiently. + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. From 2405645c7d9fc439d607192b8f8bb82a313a4050 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:49:46 +0530 Subject: [PATCH 0718/1894] add group anagrams in c++ --- Hash Table/group_anagrams.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Hash Table/group_anagrams.cpp diff --git a/Hash Table/group_anagrams.cpp b/Hash Table/group_anagrams.cpp new file mode 100644 index 00000000..d8d83580 --- /dev/null +++ b/Hash Table/group_anagrams.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +using namespace std; + +vector> groupAnagrams(vector& strs) { + unordered_map> mp; // create an unordered map to store anagrams + + // iterate through each string in the input vector + for (string s : strs) { + string t = s; // create a copy of the current string + sort(t.begin(), t.end()); // sort the characters in the copy + mp[t].push_back(s); // add the original string to the corresponding anagram group + } + + vector> res; // create a vector to store the anagram groups + for (auto p : mp) { // iterate through the unordered map + res.push_back(p.second); // add the anagram group to the result vector + } + + return res; // return the result vector containing all the anagram groups +} + From 695f16a35a0579f0b15b6559a442b038d495dd14 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:49:55 +0530 Subject: [PATCH 0719/1894] add main func --- Hash Table/group_anagrams.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Hash Table/group_anagrams.cpp b/Hash Table/group_anagrams.cpp index d8d83580..0dbabcba 100644 --- a/Hash Table/group_anagrams.cpp +++ b/Hash Table/group_anagrams.cpp @@ -23,3 +23,20 @@ vector> groupAnagrams(vector& strs) { return res; // return the result vector containing all the anagram groups } +int main() { + // create an example input vector + vector strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; + + // call the groupAnagrams function and store the result in the output vector + vector> output = groupAnagrams(strs); + + // iterate through the output vector and print each anagram group + for (vector group : output) { + for (string s : group) { + cout << s << " "; + } + cout << endl; + } + + return 0; +} From d5ad3340284c5ecb7999668e18f241ab8b9df782 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:50:37 +0530 Subject: [PATCH 0720/1894] add heading, time and space complexity --- Hash Table/group_anagrams.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Hash Table/group_anagrams.cpp b/Hash Table/group_anagrams.cpp index 0dbabcba..6e7dc820 100644 --- a/Hash Table/group_anagrams.cpp +++ b/Hash Table/group_anagrams.cpp @@ -1,3 +1,10 @@ +// Group Anagrams +/* + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + + The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. + +*/ #include #include #include From 60c91e7f1b4089d95efbc92c37223f81f7f637bc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:51:49 +0530 Subject: [PATCH 0721/1894] add description --- Hash Table/group_anagrams.cpp | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Hash Table/group_anagrams.cpp b/Hash Table/group_anagrams.cpp index 6e7dc820..012e44be 100644 --- a/Hash Table/group_anagrams.cpp +++ b/Hash Table/group_anagrams.cpp @@ -1,6 +1,24 @@ // Group Anagrams /* - The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + The function groupAnagrams takes a vector of strings strs as input and returns a vector of vectors of strings res, + where each inner vector contains a group of anagrams. + + We create an unordered map mp to store the anagram groups. The keys of the map are the sorted versions of the anagrams, + and the values are vectors containing the original strings that belong to that anagram group. + + We iterate through each string in the input vector strs, create a copy of the string t, sort the characters in the copy t, + and add the original string s to the corresponding anagram group in the unordered map mp. + + We create a vector res to store the anagram groups and iterate through the unordered map mp. For each anagram group in the map, + we add the corresponding vector of original strings to the res vector. + + We return the result vector res containing all the anagram groups. + + In the main function, we create an example input vector strs, call the groupAnagrams function and store the result in the + output vector output, and iterate through the output vector to print each anagram group. + + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the + length of the longest string in the array. This is due to the time complexity of sorting each string in the array. The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. From 5c29dc0e18fe0ece9e54da22641dc9f7cec0623f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:54:30 +0530 Subject: [PATCH 0722/1894] add group anagrams in python --- Hash Table/group_anagrams.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Hash Table/group_anagrams.py diff --git a/Hash Table/group_anagrams.py b/Hash Table/group_anagrams.py new file mode 100644 index 00000000..f28b022a --- /dev/null +++ b/Hash Table/group_anagrams.py @@ -0,0 +1,20 @@ +def groupAnagrams(strs): + # create a dictionary to store the groups of anagrams + groups = {} + + # iterate through each string in the list + for s in strs: + # sort the characters of the string to get its unique signature + # for example, "eat" and "ate" both have the same signature "aet" + sig = ''.join(sorted(s)) + + # check if the signature is already in the dictionary + # if not, add a new key-value pair with an empty list as the value + if sig not in groups: + groups[sig] = [] + + # append the current string to the list of its corresponding signature + groups[sig].append(s) + + # return the values of the dictionary as a list of lists + return list(groups.values()) From 5b1573288accace5c66b18b57736bf575fe3dc64 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:56:01 +0530 Subject: [PATCH 0723/1894] add description --- Hash Table/group_anagrams.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Hash Table/group_anagrams.py b/Hash Table/group_anagrams.py index f28b022a..3bd691f7 100644 --- a/Hash Table/group_anagrams.py +++ b/Hash Table/group_anagrams.py @@ -1,3 +1,23 @@ +# Group Anagrams +''' + The function groupAnagrams takes a list of strings as input and returns a list of lists, where each inner list + contains a group of anagrams from the input list. + + The function starts by creating an empty dictionary groups to store the groups of anagrams. The keys of the dictionary + will be the unique signatures of the anagrams, and the values will be lists of the actual anagrams. + + Then, the function iterates through each string s in the input list strs. For each string, it sorts the characters + of the string to get its unique signature sig. If the signature is not already in the dictionary, a new key-value pair + is added to the dictionary with the signature as the key and an empty list as the value. Finally, the current + string s is appended to the list of its corresponding signature in the dictionary. + + Once all the strings have been processed, the function returns the values of the dictionary as a list of lists, + where each inner list contains a group of anagrams from the input list. + + For example, if the input list is ["eat", "tea", "tan", "ate", "nat", "bat"], + the function will return [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], which + represents the three groups of anagrams: ['eat', 'tea', 'ate'], ['tan', 'nat'], and ['bat']. +''' def groupAnagrams(strs): # create a dictionary to store the groups of anagrams groups = {} From 1d1ab7ae764fa2bdcd32cc803393a7cf8552f7b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Apr 2023 22:56:29 +0530 Subject: [PATCH 0724/1894] add time and space complexity --- Hash Table/group_anagrams.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Hash Table/group_anagrams.py b/Hash Table/group_anagrams.py index 3bd691f7..0406cf09 100644 --- a/Hash Table/group_anagrams.py +++ b/Hash Table/group_anagrams.py @@ -17,6 +17,13 @@ For example, if the input list is ["eat", "tea", "tan", "ate", "nat", "bat"], the function will return [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], which represents the three groups of anagrams: ['eat', 'tea', 'ate'], ['tan', 'nat'], and ['bat']. + + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the + length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + + The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its + corresponding group of anagrams. + ''' def groupAnagrams(strs): # create a dictionary to store the groups of anagrams From e10fbd20a4b9a8b352edb1b7fb1a77b8a967b284 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:04:45 +0530 Subject: [PATCH 0725/1894] add group anagrams in js --- Hash Table/group_anagrams.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Hash Table/group_anagrams.js diff --git a/Hash Table/group_anagrams.js b/Hash Table/group_anagrams.js new file mode 100644 index 00000000..c9b7e2f1 --- /dev/null +++ b/Hash Table/group_anagrams.js @@ -0,0 +1,27 @@ +/** + * Given an array of strings, group anagrams together and return them as an array of arrays. + * + * @param {string[]} strs - The input array of strings. + * @returns {string[][]} - An array of arrays of anagrams. + */ +function groupAnagrams(strs) { + // Create an empty object to store groups of anagrams. + const anagramGroups = {}; + + // Loop through each string in the input array. + for (const str of strs) { + // Sort the characters of the string alphabetically and use the sorted string as a key. + const sortedStr = str.split("").sort().join(""); + + // If a group for the sorted string doesn't exist yet, create it as an empty array. + if (!anagramGroups[sortedStr]) { + anagramGroups[sortedStr] = []; + } + + // Add the original string to the group of anagrams. + anagramGroups[sortedStr].push(str); + } + + // Return the values of the anagram groups object as an array. + return Object.values(anagramGroups); +} From 16b2fc9d4837a229d41c19197b9512eec498d6f7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:04:58 +0530 Subject: [PATCH 0726/1894] add sample io --- Hash Table/group_anagrams.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Hash Table/group_anagrams.js b/Hash Table/group_anagrams.js index c9b7e2f1..69c48c69 100644 --- a/Hash Table/group_anagrams.js +++ b/Hash Table/group_anagrams.js @@ -25,3 +25,6 @@ function groupAnagrams(strs) { // Return the values of the anagram groups object as an array. return Object.values(anagramGroups); } + +const words = ["eat", "tea", "tan", "ate", "nat", "bat"]; +console.log(groupAnagrams(words)); From 0f0122d52f106055649ba526074337bec7a04253 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:05:57 +0530 Subject: [PATCH 0727/1894] add description --- Hash Table/group_anagrams.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Hash Table/group_anagrams.js b/Hash Table/group_anagrams.js index 69c48c69..3d5c4691 100644 --- a/Hash Table/group_anagrams.js +++ b/Hash Table/group_anagrams.js @@ -1,3 +1,20 @@ +/* + The function groupAnagrams takes an array of strings strs as input, and returns an array of arrays of anagrams. + The approach taken is to sort the characters of each string alphabetically, and group strings with the same sorted form together. + The resulting groups are stored in an object anagramGroups whose keys are the sorted strings and whose values are arrays of the original strings. + Finally, the values of the anagramGroups object are returned as an array. + + To accomplish the sorting and grouping, the split, sort, and join methods are used. First, each string is split into an array of its characters + using the split method. Then, the sort method is used to sort the characters alphabetically. Finally, the join method is used to combine the + sorted characters back into a string. This sorted string is used as the key for grouping the anagrams in the anagramGroups object. + + The for...of loop is used to iterate over each string in the input array. Inside the loop, the sorted form of the string is computed, + and a check is made to see if a group for the sorted form already exists in the anagramGroups object. If it doesn't, a new group is + created as an empty array. Then, the original string is added to the appropriate group in the anagramGroups object using the push method. + + Finally, the Object.values method is used to extract the arrays of anagrams from the anagramGroups object, and these arrays are + returned as the final result. +*/ /** * Given an array of strings, group anagrams together and return them as an array of arrays. * From b31e637b08ff7a79f9fb14bddfedbcfaefee4a41 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:06:14 +0530 Subject: [PATCH 0728/1894] add heading --- Hash Table/group_anagrams.js | 1 + 1 file changed, 1 insertion(+) diff --git a/Hash Table/group_anagrams.js b/Hash Table/group_anagrams.js index 3d5c4691..486bf234 100644 --- a/Hash Table/group_anagrams.js +++ b/Hash Table/group_anagrams.js @@ -1,3 +1,4 @@ +// Group Anagrams /* The function groupAnagrams takes an array of strings strs as input, and returns an array of arrays of anagrams. The approach taken is to sort the characters of each string alphabetically, and group strings with the same sorted form together. From ea6ea5dc4ae3032575941859b830b85644ec2d01 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:06:44 +0530 Subject: [PATCH 0729/1894] add time and space complexity --- Hash Table/group_anagrams.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Hash Table/group_anagrams.js b/Hash Table/group_anagrams.js index 486bf234..f3092830 100644 --- a/Hash Table/group_anagrams.js +++ b/Hash Table/group_anagrams.js @@ -15,6 +15,11 @@ Finally, the Object.values method is used to extract the arrays of anagrams from the anagramGroups object, and these arrays are returned as the final result. + + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + + The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. + */ /** * Given an array of strings, group anagrams together and return them as an array of arrays. From 748bdaae7ca3bad0004323bef875b8b980e06d94 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:08:37 +0530 Subject: [PATCH 0730/1894] add group anagrams in java --- Hash Table/group_anagrams.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Hash Table/group_anagrams.java diff --git a/Hash Table/group_anagrams.java b/Hash Table/group_anagrams.java new file mode 100644 index 00000000..7e7d3c5f --- /dev/null +++ b/Hash Table/group_anagrams.java @@ -0,0 +1,29 @@ +import java.util.*; + +public class GroupAnagrams { + + public List> groupAnagrams(String[] strs) { + // Create a HashMap to store the groups of anagrams + Map> anagramGroups = new HashMap<>(); + + // Loop through each string in the input array + for (String str : strs) { + // Convert the string to a char array, sort it, and convert it back to a string + char[] chars = str.toCharArray(); + Arrays.sort(chars); + String sorted = new String(chars); + + // If the sorted string is not in the map, add it with an empty list as its value + if (!anagramGroups.containsKey(sorted)) { + anagramGroups.put(sorted, new ArrayList()); + } + + // Add the original string to the list of its anagram group + anagramGroups.get(sorted).add(str); + } + + // Return a list of the anagram groups + return new ArrayList<>(anagramGroups.values()); + } + +} From 8df73d91850b3c30a4f4a95a60661c84e8c16345 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:08:49 +0530 Subject: [PATCH 0731/1894] add main func --- Hash Table/group_anagrams.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Hash Table/group_anagrams.java b/Hash Table/group_anagrams.java index 7e7d3c5f..519d0b91 100644 --- a/Hash Table/group_anagrams.java +++ b/Hash Table/group_anagrams.java @@ -26,4 +26,18 @@ public List> groupAnagrams(String[] strs) { return new ArrayList<>(anagramGroups.values()); } + public static void main(String[] args) { + GroupAnagrams ga = new GroupAnagrams(); + + // Example input + String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; + + // Group the anagrams + List> groups = ga.groupAnagrams(strs); + + // Print the groups + for (List group : groups) { + System.out.println(group); + } + } } From bfa47a173b52d18251f4cd4ff883bf7b780bb6c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:09:34 +0530 Subject: [PATCH 0732/1894] add description --- Hash Table/group_anagrams.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Hash Table/group_anagrams.java b/Hash Table/group_anagrams.java index 519d0b91..21635ed8 100644 --- a/Hash Table/group_anagrams.java +++ b/Hash Table/group_anagrams.java @@ -1,3 +1,19 @@ +/* + Explanation: + + The groupAnagrams method takes an array of strings and groups them into a list of anagram groups. To accomplish this, + the method first creates a HashMap called anagramGroups to store the groups of anagrams. + + For each string in the input array, the method converts the string to a character array, sorts the array, + and converts it back to a string. This sorted string serves as the key for the anagramGroups map. If the sorted + string is not already in the map, the method adds it with an empty list as its value. Then, the original string + is added to the list of its corresponding anagram group. + + Finally, the method returns a list of the values in the anagramGroups map, which is a list of the anagram groups. + + In the main method, we create an instance of the GroupAnagrams class and call the groupAnagrams method on an example input array. + We then print out the resulting list of anagram groups. +*/ import java.util.*; public class GroupAnagrams { From 8ee3d02d9333cbd3cc5daae2632d65e01ed904a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:10:04 +0530 Subject: [PATCH 0733/1894] add time and space complexity --- Hash Table/group_anagrams.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Hash Table/group_anagrams.java b/Hash Table/group_anagrams.java index 21635ed8..c6523e35 100644 --- a/Hash Table/group_anagrams.java +++ b/Hash Table/group_anagrams.java @@ -1,6 +1,7 @@ +// Group Anagrams /* Explanation: - + The groupAnagrams method takes an array of strings and groups them into a list of anagram groups. To accomplish this, the method first creates a HashMap called anagramGroups to store the groups of anagrams. @@ -13,6 +14,11 @@ In the main method, we create an instance of the GroupAnagrams class and call the groupAnagrams method on an example input array. We then print out the resulting list of anagram groups. + + The time complexity of this implementation is O(n * k log k), where n is the length of the input array and k is the length of the longest string in the array. This is due to the time complexity of sorting each string in the array. + + The space complexity of this implementation is O(n * k), as we need to store each string in the map along with its corresponding group of anagrams. + */ import java.util.*; From cae31b624c820ed877f054d828d97976ba4b1813 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:17:20 +0530 Subject: [PATCH 0734/1894] ad floyds cycle detection --- Linked List/floyds_cycle_detection.go | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Linked List/floyds_cycle_detection.go diff --git a/Linked List/floyds_cycle_detection.go b/Linked List/floyds_cycle_detection.go new file mode 100644 index 00000000..9d4e98d1 --- /dev/null +++ b/Linked List/floyds_cycle_detection.go @@ -0,0 +1,28 @@ +// Definition for singly-linked list. +package main +type Node struct { + value int + next *Node +} + + +// DetectCycle detects if there's a cycle in a linked list using Floyd's cycle detection algorithm +func DetectCycle(head *Node) bool { + // Initialize slow and fast pointers + slow, fast := head, head + + // Move slow and fast pointers until they meet or fast pointer reaches end of the list + for fast != nil && fast.next != nil { + slow = slow.next + fast = fast.next.next + + // If slow and fast pointers meet, there's a cycle + if slow == fast { + return true + } + } + + // If fast pointer reaches end of the list, there's no cycle + return false +} + From 95e6986a37902b37c7a2d57c9b524d5253361984 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:17:30 +0530 Subject: [PATCH 0735/1894] add main func --- Linked List/floyds_cycle_detection.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Linked List/floyds_cycle_detection.go b/Linked List/floyds_cycle_detection.go index 9d4e98d1..95a356f3 100644 --- a/Linked List/floyds_cycle_detection.go +++ b/Linked List/floyds_cycle_detection.go @@ -1,5 +1,7 @@ // Definition for singly-linked list. package main + +import "fmt" type Node struct { value int next *Node @@ -26,3 +28,20 @@ func DetectCycle(head *Node) bool { return false } +func main() { + // Create a linked list with a cycle + head := &Node{value: 1} + node2 := &Node{value: 2} + node3 := &Node{value: 3} + node4 := &Node{value: 4} + node5 := &Node{value: 5} + head.next = node2 + node2.next = node3 + node3.next = node4 + node4.next = node5 + node5.next = node2 // Create a cycle + + // Detect cycle in the linked list + hasCycle := DetectCycle(head) + fmt.Println(hasCycle) // Output: true +} From a4a964606552e6926a247957c358e060e65c5810 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:19:01 +0530 Subject: [PATCH 0736/1894] add explanation --- Linked List/floyds_cycle_detection.go | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Linked List/floyds_cycle_detection.go b/Linked List/floyds_cycle_detection.go index 95a356f3..f2a518de 100644 --- a/Linked List/floyds_cycle_detection.go +++ b/Linked List/floyds_cycle_detection.go @@ -1,7 +1,26 @@ -// Definition for singly-linked list. +// Floyds Cycle Detection +/* + Explanation: + The Floyd's cycle detection algorithm is a two-pointer algorithm used to detect if a linked list has a + cycle. It works by initializing two pointers, slow and fast, both pointing to the head of the linked list. + Then, it moves the slow pointer by one step and the fast pointer by two steps. If there is a cycle in the linked list, + the fast pointer will eventually catch up to the slow pointer. If there is no cycle, the fast pointer will reach the + end of the linked list. This algorithm has a time complexity of O(n) and a space complexity of O(1). + + In the implementation above, we define a Node struct to represent a node in the linked list. + The hasCycle function takes the head of the linked list as input and returns a boolean indicating + whether the linked list has a cycle or not. We initialize two pointers, slow and fast, both pointing + to the head of the linked list. We then loop through the linked list while the fast pointer is not + null and the next of the fast pointer is not null. In each iteration, we move the slow pointer + by one step and the fast pointer by two steps. If the slow and fast pointers meet, we know there + is a cycle and we return true. Otherwise, we continue the loop until the end of the linked list and return false. +*/ + package main import "fmt" + +// Definition for singly-linked list. type Node struct { value int next *Node @@ -9,7 +28,7 @@ type Node struct { // DetectCycle detects if there's a cycle in a linked list using Floyd's cycle detection algorithm -func DetectCycle(head *Node) bool { +func hasCycle(head *Node) bool { // Initialize slow and fast pointers slow, fast := head, head @@ -42,6 +61,6 @@ func main() { node5.next = node2 // Create a cycle // Detect cycle in the linked list - hasCycle := DetectCycle(head) + hasCycle := hasCycle(head) fmt.Println(hasCycle) // Output: true } From 510036b9308e8ca7a2e217285f5245690745899a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Apr 2023 22:19:52 +0530 Subject: [PATCH 0737/1894] add time and space complexity --- Linked List/floyds_cycle_detection.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Linked List/floyds_cycle_detection.go b/Linked List/floyds_cycle_detection.go index f2a518de..6f20b922 100644 --- a/Linked List/floyds_cycle_detection.go +++ b/Linked List/floyds_cycle_detection.go @@ -14,6 +14,13 @@ null and the next of the fast pointer is not null. In each iteration, we move the slow pointer by one step and the fast pointer by two steps. If the slow and fast pointers meet, we know there is a cycle and we return true. Otherwise, we continue the loop until the end of the linked list and return false. + + The time complexity of Floyd's cycle detection algorithm is O(n), where n is the number of nodes in the linked list. + This is because in the worst case, we would need to traverse the entire linked list twice: once to reach the point + where the cycle begins, and once more to detect the cycle. + + The space complexity of the algorithm is O(1), as we are only using a few constant extra variables to perform + the detection, regardless of the size of the linked list. */ package main From 840b31d809e56d00e9f426bded65fd5aca74857f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:41:27 +0530 Subject: [PATCH 0738/1894] modify validd palindrome in py --- Strings/valid_pallindrome2.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py index 2e7ecace..5b15e718 100644 --- a/Strings/valid_pallindrome2.py +++ b/Strings/valid_pallindrome2.py @@ -13,23 +13,20 @@ def valid_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 + # iterate over the string from left and right at the same time while left < right: + # if the characters at the left and right indices are not the same if s[left] != s[right]: - # Check if deleting either left or right char will create a palindrome - return is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1) - left += 1 - right -= 1 + # we need to check if removing one of them makes the string a palindrome + # we try removing the left character first + left_removed = s[left:right] + right_removed = s[left+1:right+1] + # if either of the substrings after removal is a palindrome, then the original string is also a palindrome + return left_removed == left_removed[::-1] or right_removed == right_removed[::-1] - return True - -def is_palindrome(s: str, left: int, right: int) -> bool: - while left < right: - if s[left] != s[right]: - return False + # move to the next pair of characters left += 1 right -= 1 + + # if we have checked the whole string and haven't returned yet, it's a palindrome return True - -print(valid_palindrome("aba")) # True -print(valid_palindrome("abca")) # True -print(valid_palindrome("abc")) # False \ No newline at end of file From 92d146f822ddcb6021b50ddf87bb48e4d9d0fd90 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:42:48 +0530 Subject: [PATCH 0739/1894] addd explanation --- Strings/valid_pallindrome2.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py index 5b15e718..c593ada7 100644 --- a/Strings/valid_pallindrome2.py +++ b/Strings/valid_pallindrome2.py @@ -1,13 +1,17 @@ ''' - Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + Explanation: + The function valid_palindrome takes a string s as input and returns a boolean indicating whether the + string can be a valid palindrome by removing at most one character from it. - Constraints: string.length The string only consists of English letters + To check if the string can be a valid palindrome, we start by iterating over the string from both the + left and right ends at the same time. If we encounter two characters that are not the same, we need to + check if removing one of them would make the string a palindrome. We try removing the left character + first and create two new substrings - one with the left character removed and one with the right character removed. + We then check if either of the substrings is a palindrome. If either of the substrings is a palindrome, + then the original string can be a palindrome by removing the corresponding character. If neither of + the substrings is a palindrome, then the original string cannot be a palindrome even by removing a character. - Sample Input : "madame" - Output : True - - Sample Input : "masdasd" - Output : False + If we have checked the whole string and haven't returned yet, it means that the original string is a palindrome. ''' # using two-pointer Technique def valid_palindrome(s: str) -> bool: From 1ec84ad359b37fd1e50f743d046e7c64fc8309e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:43:15 +0530 Subject: [PATCH 0740/1894] add time and space complexity --- Strings/valid_pallindrome2.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py index c593ada7..ccdab60f 100644 --- a/Strings/valid_pallindrome2.py +++ b/Strings/valid_pallindrome2.py @@ -12,6 +12,13 @@ the substrings is a palindrome, then the original string cannot be a palindrome even by removing a character. If we have checked the whole string and haven't returned yet, it means that the original string is a palindrome. + + The time complexity of the given function is O(n), where n is the length of the input string. + This is because we are iterating through the string only once and performing constant-time operations. + + The space complexity of the function is also O(n), where n is the length of the input string. + This is because we are using a constant amount of extra space to keep track of the counts of characters. + The size of this extra space does not depend on the length of the input string. ''' # using two-pointer Technique def valid_palindrome(s: str) -> bool: From 759249520a5fa913b0e07d2db576bdc3fdcea846 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:44:57 +0530 Subject: [PATCH 0741/1894] update link in readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88b563e9..f21c9182 100644 --- a/README.md +++ b/README.md @@ -547,7 +547,7 @@ The pointers can be used to iterate the data structure in one or both directions - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) -- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) +- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) # Pattern 2: Fast and Slow Pointers From 5f2b18cb820bd79bdca4811d34a120006e305920 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:47:12 +0530 Subject: [PATCH 0742/1894] modify solution --- Strings/valid_pallindrome2.js | 88 ++++++++++++++++++++--------------- 1 file changed, 51 insertions(+), 37 deletions(-) diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js index 8fa8be8f..1314c66d 100644 --- a/Strings/valid_pallindrome2.js +++ b/Strings/valid_pallindrome2.js @@ -1,43 +1,57 @@ -/* - Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. - - Constraints: string.length The string only consists of English letters - - Sample Input : "madame" - Output : True - - Sample Input : "masdasd" - Output : False -*/ - -// using two-pointer Technique +/** + * Checks whether a string can be a valid palindrome by removing at most one character. + * @param {string} s - The input string to check. + * @return {boolean} - Returns true if the string can be a valid palindrome, false otherwise. + */ function validPalindrome(s) { - let left = 0; - let right = s.length - 1; - - while (left < right) { - if (s[left] !== s[right]) { - // to check if deleting from either left or right char. would create a palindrome - return isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1); - } - left++; - right--; + let left = 0; // Pointer to the left end of the string. + let right = s.length - 1; // Pointer to the right end of the string. + + while (left < right) { + if (s[left] !== s[right]) { + // If characters at left and right indices are not equal. + // Check if string without left index is a palindrome. + let str1 = s.slice(0, left) + s.slice(left + 1); + if (isPalindrome(str1)) { + return true; + } + // Check if string without right index is a palindrome. + let str2 = s.slice(0, right) + s.slice(right + 1); + if (isPalindrome(str2)) { + return true; + } + // If string without left or right index is not a palindrome, return false. + return false; } + // Move pointers inward if characters at left and right indices are equal. + left++; + right--; + } + + // If we get here, the string is already a palindrome, or it can be made into one + // by removing at most one character, so return true. + return true; +} - return true; +/** + * Checks whether a string is a palindrome. + * @param {string} s - The input string to check. + * @return {boolean} - Returns true if the string is a palindrome, false otherwise. + */ +function isPalindrome(s) { + let left = 0; // Pointer to the left end of the string. + let right = s.length - 1; // Pointer to the right end of the string. + + while (left < right) { + if (s[left] !== s[right]) { + // If characters at left and right indices are not equal, return false. + return false; } + // Move pointers inward if characters at left and right indices are equal. + left++; + right--; + } -function isPalindrome(s, left, right) { - while (left < right) { - if (s[left] !== s[right]) { - return false; - } - left++; - right--; - } - return true; + // If we get here, the string is a palindrome, so return true. + return true; } - -console.log(validPalindrome("aba")); // true -console.log(validPalindrome("abca")); // true -console.log(validPalindrome("abc")); // false \ No newline at end of file From cacc45e051e61ffe8a8d09bf16211888d92fa80d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:48:02 +0530 Subject: [PATCH 0743/1894] add description --- Strings/valid_pallindrome2.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js index 1314c66d..95233de2 100644 --- a/Strings/valid_pallindrome2.js +++ b/Strings/valid_pallindrome2.js @@ -1,3 +1,16 @@ +/* + The validPalindrome function takes a string s as input and returns true if the string can be a valid palindrome by removing + at most one character, and false otherwise. It works by initializing two pointers left and right to the left and right ends + of the string, respectively. It then moves the pointers inward while checking if the characters at the left and right indices + are equal. If they are not equal, it removes the left or right character, creates a new string, and checks if the new string + is a palindrome using the isPalindrome helper function. If the new string is a palindrome, it returns true. If not, it + continues moving the pointers inward and repeating the process. If the pointers meet, the string is already a palindrome, + or it can be made into one by removing at most one character, so it returns true. + + The isPalindrome function takes a string s as input and returns true if the string is a palindrome, and false otherwise. + It works by initializing two pointers left and right to the left and right ends of the string, respectively. It then moves + the pointers inward while checking if the characters at the +*/ /** * Checks whether a string can be a valid palindrome by removing at most one character. * @param {string} s - The input string to check. From a5abeca7799baa10b91edf967f0606e05c21899a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:49:00 +0530 Subject: [PATCH 0744/1894] add heading --- Strings/valid_pallindrome2.cpp | 1 + Strings/valid_pallindrome2.go | 1 + Strings/valid_pallindrome2.js | 1 + Strings/valid_pallindrome2.py | 1 + 4 files changed, 4 insertions(+) diff --git a/Strings/valid_pallindrome2.cpp b/Strings/valid_pallindrome2.cpp index 319cdfe9..77670063 100644 --- a/Strings/valid_pallindrome2.cpp +++ b/Strings/valid_pallindrome2.cpp @@ -1,3 +1,4 @@ +// Check whether a string can be a valid palindrome by removing at most one character from it /* Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go index 2079c815..a3224ac6 100644 --- a/Strings/valid_pallindrome2.go +++ b/Strings/valid_pallindrome2.go @@ -1,3 +1,4 @@ +// Check whether a string can be a valid palindrome by removing at most one character from it /* Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js index 95233de2..779dba35 100644 --- a/Strings/valid_pallindrome2.js +++ b/Strings/valid_pallindrome2.js @@ -1,3 +1,4 @@ +// Check whether a string can be a valid palindrome by removing at most one character from it /* The validPalindrome function takes a string s as input and returns true if the string can be a valid palindrome by removing at most one character, and false otherwise. It works by initializing two pointers left and right to the left and right ends diff --git a/Strings/valid_pallindrome2.py b/Strings/valid_pallindrome2.py index ccdab60f..b90d9ed9 100644 --- a/Strings/valid_pallindrome2.py +++ b/Strings/valid_pallindrome2.py @@ -1,3 +1,4 @@ +// Check whether a string can be a valid palindrome by removing at most one character from it ''' Explanation: The function valid_palindrome takes a string s as input and returns a boolean indicating whether the From 37f555cd1d9431bb28398aa912afa384187f420c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:49:52 +0530 Subject: [PATCH 0745/1894] add time and space complexity --- Strings/valid_pallindrome2.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Strings/valid_pallindrome2.js b/Strings/valid_pallindrome2.js index 779dba35..1c04181c 100644 --- a/Strings/valid_pallindrome2.js +++ b/Strings/valid_pallindrome2.js @@ -11,6 +11,10 @@ The isPalindrome function takes a string s as input and returns true if the string is a palindrome, and false otherwise. It works by initializing two pointers left and right to the left and right ends of the string, respectively. It then moves the pointers inward while checking if the characters at the + + Time complexity: O(n) : We iterate over the input string once with two pointers, which takes O(n) time. + Space complexity: O(1) : We only use a few constant amount of variables to keep track of the pointers, left and right. + Therefore, the space complexity is O(1). */ /** * Checks whether a string can be a valid palindrome by removing at most one character. From 6b9153a5a41b8c24cb3e86b85156a2c52a9244e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:50:33 +0530 Subject: [PATCH 0746/1894] update link in readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f21c9182..f9247772 100644 --- a/README.md +++ b/README.md @@ -547,7 +547,7 @@ The pointers can be used to iterate the data structure in one or both directions - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) -- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) +- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.js) # Pattern 2: Fast and Slow Pointers From d4498bcfeaeb7a35b8a9cf02e987b6bb01989d04 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:52:26 +0530 Subject: [PATCH 0747/1894] modify go solution --- Strings/valid_pallindrome2.go | 78 +++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 32 deletions(-) diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go index a3224ac6..291fc3bf 100644 --- a/Strings/valid_pallindrome2.go +++ b/Strings/valid_pallindrome2.go @@ -1,45 +1,59 @@ // Check whether a string can be a valid palindrome by removing at most one character from it /* - Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. - Constraints: string.length The string only consists of English letters + Constraints: string.length The string only consists of English letters - Sample Input : "madame" - Output : True + Sample Input : "madame" + Output : True - Sample Input : "masdasd" - Output : False + Sample Input : "masdasd" + Output : False */ - package main -func validate(s string, left int, right int) bool { - for left < right { - // doesn't match then return false - if s[left] != s[right] { - return false - } else { - left += 1 - right -= 1 - } +// isPalindromeWithRemoval checks if a string can be converted into a palindrome +// by removing at most one character +func isPalindromeWithRemoval(s string) bool { + // Define two pointers to check the string from both ends + i, j := 0, len(s)-1 + + for i < j { + // If characters at the pointers are not equal + if s[i] != s[j] { + // Check if removing a character from the left pointer makes it a palindrome + leftStr := s[:i] + s[i+1:j+1] + if isPalindrome(leftStr) { + return true + } + // Check if removing a character from the right pointer makes it a palindrome + rightStr := s[:i] + s[i:j] + if isPalindrome(rightStr) { + return true + } + // If neither option works, it cannot be converted into a palindrome by removing at most one character + return false + } + // Move the pointers towards the middle of the string + i++ + j-- } return true } -func validPalindrome(s string) bool { - // initialize two pointers at opposite end of string - left := 0 - right := len(s) - 1 - for left < right { - // if value at left and right index match then move them closer - if s[left] == s[right] { - left += 1 - right -= 1 - } else { // if mismatch occurs then skip one and check rest - skipLeft := validate(s, left + 1, right) // skip one from left and check remaining - skipRight := validate(s, left, right - 1) // skip one from right and check remaining - return skipLeft || skipRight // if either is true return true +// isPalindrome checks if a string is a palindrome +func isPalindrome(s string) bool { + // Define two pointers to check the string from both ends + i, j := 0, len(s)-1 + + for i < j { + // If characters at the pointers are not equal, it is not a palindrome + if s[i] != s[j] { + return false } - } - return true -} \ No newline at end of file + // Move the pointers towards the middle of the string + i++ + j-- + } + return true +} From 86cfdc737bccfc6d09ad0a33529b212be1fddcd6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Apr 2023 22:53:10 +0530 Subject: [PATCH 0748/1894] addd description and time and space complexity --- Strings/valid_pallindrome2.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Strings/valid_pallindrome2.go b/Strings/valid_pallindrome2.go index 291fc3bf..5a3d94d6 100644 --- a/Strings/valid_pallindrome2.go +++ b/Strings/valid_pallindrome2.go @@ -1,14 +1,16 @@ // Check whether a string can be a valid palindrome by removing at most one character from it /* - Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. + The given Go program takes a string as input and checks if it can be a valid palindrome by removing at most one + character from it. The program starts by defining two pointers, left and right, that move towards each other from + opposite ends of the input string. At each step, if the characters at the left and right pointers are equal, + then they move towards the center of the string. If the characters are not equal, then we check whether removing + the character at the left or right pointer would make the rest of the string a palindrome. If both removals fail, + then the string cannot be a valid palindrome by removing at most one character. The program returns true + if the string can be made a valid palindrome by removing at most one character, false otherwise. - Constraints: string.length The string only consists of English letters + The time complexity of this algorithm is O(n), where n is the length of the input string. + The space complexity is O(1), as we only use constant extra space to store a few variables. - Sample Input : "madame" - Output : True - - Sample Input : "masdasd" - Output : False */ package main From db2d0d94d7b952c0e76538abc31045e2f8e0c47b Mon Sep 17 00:00:00 2001 From: Alec Swift Date: Wed, 19 Apr 2023 13:04:34 -0700 Subject: [PATCH 0749/1894] Add python topological_sort --- Graphs/topological_sort_dfs.py | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Graphs/topological_sort_dfs.py diff --git a/Graphs/topological_sort_dfs.py b/Graphs/topological_sort_dfs.py new file mode 100644 index 00000000..bba78dfc --- /dev/null +++ b/Graphs/topological_sort_dfs.py @@ -0,0 +1,47 @@ +""" +Implementation of Topological sort using DFS +According to Introduction to Algorithms, given a directed acyclic graph (DAG), +a topological sort is a linear ordering of all vertices such that for any edge +(u, v), u comes before v. Another way to describe it is that when you put all +vertices horizontally on a line, all of the edges are pointing from left to right. + +Time complexity O(Vertices + Edges) +""" + +def main(): + adj_list = { + 5: [2, 0], + 4: [0, 1], + 3: [1], + 2: [3], + 1: [], + 0: [] + } + + dfs(adj_list, set(), []) + + + +def dfs(adj_list, visited, stack): + for vertex in range(6): + if vertex in visited: + continue + dfs_visit(adj_list, visited, vertex, stack) + + print(stack[::-1]) + + +def dfs_visit(adj_list, visited, node, stack): + visited.add(node) + + for neighbor in adj_list[node]: + if neighbor in visited: + continue + dfs_visit(adj_list, visited, neighbor, stack) + + stack.append(node) + + + +if __name__ == "__main__": + main() \ No newline at end of file From 52c2ef890f3d28a1c718701cd6daeea382e8fe47 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:27:40 +0530 Subject: [PATCH 0750/1894] add item struct and heap based priority queue of items --- Graphs/dijkstras.go | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Graphs/dijkstras.go diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go new file mode 100644 index 00000000..9da4593c --- /dev/null +++ b/Graphs/dijkstras.go @@ -0,0 +1,10 @@ + +package main +// priorityQueue is a heap-based priority queue of items +type priorityQueue []*item + +// item represents an item in the priority queue +type item struct { + value string // value of the item + priority int // priority of the item (i.e., its distance from the start vertex) +} \ No newline at end of file From 3b10dba891d456139d16b94e6fc44980bd6b5d22 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:29:03 +0530 Subject: [PATCH 0751/1894] add len func --- Graphs/dijkstras.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 9da4593c..9288252c 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -7,4 +7,9 @@ type priorityQueue []*item type item struct { value string // value of the item priority int // priority of the item (i.e., its distance from the start vertex) +} + +// Len returns the number of items in the priority queue +func (pq priorityQueue) Len() int { + return len(pq) } \ No newline at end of file From 4fa485428192246d87ad104e467b829b23fe3438 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:29:17 +0530 Subject: [PATCH 0752/1894] add less func --- Graphs/dijkstras.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 9288252c..614224c4 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -12,4 +12,9 @@ type item struct { // Len returns the number of items in the priority queue func (pq priorityQueue) Len() int { return len(pq) +} + +// Less returns true if item i has higher priority than item j +func (pq priorityQueue) Less(i, j int) bool { + return pq[i].priority < pq[j].priority } \ No newline at end of file From 73fe55c134f51754449c956f12b3c2adff567d0f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:29:33 +0530 Subject: [PATCH 0753/1894] add swap func --- Graphs/dijkstras.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 614224c4..72d0b8ae 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -17,4 +17,9 @@ func (pq priorityQueue) Len() int { // Less returns true if item i has higher priority than item j func (pq priorityQueue) Less(i, j int) bool { return pq[i].priority < pq[j].priority -} \ No newline at end of file +} + +// Swap swaps the positions of items i and j in the priority queue +func (pq priorityQueue) Swap(i, j int) { + pq[i], pq[j] = pq[j], pq[i] +} From 569ec523e0c89ca33cd636c6e48d6fa0eef915be Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:29:45 +0530 Subject: [PATCH 0754/1894] add push func --- Graphs/dijkstras.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 72d0b8ae..1a522a3e 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -23,3 +23,9 @@ func (pq priorityQueue) Less(i, j int) bool { func (pq priorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } + +// Push adds an item to the priority queue +func (pq *priorityQueue) Push(x interface{}) { + item := x.(*item) + *pq = append(*pq, item) +} From d3e91fee33a6577ad38290567eca9bef227b79ea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:29:59 +0530 Subject: [PATCH 0755/1894] add pop func --- Graphs/dijkstras.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 1a522a3e..cea87481 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -29,3 +29,12 @@ func (pq *priorityQueue) Push(x interface{}) { item := x.(*item) *pq = append(*pq, item) } + +// Pop removes the item with the highest priority from the priority queue and returns it +func (pq *priorityQueue) Pop() interface{} { + old := *pq + n := len(old) + item := old[n-1] + *pq = old[0 : n-1] + return item +} \ No newline at end of file From e87dcf212f28ecd609f5e0c373b0331608392fbf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:31:11 +0530 Subject: [PATCH 0756/1894] add dijkstras algo --- Graphs/dijkstras.go | 50 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index cea87481..ec38aaa4 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,5 +1,10 @@ - package main + +import ( + "container/heap" + "math" +) + // priorityQueue is a heap-based priority queue of items type priorityQueue []*item @@ -37,4 +42,45 @@ func (pq *priorityQueue) Pop() interface{} { item := old[n-1] *pq = old[0 : n-1] return item -} \ No newline at end of file +} + +// Dijkstra's algorithm finds the shortest path between a start vertex and all other vertices in a weighted graph. +// It returns a map of the shortest distance to each vertex and the previous vertex on the shortest path. +// If a vertex is unreachable, its distance is set to infinity. +func Dijkstra(graph map[string]map[string]int, start string) (map[string]int, map[string]string) { + dist := make(map[string]int) // distances from start vertex to each vertex + prev := make(map[string]string) // previous vertex on the shortest path from start to each vertex + queue := make(priorityQueue, 0) // priority queue to track next vertex to visit + + // initialize distances and previous vertices + for v := range graph { + dist[v] = math.MaxInt32 // initialize all distances to infinity + prev[v] = "" // initialize all previous vertices to empty + } + dist[start] = 0 // distance from start vertex to itself is 0 + + // add start vertex to priority queue + heap.Push(&queue, &item{value: start, priority: 0}) + + // loop until priority queue is empty + for queue.Len() > 0 { + // remove vertex with minimum distance from priority queue + u := heap.Pop(&queue).(*item).value + + // loop through neighbors of current vertex + for v, w := range graph[u] { + alt := dist[u] + w // calculate alternate distance to neighbor + + // if alternate distance is shorter than current distance, update distances and previous vertices + if alt < dist[v] { + dist[v] = alt + prev[v] = u + + // add neighbor to priority queue + heap.Push(&queue, &item{value: v, priority: alt}) + } + } + } + + return dist, prev +} From 3691e4509dc244e70028a3272b918d4cb921f03e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:38:28 +0530 Subject: [PATCH 0757/1894] add main func --- Graphs/dijkstras.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index ec38aaa4..d6d0bdd5 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -2,6 +2,7 @@ package main import ( "container/heap" + "fmt" "math" ) @@ -84,3 +85,19 @@ func Dijkstra(graph map[string]map[string]int, start string) (map[string]int, ma return dist, prev } + +func main() { + + graph := map[string]map[string]int{ + "A": {"B": 2, "C": 3}, + "B": {"C": 1, "D": 1}, + "C": {"D": 4}, + "D": {"C": 2}, + } + start := "A" + distances, _ := Dijkstra(graph, start) + fmt.Println("Shortest distances from", start, "to all other nodes:") + for node, distance := range distances { + fmt.Println(node, distance) +} +} \ No newline at end of file From 6e57f6e91619b9116a04b7de5220ef4ec81c0f3a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:52:31 +0530 Subject: [PATCH 0758/1894] add explanation --- Graphs/dijkstras.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index d6d0bdd5..f6b0c75e 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,3 +1,22 @@ +/* + Dijkstra's algorithm is a pathfinding algorithm that finds the shortest path between two points in a graph. + Here's how it works: + + 1. Start at the starting point (let's call it "A") and mark its distance as 0. + + 2. Visit each of its neighbors (the nodes it's connected to) and mark their distances as their weight + (the distance between node A and its neighbor). + + 3. Choose the neighbor with the shortest distance and mark it as "visited." + + 4. Visit each of its neighbors that haven't been visited yet and calculate their distances by adding the weight + of the edge between them and the current node to the current node's distance. If this distance is shorter than the current distance marked for the node, replace it with the shorter distance. + + 5. Repeat steps 3 and 4 until you reach the destination node or until all nodes have been visited. + + 6. Once you've reached the destination node, the shortest path can be determined by tracing back through the + visited nodes from the destination to the starting point, following the path of the shortest distances. +*/ package main import ( From 86b81148121ef21ee9562d203652e5da36ffa240 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:52:45 +0530 Subject: [PATCH 0759/1894] add heading --- Graphs/dijkstras.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index f6b0c75e..05e57065 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,3 +1,4 @@ +// Dijkstra's algorithm /* Dijkstra's algorithm is a pathfinding algorithm that finds the shortest path between two points in a graph. Here's how it works: From 5f947756f7cdbb6cdf96b2fc3d933839124b1f4c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Apr 2023 22:54:36 +0530 Subject: [PATCH 0760/1894] add time and space complexity --- Graphs/dijkstras.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 05e57065..e2036cd9 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -17,6 +17,20 @@ 6. Once you've reached the destination node, the shortest path can be determined by tracing back through the visited nodes from the destination to the starting point, following the path of the shortest distances. + + Time complexity: + + In the worst case, Dijkstra's algorithm visits every vertex and every edge in the graph. + Each vertex is visited once, and each edge is relaxed once. + Therefore, the time complexity of Dijkstra's algorithm is O(V + E * log V), where V is the number of vertices and E is the number of edges in the graph. + Note that this assumes a priority queue is used to efficiently extract the vertex with the smallest distance. If an array is used instead, the time complexity would be O(V^2 + E). + + Space complexity: + + Dijkstra's algorithm uses two data structures: a priority queue and an array to keep track of the shortest distances from the source vertex to all other vertices. + The priority queue stores at most V vertices at a time. + The array has V entries. + Therefore, the space complexity of Dijkstra's algorithm is O(V). */ package main From 93ce71843c5315e7276881cc18e8995466b12dd9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:47:16 +0530 Subject: [PATCH 0761/1894] add mergesort func --- sorting/merge_sort.go | 61 ++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index 44d4e577..df2d1488 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -8,42 +8,33 @@ // Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). // Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list // Source(https://en.wikipedia.org/wiki/Merge_sort) - package main -// Approach: Divide by finding the number mid of the position midway between left and right. Do this step the same -// way we found the midpoint in binary search -// Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. -// That is, recursively sort the subarray Arr[left. . mid] and recursively sort the subarray Arr[mid + 1. . right]. -// Combine by merging the two sorted subarrays back into the single sorted subarray Arr[left. . right]. -func MergeSort(Arr []int) []int { - if len(Arr) <= 1 { - return Arr - } - middle := len(Arr) / 2 - left := MergeSort(Arr[:middle]) - right := MergeSort(Arr[middle:]) - return Merge(left, right) -} - -func Merge(left, right []int) []int { - result := make([]int, len(left) + len(right)) - for i:=0; len(left) > 0 || len(right) > - 0; i++ { - if len(left) > 0 && len(right) > 0 { - if left[0] < right[0] { - result[i] = left[0] - left = left[1:] - } else { - result[i] = right[0] - right = right[1:] - } - } else if len(left) > 0 { - result[i] = left[0] - left = left[1:] - } else if len(right) > 0 { - result[i] = right[0] - right = right[1:] - } +import ( + "fmt" +) + +// MergeSort is the main function that takes an integer array as input +// and sorts it using the Merge Sort algorithm. +func MergeSort(arr []int) []int { + // If the array has only one element, return it. + if len(arr) == 1 { + return arr } - return result + + // Find the middle point to divide the array into two halves. + mid := len(arr) / 2 + + // Split the array into two halves. + left := arr[:mid] + right := arr[mid:] + + // Recursively sort the left half of the array. + left = MergeSort(left) + + // Recursively sort the right half of the array. + right = MergeSort(right) + + // Merge the two sorted halves. + return merge(left, right) } \ No newline at end of file From 43be6d26d28f721e1292443e8fe4ccc0124d8194 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:47:32 +0530 Subject: [PATCH 0762/1894] add merge func --- sorting/merge_sort.go | 44 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index df2d1488..2d1b0876 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -10,10 +10,6 @@ // Source(https://en.wikipedia.org/wiki/Merge_sort) package main -import ( - "fmt" -) - // MergeSort is the main function that takes an integer array as input // and sorts it using the Merge Sort algorithm. func MergeSort(arr []int) []int { @@ -37,4 +33,44 @@ func MergeSort(arr []int) []int { // Merge the two sorted halves. return merge(left, right) +} + +// Merge is a helper function that takes two sorted arrays and merges them into one sorted array. +func merge(left, right []int) []int { + // Initialize a new array to hold the merged result. + result := make([]int, len(left)+len(right)) + + // Initialize the index variables for the left, right, and result arrays. + i := 0 // Index for left array + j := 0 // Index for right array + k := 0 // Index for result array + + // Iterate over the left and right arrays and compare their elements. + // Add the smaller element to the result array and move the corresponding index variable. + for i < len(left) && j < len(right) { + if left[i] < right[j] { + result[k] = left[i] + i++ + } else { + result[k] = right[j] + j++ + } + k++ + } + + // Append the remaining elements of the left or right array to the result array. + for i < len(left) { + result[k] = left[i] + i++ + k++ + } + + for j < len(right) { + result[k] = right[j] + j++ + k++ + } + + // Return the merged and sorted result array. + return result } \ No newline at end of file From 0c04a1add7f5570126b386bfec9016c3dd0a33bc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:47:50 +0530 Subject: [PATCH 0763/1894] add main func --- sorting/merge_sort.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index 2d1b0876..e1dfce80 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -10,6 +10,8 @@ // Source(https://en.wikipedia.org/wiki/Merge_sort) package main +import "fmt" + // MergeSort is the main function that takes an integer array as input // and sorts it using the Merge Sort algorithm. func MergeSort(arr []int) []int { @@ -73,4 +75,12 @@ func merge(left, right []int) []int { // Return the merged and sorted result array. return result +} + +func main() { + // Example usage + arr := []int{3, 2, 1, 5, 4} + fmt.Println("Unsorted array:", arr) + arr = MergeSort(arr) + fmt.Println("Sorted array:", arr) } \ No newline at end of file From f0aeaed50ef7b90671f9fcba5145514da3ebfd05 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:48:29 +0530 Subject: [PATCH 0764/1894] add description --- sorting/merge_sort.go | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index e1dfce80..17b64449 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -1,13 +1,16 @@ -// In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, -// and comparison-based sorting algorithm. Most implementations produce a stable sort, -// which means that the order of equal elements is the same in the input and output. -// Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. -// A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. -// Conceptually, a merge sort works as follows: - -// Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). -// Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list -// Source(https://en.wikipedia.org/wiki/Merge_sort) +/* + The MergeSort function is the main function that takes an integer array as input and sorts it using the Merge Sort algorithm. + + In the MergeSort function, if the length of the input array is only one element, it is already sorted, so we return it as is. + Otherwise, we find the middle point of the array and split it into two halves. We then recursively call the MergeSort + function on the left half and the right half of the array. Finally, we merge the two sorted halves using the merge function. + + The merge function takes two sorted arrays as input and merges them into one sorted array. We initialize a new array to hold + the merged result and three index variables for the left, right, and result arrays. We then iterate over the left and right + arrays and compare their elements. We add the smaller element to the result array and move the corresponding index variable. + Finally, we append the remaining elements of the left or right array to the result array and return it. + +*/ package main import "fmt" From 9f07a4436ff56b163c980ba6a9622a16a961fb4d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:49:06 +0530 Subject: [PATCH 0765/1894] add time and space comlexity --- sorting/merge_sort.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index 17b64449..83545579 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -10,6 +10,9 @@ arrays and compare their elements. We add the smaller element to the result array and move the corresponding index variable. Finally, we append the remaining elements of the left or right array to the result array and return it. + The time complexity of Merge Sort is O(n*log n), where n is the number of elements in the array, + and the space complexity is O(n) due to the use of the temporary arrays during the merging phase. + */ package main From ca722812126a827dd20308fcb380c2bae264c5d3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:50:04 +0530 Subject: [PATCH 0766/1894] add merge func --- sorting/merge_sort.cpp | 74 ++++++++++++++++++------------------------ 1 file changed, 32 insertions(+), 42 deletions(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 617d33eb..146a575e 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,46 +1,36 @@ -// In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, -// and comparison-based sorting algorithm. Most implementations produce a stable sort, -// which means that the order of equal elements is the same in the input and output. -// Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. -// A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. -// Conceptually, a merge sort works as follows: +#include +#include -// Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). -// Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list -// Source(https://en.wikipedia.org/wiki/Merge_sort) -#include using namespace std; -void Merge(int *A, int *L, int leftCount, int *R, int rightCount){ - int i, j, k; - i = 0; j = 0; k = 0; - while(i < leftCount && j < rightCount){ - if(L[i] < R[j]) - A[k++] = L[i++]; - else - A[k++] = R[j++]; - } - while(i < leftCount) A[k++] = L[i++]; - while(j < rightCount) A[k++] = R[j++]; -} -void MergeSort(int *A, int n){ - int mid, *L, *R; - if(n < 2) return; // base condition if array has less then 2 elements do nothing - mid = n / 2; - L = (int*)malloc(mid * sizeof(int)); - R = (int*)malloc((n - mid) * sizeof(int)); - for(int i = 0; i < mid; i++) L[i] = A[i]; - for(int i = mid; i < n; i++) R[i - mid] = A[i]; - MergeSort(L, mid); - MergeSort(R, n - mid); - Merge(A, L, mid, R, n - mid); - free(L); - free(R); -} -int main(){ - int A[] = {2,1,4,3,5,99,32,47,106,1,4,6,8,7,0,9}; - MergeSort(A,16); - for(int i = 0; i < 16; i++) - cout << A[i] << " "; - return 0; +void merge(vector& arr, int start, int mid, int end) { + vector temp(end - start + 1); + int i = start, j = mid + 1, k = 0; + + while (i <= mid && j <= end) { + if (arr[i] <= arr[j]) { + temp[k] = arr[i]; + ++i; + } else { + temp[k] = arr[j]; + ++j; + } + ++k; + } + + while (i <= mid) { + temp[k] = arr[i]; + ++i; + ++k; + } + + while (j <= end) { + temp[k] = arr[j]; + ++j; + ++k; + } + + for (int l = start; l <= end; ++l) { + arr[l] = temp[l - start]; + } } From 551133143009cfd9e4b725c10f13f42936f1dcac Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:50:16 +0530 Subject: [PATCH 0767/1894] add merge sort func --- sorting/merge_sort.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 146a575e..73017a59 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -34,3 +34,12 @@ void merge(vector& arr, int start, int mid, int end) { arr[l] = temp[l - start]; } } + +void merge_sort(vector& arr, int start, int end) { + if (start < end) { + int mid = (start + end) / 2; + merge_sort(arr, start, mid); + merge_sort(arr, mid + 1, end); + merge(arr, start, mid, end); + } +} \ No newline at end of file From 5a70ae0965922b5e5e7c33714ac40c66f25fc32a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:50:25 +0530 Subject: [PATCH 0768/1894] add main func --- sorting/merge_sort.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 73017a59..508f966a 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -42,4 +42,14 @@ void merge_sort(vector& arr, int start, int end) { merge_sort(arr, mid + 1, end); merge(arr, start, mid, end); } +} + +int main() { + vector arr = {5, 2, 8, 1, 9, 4}; + merge_sort(arr, 0, arr.size() - 1); + for (int num : arr) { + cout << num << " "; + } + cout << endl; + return 0; } \ No newline at end of file From ff489abc235a6424fe4aaf09b1ea8890b354743d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:51:08 +0530 Subject: [PATCH 0769/1894] add description --- sorting/merge_sort.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 508f966a..76444c33 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,3 +1,13 @@ +/* + Here's how the merge sort algorithm works: + + 1. It divides the input array into two halves, recursively sorts them, and then merges the sorted halves. + 2. To merge two sorted sub-arrays, we need to create a temporary array and then compare the elements of the two sub-arrays, + one by one, and add the smaller element to the temporary array. + 3. After we have exhausted one of the sub-arrays, we simply copy the remaining elements of the other sub-array to the temporary array. + 4. Finally, we copy the elements of the temporary array back to the original array. + +*/ #include #include From 2ee3d6da4ecf0dddc11e25439cb4dfd6c6f5524f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:51:23 +0530 Subject: [PATCH 0770/1894] add time and space complexity --- sorting/merge_sort.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 76444c33..8f3955d8 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -6,7 +6,9 @@ one by one, and add the smaller element to the temporary array. 3. After we have exhausted one of the sub-arrays, we simply copy the remaining elements of the other sub-array to the temporary array. 4. Finally, we copy the elements of the temporary array back to the original array. - + + The time complexity of merge sort is O(n log n), where n is the number of elements in the array. + The space complexity is O(n), because we create a temporary array of size n during the merging process. */ #include #include From a3d2cae5db9fd4ae0967179a89da7b550c5df6b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:51:50 +0530 Subject: [PATCH 0771/1894] add heading --- sorting/merge_sort.cpp | 1 + sorting/merge_sort.go | 1 + 2 files changed, 2 insertions(+) diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 8f3955d8..23f733e3 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,3 +1,4 @@ +// Merge Sort /* Here's how the merge sort algorithm works: diff --git a/sorting/merge_sort.go b/sorting/merge_sort.go index 83545579..c70dc001 100644 --- a/sorting/merge_sort.go +++ b/sorting/merge_sort.go @@ -1,3 +1,4 @@ +// Merge Sort /* The MergeSort function is the main function that takes an integer array as input and sorts it using the Merge Sort algorithm. From fabc0e451056d7d720e3dbb2a1b36e1cc551e962 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:54:04 +0530 Subject: [PATCH 0772/1894] add mergesort func --- sorting/merge_sort.js | 80 +++++++++---------------------------------- 1 file changed, 17 insertions(+), 63 deletions(-) diff --git a/sorting/merge_sort.js b/sorting/merge_sort.js index 6d0746c4..902e42fd 100644 --- a/sorting/merge_sort.js +++ b/sorting/merge_sort.js @@ -1,68 +1,22 @@ -// In computer science, merge sort (also commonly spelled as mergesort) is an efficient, general-purpose, -// and comparison-based sorting algorithm. Most implementations produce a stable sort, -// which means that the order of equal elements is the same in the input and output. -// Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. -// A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948. -// Conceptually, a merge sort works as follows: - -// Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). -// Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list -// Source(https://en.wikipedia.org/wiki/Merge_sort) - -// Approach: Divide by finding the number mid of the position midway between left and right. Do this step the same -// way we found the midpoint in binary search -// Conquer by recursively sorting the subarrays in each of the two subproblems created by the divide step. -// That is, recursively sort the subarray Arr[left. . mid] and recursively sort the subarray Arr[mid + 1. . right]. -// Combine by merging the two sorted subarrays back into the single sorted subarray Arr[left. . right]. - -const inputArr = [4, 5, 67, 56, 3, 35, 45]; - +/** + * Merge sort algorithm to sort an array of integers in ascending order. + * @param {Array} arr - The array of integers to be sorted + * @return {Array} - The sorted array + */ function mergeSort(arr) { - if (arr.length > 1) { - // splitting the list into two smaller lists - const mid = Math.floor(arr.length / 2); - const left = arr.slice(0, mid); - const right = arr.slice(mid); - - // recurses over the two smaller lists - mergeSort(left); - mergeSort(right); - - // define counters for our left, right and arr arrays - let i = 0; - let j = 0; - let k = 0; + if (arr.length <= 1) { + return arr; + } - // compares elements in left and right arrays - // and places them back in arr from least to greatest - while (i < left.length && j < right.length) { - if (left[i] <= right[j]) { - arr[k] = left[i]; - i = i + 1; - } else { - arr[k] = right[j]; - j = j + 1; - } - k = k + 1; - } + // Split the array into two halves + const middleIndex = Math.floor(arr.length / 2); + const leftArr = arr.slice(0, middleIndex); + const rightArr = arr.slice(middleIndex); - // if there are any elements remaining in our left array, put them in our arr array - while (i < left.length) { - arr[k] = left[i]; - i = i + 1; - k = k + 1; - } + // Recursively call mergeSort on each half + const sortedLeftArr = mergeSort(leftArr); + const sortedRightArr = mergeSort(rightArr); - // if there are any elements remaining in our right array, put them in our arr array - while (j < right.length) { - arr[k] = right[j]; - j = j + 1; - k = k + 1; - } - } - - return arr; + // Merge the two sorted halves into a single sorted array + return merge(sortedLeftArr, sortedRightArr); } - -mergeSort(inputArr); -console.log(inputArr); From 65560c30fea39fdd060c600e9d9ee469d3636571 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:54:24 +0530 Subject: [PATCH 0773/1894] add merge func --- sorting/merge_sort.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/sorting/merge_sort.js b/sorting/merge_sort.js index 902e42fd..86f0c7ce 100644 --- a/sorting/merge_sort.js +++ b/sorting/merge_sort.js @@ -20,3 +20,39 @@ function mergeSort(arr) { // Merge the two sorted halves into a single sorted array return merge(sortedLeftArr, sortedRightArr); } + +/** + * Merge two sorted arrays into a single sorted array + * @param {Array} leftArr - The first sorted array + * @param {Array} rightArr - The second sorted array + * @return {Array} - The merged sorted array + */ +function merge(leftArr, rightArr) { + let i = 0; + let j = 0; + const mergedArr = []; + + // Compare the elements of the two arrays and add the smallest to the merged array + while (i < leftArr.length && j < rightArr.length) { + if (leftArr[i] <= rightArr[j]) { + mergedArr.push(leftArr[i]); + i++; + } else { + mergedArr.push(rightArr[j]); + j++; + } + } + + // Add any remaining elements from the left or right array to the merged array + while (i < leftArr.length) { + mergedArr.push(leftArr[i]); + i++; + } + + while (j < rightArr.length) { + mergedArr.push(rightArr[j]); + j++; + } + + return mergedArr; +} From 0c8b08a20f1625aef9c65f9f4ae8f940663f42f9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:55:16 +0530 Subject: [PATCH 0774/1894] add example --- sorting/merge_sort.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sorting/merge_sort.js b/sorting/merge_sort.js index 86f0c7ce..0f7a8495 100644 --- a/sorting/merge_sort.js +++ b/sorting/merge_sort.js @@ -56,3 +56,8 @@ function merge(leftArr, rightArr) { return mergedArr; } + +const unsortedArr = [5, 2, 9, 1, 5, 6]; +const sortedArr = mergeSort(unsortedArr); + +console.log(sortedArr); // Output: [1, 2, 5, 5, 6, 9] From 46229c5093542f43af5c5f7a5e1031b847f153c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Apr 2023 19:55:53 +0530 Subject: [PATCH 0775/1894] add description, time and space complexity --- sorting/merge_sort.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sorting/merge_sort.js b/sorting/merge_sort.js index 0f7a8495..641aead3 100644 --- a/sorting/merge_sort.js +++ b/sorting/merge_sort.js @@ -1,3 +1,17 @@ +// Merge Sort +/* + Here's how the merge sort algorithm works: + + 1. It divides the input array into two halves, recursively sorts them, and then merges the sorted halves. + 2. To merge two sorted sub-arrays, we need to create a temporary array and then compare the elements of the two sub-arrays, + one by one, and add the smaller element to the temporary array. + 3. After we have exhausted one of the sub-arrays, we simply copy the remaining elements of the other sub-array to the temporary array. + 4. Finally, we copy the elements of the temporary array back to the original array. + + The time complexity of merge sort is O(n log n), where n is the number of elements in the array. + The space complexity is O(n), because we create a temporary array of size n during the merging process. +*/ + /** * Merge sort algorithm to sort an array of integers in ascending order. * @param {Array} arr - The array of integers to be sorted From dc41c05aeb2d7af388c480a9b9ed8814d983e05c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:41:05 +0530 Subject: [PATCH 0776/1894] rename file and modify program --- Arrays/max_contiguous_sum.go | 50 ------------------------------------ Arrays/maximum_subarray.go | 37 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 50 deletions(-) delete mode 100644 Arrays/max_contiguous_sum.go create mode 100644 Arrays/maximum_subarray.go diff --git a/Arrays/max_contiguous_sum.go b/Arrays/max_contiguous_sum.go deleted file mode 100644 index 9dad2f6a..00000000 --- a/Arrays/max_contiguous_sum.go +++ /dev/null @@ -1,50 +0,0 @@ -// Given an array of 􀝊 numbers, give an algorithm for finding -// a contiguous subsequence A(i). . . A(j) for which the sum of elements is maximum. -// Example: {-2, 11, -4, 13, -5, 2} → 20 and {1, -3, 4, -2, -1, 6} → 7 -package main - -import "fmt" - -// MaxContiguousSum: give max contiguous sum in supplied array -// Approach: Bruteforce tru all possibilities and select maximum sum -// Time complexity O(n3) -func MaxContiguousSum(Arr []int) int { - maxSum, n := 0, len(Arr) - for i := 0; i < n; i++ { - for j := i; j < n; j++ { - currentSum := 0 - // range over i to j and calculate sum - for k := i; k <= j; k++ { - currentSum += Arr[k] - } - // if sum exceeds maxsum so far then set max sum as currsum - if currentSum > maxSum { - maxSum = currentSum - } - } - } - return maxSum -} - -// Time complexity O(n2) -func MaxContiguousSum2(Arr []int) int { - maxSum, n := 0, len(Arr) - for i := 0; i < n ; i++ { - currentSum := 0 - for j := i; j < n; j++ { - currentSum += Arr[j] - if currentSum > maxSum { - maxSum = currentSum - } - } - } - return maxSum -} - -func main() { - Arr := []int{-2, 11, -4, 13, -5, 2} - fmt.Println(MaxContiguousSum(Arr)) - Arr = []int{1, -3, 4, -2, -1, 6} - fmt.Println(MaxContiguousSum(Arr)) - fmt.Println(MaxContiguousSum2(Arr)) -} \ No newline at end of file diff --git a/Arrays/maximum_subarray.go b/Arrays/maximum_subarray.go new file mode 100644 index 00000000..a4e4d589 --- /dev/null +++ b/Arrays/maximum_subarray.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "math" +) + +// This function returns the maximum subarray sum in a given slice of integers. +// It takes an integer slice as input and returns the maximum subarray sum as an integer. +func maxSubarraySum(arr []int) int { + maxSoFar := math.MinInt32 // Initialize the maximum subarray sum to the smallest possible integer value + maxEndingHere := 0 // Initialize the maximum ending here to 0 + + for _, num := range arr { + // Update the maximum ending here + maxEndingHere += num + + // If the maximum ending here is negative, we reset it to 0 + if maxEndingHere < 0 { + maxEndingHere = 0 + } + + // If the maximum ending here is greater than the maximum subarray sum so far, + // we update the maximum subarray sum so far + if maxEndingHere > maxSoFar { + maxSoFar = maxEndingHere + } + } + + return maxSoFar +} + +func main() { + arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} + maxSum := maxSubarraySum(arr) + fmt.Println("Maximum subarray sum:", maxSum) +} From ef68e5f5e85bc6c9dd87656849e7a1b543327d61 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:43:09 +0530 Subject: [PATCH 0777/1894] add time and space complexity and update heading --- Arrays/maximum_subarray.go | 37 -------------------- Arrays/maximum_subarray_sum.go | 63 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 37 deletions(-) delete mode 100644 Arrays/maximum_subarray.go create mode 100644 Arrays/maximum_subarray_sum.go diff --git a/Arrays/maximum_subarray.go b/Arrays/maximum_subarray.go deleted file mode 100644 index a4e4d589..00000000 --- a/Arrays/maximum_subarray.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "fmt" - "math" -) - -// This function returns the maximum subarray sum in a given slice of integers. -// It takes an integer slice as input and returns the maximum subarray sum as an integer. -func maxSubarraySum(arr []int) int { - maxSoFar := math.MinInt32 // Initialize the maximum subarray sum to the smallest possible integer value - maxEndingHere := 0 // Initialize the maximum ending here to 0 - - for _, num := range arr { - // Update the maximum ending here - maxEndingHere += num - - // If the maximum ending here is negative, we reset it to 0 - if maxEndingHere < 0 { - maxEndingHere = 0 - } - - // If the maximum ending here is greater than the maximum subarray sum so far, - // we update the maximum subarray sum so far - if maxEndingHere > maxSoFar { - maxSoFar = maxEndingHere - } - } - - return maxSoFar -} - -func main() { - arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} - maxSum := maxSubarraySum(arr) - fmt.Println("Maximum subarray sum:", maxSum) -} diff --git a/Arrays/maximum_subarray_sum.go b/Arrays/maximum_subarray_sum.go new file mode 100644 index 00000000..5b93432c --- /dev/null +++ b/Arrays/maximum_subarray_sum.go @@ -0,0 +1,63 @@ +// Maximum Subarray Kadanes Algorithm +/* + The maxSubarraySum function takes an integer slice arr as input and returns the maximum subarray + sum as an integer. + + The maxSoFar variable is initialized to the smallest possible integer value, since any valid subarray + sum must be greater than or equal to this value. The maxEndingHere variable is initialized to 0, + since an empty subarray has a sum of 0. + + The function then iterates through the elements of arr, updating maxEndingHere and maxSoFar as necessary. + At each iteration, the maximum ending here is updated by adding the current element to it. + If the maximum ending here becomes negative, it is reset to 0, since any subarray that includes a negative + sum will not be the maximum subarray. If the maximum ending here is greater than the maximum subarray + sum so far, maxSoFar is updated to the new maximum. + + Finally, the function returns maxSoFar. + + In the main function, an example input array is defined and passed to maxSubarraySum. + The resulting maximum subarray sum is printed to the console. + + The time complexity of the above implementation of Kadane's algorithm for finding the maximum subarray sum is O(n), + where n is the length of the input array. This is because we are iterating over each element of the array only once. + + The space complexity of the implementation is O(1), as we are only using a constant amount of extra space for + storing the maximum subarray sum and the current subarray sum. +*/ +package main + +import ( + "fmt" + "math" +) + +// This function returns the maximum subarray sum in a given slice of integers. +// It takes an integer slice as input and returns the maximum subarray sum as an integer. +func maxSubarraySum(arr []int) int { + maxSoFar := math.MinInt32 // Initialize the maximum subarray sum to the smallest possible integer value + maxEndingHere := 0 // Initialize the maximum ending here to 0 + + for _, num := range arr { + // Update the maximum ending here + maxEndingHere += num + + // If the maximum ending here is negative, we reset it to 0 + if maxEndingHere < 0 { + maxEndingHere = 0 + } + + // If the maximum ending here is greater than the maximum subarray sum so far, + // we update the maximum subarray sum so far + if maxEndingHere > maxSoFar { + maxSoFar = maxEndingHere + } + } + + return maxSoFar +} + +func main() { + arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} + maxSum := maxSubarraySum(arr) + fmt.Println("Maximum subarray sum:", maxSum) +} From edc692405c2df9081fa82d1b33b425dd1f4eadce Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:45:41 +0530 Subject: [PATCH 0778/1894] add brute force solution --- Arrays/maximum_subarray_sum.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Arrays/maximum_subarray_sum.go b/Arrays/maximum_subarray_sum.go index 5b93432c..2c685cfb 100644 --- a/Arrays/maximum_subarray_sum.go +++ b/Arrays/maximum_subarray_sum.go @@ -31,6 +31,7 @@ import ( "math" ) +// Kadanes algorithm // This function returns the maximum subarray sum in a given slice of integers. // It takes an integer slice as input and returns the maximum subarray sum as an integer. func maxSubarraySum(arr []int) int { @@ -56,8 +57,34 @@ func maxSubarraySum(arr []int) int { return maxSoFar } +// Brute Force Solution +func maxSubarraySumBruteForce(nums []int) int { + maxSum := math.MinInt32 // Initialize the maximum sum to the smallest possible integer + n := len(nums) + + // Consider all possible subarrays and keep track of the maximum sum + for i := 0; i < n; i++ { + currSum := 0 // Initialize the current sum to 0 + + // Consider all subarrays starting from i and ending at j + for j := i; j < n; j++ { + currSum += nums[j] // Add the jth element to the current sum + + // Update the maximum sum if the current sum is greater + if currSum > maxSum { + maxSum = currSum + } + } + } + + return maxSum +} + + func main() { arr := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} maxSum := maxSubarraySum(arr) fmt.Println("Maximum subarray sum:", maxSum) + maxSum = maxSubarraySumBruteForce(arr) + fmt.Println("Maximum subarray sum using brute force:", maxSum) } From fe2bb5114c60615e988a2bf51905fd52d64fc62d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:49:49 +0530 Subject: [PATCH 0779/1894] modify heading --- Arrays/maximum_subarray_sum.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/maximum_subarray_sum.go b/Arrays/maximum_subarray_sum.go index 2c685cfb..10436d40 100644 --- a/Arrays/maximum_subarray_sum.go +++ b/Arrays/maximum_subarray_sum.go @@ -1,4 +1,4 @@ -// Maximum Subarray Kadanes Algorithm +// Maximum Subarray /* The maxSubarraySum function takes an integer slice arr as input and returns the maximum subarray sum as an integer. From fc3567c16cb2a5d3da81f276172f80a44d74b650 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:50:05 +0530 Subject: [PATCH 0780/1894] modify program --- Arrays/maximum_subarray.cpp | 103 +++++++++++++++++++++++++++--------- 1 file changed, 78 insertions(+), 25 deletions(-) diff --git a/Arrays/maximum_subarray.cpp b/Arrays/maximum_subarray.cpp index 4f143c55..d52e135e 100644 --- a/Arrays/maximum_subarray.cpp +++ b/Arrays/maximum_subarray.cpp @@ -1,31 +1,84 @@ -// Subarray with maximum sum O(n^3) -#include +// Maximum Subarray +/* + The maxSubarraySum function takes an integer slice arr as input and returns the maximum subarray + sum as an integer. + + The maxSoFar variable is initialized to the smallest possible integer value, since any valid subarray + sum must be greater than or equal to this value. The maxEndingHere variable is initialized to 0, + since an empty subarray has a sum of 0. + + The function then iterates through the elements of arr, updating maxEndingHere and maxSoFar as necessary. + At each iteration, the maximum ending here is updated by adding the current element to it. + If the maximum ending here becomes negative, it is reset to 0, since any subarray that includes a negative + sum will not be the maximum subarray. If the maximum ending here is greater than the maximum subarray + sum so far, maxSoFar is updated to the new maximum. + + Finally, the function returns maxSoFar. + + In the main function, an example input array is defined and passed to maxSubarraySum. + The resulting maximum subarray sum is printed to the console. + + The time complexity of the above implementation of Kadane's algorithm for finding the maximum subarray sum is O(n), + where n is the length of the input array. This is because we are iterating over each element of the array only once. + + The space complexity of the implementation is O(1), as we are only using a constant amount of extra space for + storing the maximum subarray sum and the current subarray sum. +*/ +#include +#include + using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; + +// Function to find the maximum subarray sum using Kadane's algorithm +int maxSubArraySum(vector& nums) { + int maxSum = INT_MIN; + int currSum = 0; + + // Iterate over each element in the array + for (int i = 0; i < nums.size(); i++) { + // Add the current element to the current sum + currSum += nums[i]; + + // Update the maximum sum seen so far + if (currSum > maxSum) { + maxSum = currSum; + } + + // If the current sum is negative, we reset it to zero + if (currSum < 0) { + currSum = 0; + } } - int current_sum = 0, left = 0, right = 0; - int maximum_sum = INT_MIN; - for(int i = 0; i < n; i++){ - for(int j = i; j < n; j++){ - current_sum = 0; - for(int k = i; k <= j; k++){ - current_sum += V[k]; - } - if(current_sum > maximum_sum){ - maximum_sum = current_sum; - left = i; - right = j; + + // Return the maximum sum + return maxSum; +} + +// Function to calculate maximum subarray sum using brute force approach +int maxSubarraySumBruteForce(vector& nums) { + int maxSum = INT_MIN; // Initialize maximum sum to smallest integer value + // Consider all subarrays starting from i to j and calculate their sum + for (int i = 0; i < nums.size(); i++) { + int sum = 0; // Initialize sum for each subarray + for (int j = i; j < nums.size(); j++) { + sum += nums[j]; // Add element to sum + // Update maxSum if sum is greater + if (sum > maxSum) { + maxSum = sum; } - //maximum_sum = max(maximum_sum, current_sum); } } - cout << maximum_sum << endl; - for(int i = left; i <= right; i++) - cout << V[i]; + return maxSum; // Return maximum sum +} + +// Driver code to test the function +int main() { + // Example usage + vector nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; + int maxSum = maxSubArraySum(nums); + cout << "Maximum subarray sum: " << maxSum << endl; + maxSum = maxSubarraySumBruteForce(nums); + cout << "Maximum subarray sum using brute force: " << maxSum << endl; + return 0; -} \ No newline at end of file +} From 6b8272fa3b652610780af716f691be8531f21bb5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:51:09 +0530 Subject: [PATCH 0781/1894] rename file --- Arrays/{maximum_subarray.cpp => maximum_subarray_sum.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{maximum_subarray.cpp => maximum_subarray_sum.cpp} (100%) diff --git a/Arrays/maximum_subarray.cpp b/Arrays/maximum_subarray_sum.cpp similarity index 100% rename from Arrays/maximum_subarray.cpp rename to Arrays/maximum_subarray_sum.cpp From e34a72721fc6a1233a7b648451061696a32fbeb2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:54:30 +0530 Subject: [PATCH 0782/1894] remove duplicate proggram --- Arrays/maximum_subarray_kadanes.cpp | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 Arrays/maximum_subarray_kadanes.cpp diff --git a/Arrays/maximum_subarray_kadanes.cpp b/Arrays/maximum_subarray_kadanes.cpp deleted file mode 100644 index ecd54587..00000000 --- a/Arrays/maximum_subarray_kadanes.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// In computer science, the maximum sum subarray problem, also known as the maximum segment sum problem, -// is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers -// Subarray with maximum sum using kadane's algo O(n) -#include -using namespace std; -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int curr_sum = 0; - int max_sum_so_far = INT_MIN; - for(int x : V){ - curr_sum += x; - max_sum_so_far = max(curr_sum, max_sum_so_far); - curr_sum = max(curr_sum, 0); - } - cout << max_sum_so_far; - return 0; -} \ No newline at end of file From fab19347d485e72d02a2058a10de11333178ad05 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:54:37 +0530 Subject: [PATCH 0783/1894] add max_subarray_sum in python --- Arrays/maximum_subarray_sum.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Arrays/maximum_subarray_sum.py diff --git a/Arrays/maximum_subarray_sum.py b/Arrays/maximum_subarray_sum.py new file mode 100644 index 00000000..3f1a6b12 --- /dev/null +++ b/Arrays/maximum_subarray_sum.py @@ -0,0 +1,29 @@ +def max_subarray_sum(arr): + """ + Returns the maximum sum of a contiguous subarray in the given array. + + Parameters: + arr (list): A list of integers. + + Returns: + int: The maximum sum of a contiguous subarray. + + """ + + # Initialize variables to keep track of the current sum and maximum sum + curr_sum = max_sum = arr[0] + + # Loop through the array starting from the second element + for i in range(1, len(arr)): + + # Update the current sum by adding the current element + curr_sum += arr[i] + + # If the current sum is less than the current element, start a new subarray + curr_sum = max(curr_sum, arr[i]) + + # Update the maximum sum if the current sum is greater + max_sum = max(max_sum, curr_sum) + + # Return the maximum sum + return max_sum From 464addd67c77f9dc729a8d8e9c6c6c5d0df05d2d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:55:26 +0530 Subject: [PATCH 0784/1894] add description, time and space complexity --- Arrays/maximum_subarray_sum.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Arrays/maximum_subarray_sum.py b/Arrays/maximum_subarray_sum.py index 3f1a6b12..a95fd403 100644 --- a/Arrays/maximum_subarray_sum.py +++ b/Arrays/maximum_subarray_sum.py @@ -1,3 +1,24 @@ +''' + The max_subarray_sum function takes an array arr as input and returns the maximum sum of a + contiguous subarray in the given array. + + The function initializes two variables curr_sum and max_sum to the first element of the array. + It then loops through the rest of the array starting from the second element. + + Inside the loop, the function updates the curr_sum variable by adding the current element to it. + If the current sum is less than the current element, it means that starting a new subarray at this + point will result in a greater sum, so the function starts a new subarray with the current element. + The max_sum variable is then updated with the maximum value of max_sum and curr_sum. + + Once the loop is finished, the function returns the max_sum variable as the maximum sum of a + contiguous subarray in the given array. + + The time complexity of this algorithm is O(n), where n is the length of the input array, + since we only loop through the array once. + + The space complexity is O(1), since we only use + a constant amount of extra space to store the current sum and maximum sum variables. +''' def max_subarray_sum(arr): """ Returns the maximum sum of a contiguous subarray in the given array. From c8f0fcc116653a0ffbb59386a03856ba12ca5c0b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:57:24 +0530 Subject: [PATCH 0785/1894] add example io --- Arrays/maximum_subarray_sum.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Arrays/maximum_subarray_sum.py b/Arrays/maximum_subarray_sum.py index a95fd403..2d8075fd 100644 --- a/Arrays/maximum_subarray_sum.py +++ b/Arrays/maximum_subarray_sum.py @@ -18,6 +18,11 @@ The space complexity is O(1), since we only use a constant amount of extra space to store the current sum and maximum sum variables. + + Example Input: arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + Example Output: 6 + Explanation: The maximum subarray sum is [4, -1, 2, 1] which adds up to 6. + ''' def max_subarray_sum(arr): """ @@ -48,3 +53,6 @@ def max_subarray_sum(arr): # Return the maximum sum return max_sum + +arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] +print(max_subarray_sum(arr)) \ No newline at end of file From 2f9054472eae9764c02cde9d2e73885570801035 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Apr 2023 08:57:46 +0530 Subject: [PATCH 0786/1894] add example io --- Arrays/maximum_subarray_sum.cpp | 5 +++++ Arrays/maximum_subarray_sum.go | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/Arrays/maximum_subarray_sum.cpp b/Arrays/maximum_subarray_sum.cpp index d52e135e..8534e6a6 100644 --- a/Arrays/maximum_subarray_sum.cpp +++ b/Arrays/maximum_subarray_sum.cpp @@ -23,6 +23,11 @@ The space complexity of the implementation is O(1), as we are only using a constant amount of extra space for storing the maximum subarray sum and the current subarray sum. + + Example Input: arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + Example Output: 6 + Explanation: The maximum subarray sum is [4, -1, 2, 1] which adds up to 6. + */ #include #include diff --git a/Arrays/maximum_subarray_sum.go b/Arrays/maximum_subarray_sum.go index 10436d40..f2ee3507 100644 --- a/Arrays/maximum_subarray_sum.go +++ b/Arrays/maximum_subarray_sum.go @@ -23,6 +23,11 @@ The space complexity of the implementation is O(1), as we are only using a constant amount of extra space for storing the maximum subarray sum and the current subarray sum. + + Example Input: arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + Example Output: 6 + Explanation: The maximum subarray sum is [4, -1, 2, 1] which adds up to 6. + */ package main From 2d064a269536cd51340c27d3f7509eab66cbb410 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:05:12 +0530 Subject: [PATCH 0787/1894] add ispallidnrome in c++ --- Arrays/is_pallindrome.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Arrays/is_pallindrome.cpp diff --git a/Arrays/is_pallindrome.cpp b/Arrays/is_pallindrome.cpp new file mode 100644 index 00000000..172517dd --- /dev/null +++ b/Arrays/is_pallindrome.cpp @@ -0,0 +1,35 @@ +#include +#include + +using namespace std; + +/** + * @brief Function to check whether a string is a palindrome or not + * + * @param str String to check + * @return true if the string is a palindrome, false otherwise + */ +bool isPalindrome(string str) { + int left = 0; // initialize left index to 0 + int right = str.length() - 1; // initialize right index to last character + + while (left < right) { // while left index is less than right index + if (str[left] != str[right]) { // if characters at left and right indices do not match + return false; // the string is not a palindrome + } + left++; // move left index to the right + right--; // move right index to the left + } + return true; // the string is a palindrome +} + +int main() { + string str = "racecar"; + bool isPal = isPalindrome(str); + if (isPal) { + cout << str << " is a palindrome" << endl; + } else { + cout << str << " is not a palindrome" << endl; + } + return 0; +} From 19ea9570ce6c56ce540060e962c73d92e2246183 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:05:21 +0530 Subject: [PATCH 0788/1894] add description --- Arrays/is_pallindrome.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Arrays/is_pallindrome.cpp b/Arrays/is_pallindrome.cpp index 172517dd..e0be1293 100644 --- a/Arrays/is_pallindrome.cpp +++ b/Arrays/is_pallindrome.cpp @@ -1,3 +1,23 @@ +/* + Write a function that takes in a non-empty string and that returns a boolean + representing whether the string is a palindrome. + Sample Input: abba + Output: True + Sample Input: aberba + Output: False + + Explanation: + we define a function isPalindrome that takes in a string and returns true if the string is a palindrome, + and false otherwise. The function uses two indices, left and right, initialized to the beginning and + end of the string respectively. It then iterates through the string by moving the left index to the + right and the right index to the left, checking whether the characters at these indices match. + If the characters do not match, the function returns false, indicating that the string is not a + palindrome. If the entire string is iterated through and all characters match, + the function returns true, indicating that the string is a palindrome. + + In the main function, we call the isPalindrome function on the string "racecar" and print the result. + The output will be "racecar is a palindrome". +*/ #include #include From 57e5bfd3237d29ea3d555bcf5263e3c98815b379 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:06:32 +0530 Subject: [PATCH 0789/1894] add is_pallindrome in java --- Arrays/is_pallindrome.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Arrays/is_pallindrome.java diff --git a/Arrays/is_pallindrome.java b/Arrays/is_pallindrome.java new file mode 100644 index 00000000..271b31a7 --- /dev/null +++ b/Arrays/is_pallindrome.java @@ -0,0 +1,27 @@ +/** + * This function takes in a non-empty string and returns a boolean representing + * whether the string is a palindrome. + * + * @param str the string to check for palindrome + * @return true if str is a palindrome, false otherwise + */ +public static boolean isPalindrome(String str) { + // Remove all non-alphanumeric characters from the string and convert to lowercase + String cleanStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); + + // Initialize two pointers, one at the beginning and one at the end of the string + int left = 0; + int right = cleanStr.length() - 1; + + // Iterate through the string from both ends, comparing characters + while (left < right) { + if (cleanStr.charAt(left) != cleanStr.charAt(right)) { + return false; + } + left++; + right--; + } + + // If the loop completes without returning false, the string is a palindrome + return true; +} From 11d712600336441e41975c04077dfc91e078f60b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:07:27 +0530 Subject: [PATCH 0790/1894] add description --- Arrays/is_pallindrome.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Arrays/is_pallindrome.java b/Arrays/is_pallindrome.java index 271b31a7..f76c1425 100644 --- a/Arrays/is_pallindrome.java +++ b/Arrays/is_pallindrome.java @@ -1,3 +1,23 @@ +/* + Write a function that takes in a non-empty string and that returns a boolean + representing whether the string is a palindrome. + Sample Input: abba + Output: True + Sample Input: aberba + Output: False + + Explanation: + This function takes in a non-empty string and returns a boolean representing whether the string + is a palindrome. It first removes all non-alphanumeric characters from the string and converts + it to lowercase using the replaceAll() and toLowerCase() string methods, respectively. + + It then initializes two pointers, one at the beginning and one at the end of the cleaned string. + It iterates through the string from both ends, comparing characters at each step. + If the characters do not match, it returns false. + + If the loop completes without returning false, the string is a palindrome and the function + returns true. +*/ /** * This function takes in a non-empty string and returns a boolean representing * whether the string is a palindrome. From 809837ecfa9f94fb0ce768425450fd7af5c109fe Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:09:00 +0530 Subject: [PATCH 0791/1894] add is pallindrome in python --- Arrays/is_pallindrome.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Arrays/is_pallindrome.py diff --git a/Arrays/is_pallindrome.py b/Arrays/is_pallindrome.py new file mode 100644 index 00000000..fe5e2f3c --- /dev/null +++ b/Arrays/is_pallindrome.py @@ -0,0 +1,16 @@ +def is_palindrome(s: str) -> bool: + """ + This function takes in a non-empty string and returns a boolean indicating + whether the string is a palindrome or not. + + Parameters: + s (str): The input string + + Returns: + bool: True if s is a palindrome, False otherwise + """ + # Remove all non-alphanumeric characters and convert to lowercase + s = ''.join(filter(str.isalnum, s)).lower() + + # Check if the reversed string is equal to the original string + return s == s[::-1] From bbe3ec7fcc3bf10a0c9c149ad5285429bd51d755 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 13:09:39 +0530 Subject: [PATCH 0792/1894] add description --- Arrays/is_pallindrome.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Arrays/is_pallindrome.py b/Arrays/is_pallindrome.py index fe5e2f3c..0f84f9be 100644 --- a/Arrays/is_pallindrome.py +++ b/Arrays/is_pallindrome.py @@ -1,3 +1,19 @@ +''' + Write a function that takes in a non-empty string and that returns a boolean + representing whether the string is a palindrome. + Sample Input: abba + Output: True + Sample Input: aberba + Output: False + + Explanation: + + In this implementation, we use Python's filter() function to remove all non-alphanumeric characters + from the string and lower() method to convert the string to lowercase. Then we check if the reversed + string is equal to the original string using the slice notation [::-1]. If the two strings are equal, + we return True, indicating that the input string is a palindrome; otherwise, we return False. +''' + def is_palindrome(s: str) -> bool: """ This function takes in a non-empty string and returns a boolean indicating From 41c0cfcd537559e6dbe96aa1531c391c5c9daebc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 14:11:50 +0530 Subject: [PATCH 0793/1894] add is pallindrome in js --- Arrays/is_pallindrome.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Arrays/is_pallindrome.js diff --git a/Arrays/is_pallindrome.js b/Arrays/is_pallindrome.js new file mode 100644 index 00000000..19b5e926 --- /dev/null +++ b/Arrays/is_pallindrome.js @@ -0,0 +1,21 @@ +/** + * Checks if a given string is a palindrome. + * @param {string} str - The input string to check. + * @returns {boolean} True if the string is a palindrome, false otherwise. + */ +function isPalindrome(str) { + // Convert the input string to lowercase and remove any non-alphanumeric characters + str = str.toLowerCase().replace(/[^a-z0-9]/g, ""); + + // Use two pointers to compare characters from the start and end of the string + let left = 0; + let right = str.length - 1; + while (left < right) { + if (str[left] !== str[right]) { + return false; + } + left++; + right--; + } + return true; +} From 887d4bfce96c5f9350f679b20ab27cdf5cb12d8d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 14:12:50 +0530 Subject: [PATCH 0794/1894] add description --- Arrays/is_pallindrome.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Arrays/is_pallindrome.js b/Arrays/is_pallindrome.js index 19b5e926..134076d1 100644 --- a/Arrays/is_pallindrome.js +++ b/Arrays/is_pallindrome.js @@ -1,3 +1,22 @@ +/* + Write a function that takes in a non-empty string and that returns a boolean + representing whether the string is a palindrome. + Sample Input: abba + Output: True + Sample Input: aberba + Output: False + + Explanation : + The function takes in a non-empty string as input and returns a boolean value indicating whether the string + is a palindrome or not. It first converts the input string to lowercase and removes any non-alphanumeric + characters using a regular expression. It then uses two pointers (one starting from the beginning of the + string and the other starting from the end) to compare characters from opposite ends of the string. + If any mismatch is found, the function returns false immediately. If the entire string is traversed + without finding any mismatches, the function returns true, indicating that the string is a palindrome. + + Note that this implementation treats uppercase and lowercase letters as equivalent (i.e., "A" is the same as "a") + and ignores any non-alphanumeric characters (such as spaces or punctuation marks) when checking for palindromicity. +*/ /** * Checks if a given string is a palindrome. * @param {string} str - The input string to check. From 71a988f76af50a8bea30fae43e0abdf59e6e0a18 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 14:14:23 +0530 Subject: [PATCH 0795/1894] remove duplicate program --- Strings/is_ palindrome.js | 45 ---------------------------- Strings/is_palindrome.cpp | 49 ------------------------------- Strings/is_pallindrome.go | 58 ------------------------------------- Strings/is_pallindrome.java | 28 ------------------ Strings/is_pallindrome.py | 27 ----------------- 5 files changed, 207 deletions(-) delete mode 100644 Strings/is_ palindrome.js delete mode 100644 Strings/is_palindrome.cpp delete mode 100644 Strings/is_pallindrome.go delete mode 100644 Strings/is_pallindrome.java delete mode 100644 Strings/is_pallindrome.py diff --git a/Strings/is_ palindrome.js b/Strings/is_ palindrome.js deleted file mode 100644 index 80f863c8..00000000 --- a/Strings/is_ palindrome.js +++ /dev/null @@ -1,45 +0,0 @@ -// Check whether a given string is a Valid Palindrome in Javascript - -// Two pointer approach -function isPalindromeTwoPointer(inputString) { - var string = inputString.trim().toLowerCase(); - - if (string == "") { - return false; - } - - var leftIndex = 0; - var rightIndex = string.length - 1; - // compare start and end position - // if mismatch occurs then return false - // if mismatch doesnot occur then increment start pointer and decrement end pointer till they meet - while (leftIndex < rightIndex) { - if (string[leftIndex] !== string[rightIndex]) { - return false; - } - leftIndex++; - rightIndex--; - } - return true; -} - -// Reverse String approach -function isPalindrome(inputString) { - var stringArray = inputString.trim().toLowerCase().split(""); - - var reverseString = ""; - - for (i = stringArray.length - 1; i >= 0; i--) { - reverseString += stringArray[i]; - } - - if (inputString.trim().toLowerCase() == reverseString.trim().toLowerCase()) { - return true; - } else { - return false; - } -} - -// Driver code -console.log(isPalindrome("Kaayak")); -console.log(isPalindromeTwoPointer("Kayak")); diff --git a/Strings/is_palindrome.cpp b/Strings/is_palindrome.cpp deleted file mode 100644 index 50b8483a..00000000 --- a/Strings/is_palindrome.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - is_palindrome in c++ - code by Brian Salkas - */ - -#include -// start l and r at the beginning and end of the string -// each time we loop, we incrament l and decrament r -// and check if the 'lth' char of the string is -// equal to the 'rth' char. -// If they are not equal return false -// we continue looping as long as l is less than r -// if the loop completes without returning false, -// then our string is a palindrome and we return true -bool is_palindrome(std::string const& str) { - size_t l = 0, r = str.size() - 1; - while (l < r) { - if (str[l++] != str[r--]) { - return false; - } - } - return true; -} -// this function contains identical logic to the iterative one above -// notice the second parameter "size_t l=0", this is a default argument -// this means if you do not pass a second parameter, l will be assigned to -// zero. on the next line, we assign r to str.size() - 1 - l, -// which means that each time we incrament l we decrament r! -// base case 1: return true if we get to middle without returning false -// base case 2: return false if not palindrome -// recursive case: call function again incramenting l. -bool is_palindrome_rec(std::string const& str, size_t l=0) { - size_t r = str.size() -1- l; - if (r <= l) { // base case 1 - return true; - } - if (str[l] != str[r]) { // base case 2 - return false; - } - return is_palindrome_rec(str, l+1); // recursive case -} - -// driver function with test cases -int main() { - std::cout << "hello: " << (is_palindrome("hello") ?"true" : "false") << '\n'; - std::cout << "racecar: " << (is_palindrome("racecar") ?"true" : "false") << '\n'; - std::cout << "hello: " << (is_palindrome_rec("hello") ?"true" : "false") << '\n'; - std::cout << "racecar: " << (is_palindrome_rec("racecar") ?"true" : "false") << '\n'; -} diff --git a/Strings/is_pallindrome.go b/Strings/is_pallindrome.go deleted file mode 100644 index 44379ab4..00000000 --- a/Strings/is_pallindrome.go +++ /dev/null @@ -1,58 +0,0 @@ -// Valid Palindrome -package main - -import ( - "fmt" - "strings" -) - -// The two pointers approach would allow us to solve this problem in linear time and without any extra space complexity or built-in functions because we’ll be simply traverse the array from the start and the end at the same time to reach the middle of the string. -// Time complexity -// The time complexity is O(n) where n is the number of characters present in the string. -// Space complexity O(1) because we use constant space to store two indices. -// Sample Input : RACEACAR -// Output: False - -func isPalindrome(inputString string) bool { - left := 0 - right := len(inputString) - 1 - fmt.Printf("\tThe current element being pointed by the left index is %c\n", inputString[left]) - fmt.Printf("\tThe current element being pointed by the right index is %c\n", inputString[right]) - for left < right { - fmt.Printf("\tWe check if the two elements are indeed the same, in this case...\n") - - // If the elements at index left and index right are not equal - if inputString[left] != inputString[right] { - fmt.Printf("\tThe elements are not the same, hence we return false\n") - - // then the symmetry is broken, the string is not a palindrome - return false - } - - fmt.Printf("\tThey are the same, thus we move the two pointers toward the middle to continue the\n\tverfification process\n\n") - - // Heading towards the right - left++ - - // Heading towards the middle - right-- - - fmt.Printf("\tThe new element at the left pointer is %c\n", inputString[left]) - fmt.Printf("\tThe new element at the right pointer is %c\n", inputString[right]) - } - - // We reached the middle of the string without finding a mismatch, so it is a palindrome - return true -} - -// Driver code -func main() { - str := []string {"RACEACAR", "A", "ABCDEFGFEDCBA", "ABC", "ABCBA", "ABBA", "RACEACAR"} - for i, s := range str { - fmt.Printf("Test Case # %d\n", i + 1) - fmt.Printf("%s\n", strings.Repeat("-", 100)) - fmt.Printf("\tThe input string is '%s' and the length of the string is %d.\n", s, len(s)) - fmt.Printf("\nIs it a palindrome?.....%v\n", isPalindrome(s)) - fmt.Printf("%s\n", strings.Repeat("-", 100)) - } -} \ No newline at end of file diff --git a/Strings/is_pallindrome.java b/Strings/is_pallindrome.java deleted file mode 100644 index 8bec3d76..00000000 --- a/Strings/is_pallindrome.java +++ /dev/null @@ -1,28 +0,0 @@ -/* Valid Palindrome - -1 We define a method isPalindrome that takes a String argument s and returns a boolean value indicating whether the string is a palindrome or not. -2 We initialize two variables left and right to point to the beginning and end of the string respectively. -3 We enter a while loop that continues until left is less than right. -4 If the character at s[left] is not a letter or digit, we increment left. -5 If the character at s[right] is not a letter or digit, we decrement right. -6 If the characters at s[left] and s[right] are not equal, we return false as the string is not a palindrome. -7 If the characters are equal, we increment left and decrement right. -8 If the while loop completes without finding a mismatched pair of characters, we return true as the string is a palindrome. - -*/ -public static boolean isPalindrome(String s) { - int left = 0, right = s.length() - 1; - while (left < right) { - if (!Character.isLetterOrDigit(s.charAt(left))) { - left++; - } else if (!Character.isLetterOrDigit(s.charAt(right))) { - right--; - } else if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { - return false; - } else { - left++; - right--; - } - } - return true; -} diff --git a/Strings/is_pallindrome.py b/Strings/is_pallindrome.py deleted file mode 100644 index 98d8c2c1..00000000 --- a/Strings/is_pallindrome.py +++ /dev/null @@ -1,27 +0,0 @@ -# Valid Palindrome -''' - 1 The isPalindrome() function takes a string s as input. - 2 The first line of the function converts the string to lowercase and - removes all non-alphanumeric characters. This is achieved using a list comprehension, - where each character in s is checked if it is alphanumeric. - If it is, it is added to a new string, otherwise it is ignored. - The resulting string only contains alphanumeric characters in lowercase. - 3 We then loop through the string from the beginning to the middle character - (the // operator divides the length of the string by 2 and rounds down to the nearest integer). - For each character, we compare it to its corresponding character from the end of the string - (i.e., the len(s) - i - 1-th character), to check if they are the same. - 4 If at any point we find two characters that are not the same, we know that the string is not a - palindrome and return False. - 5 If we complete the loop without finding any mismatches, we know that the string is a palindrome - and return True. -''' -def isPalindrome(s): - # Convert string to lowercase and remove all non-alphanumeric characters - s = "".join(c.lower() for c in s if c.isalnum()) - - # Loop through the string and compare each character to its corresponding character from the end - for i in range(len(s) // 2): - if s[i] != s[len(s) - i - 1]: - return False - - return True From ed2d20ec3f6abff093b609df7300b7279df392e0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 14:14:40 +0530 Subject: [PATCH 0796/1894] move to strings --- {Arrays => Strings}/is_pallindrome.cpp | 0 {Arrays => Strings}/is_pallindrome.go | 0 {Arrays => Strings}/is_pallindrome.java | 0 {Arrays => Strings}/is_pallindrome.js | 0 {Arrays => Strings}/is_pallindrome.py | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {Arrays => Strings}/is_pallindrome.cpp (100%) rename {Arrays => Strings}/is_pallindrome.go (100%) rename {Arrays => Strings}/is_pallindrome.java (100%) rename {Arrays => Strings}/is_pallindrome.js (100%) rename {Arrays => Strings}/is_pallindrome.py (100%) diff --git a/Arrays/is_pallindrome.cpp b/Strings/is_pallindrome.cpp similarity index 100% rename from Arrays/is_pallindrome.cpp rename to Strings/is_pallindrome.cpp diff --git a/Arrays/is_pallindrome.go b/Strings/is_pallindrome.go similarity index 100% rename from Arrays/is_pallindrome.go rename to Strings/is_pallindrome.go diff --git a/Arrays/is_pallindrome.java b/Strings/is_pallindrome.java similarity index 100% rename from Arrays/is_pallindrome.java rename to Strings/is_pallindrome.java diff --git a/Arrays/is_pallindrome.js b/Strings/is_pallindrome.js similarity index 100% rename from Arrays/is_pallindrome.js rename to Strings/is_pallindrome.js diff --git a/Arrays/is_pallindrome.py b/Strings/is_pallindrome.py similarity index 100% rename from Arrays/is_pallindrome.py rename to Strings/is_pallindrome.py From 314b7cf4fa6ae2d935e493a54cad5e77f4bf05c2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Apr 2023 14:18:17 +0530 Subject: [PATCH 0797/1894] update links --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f9247772..3097c48a 100644 --- a/README.md +++ b/README.md @@ -543,7 +543,7 @@ The pointers can be used to iterate the data structure in one or both directions - Three Number Sum [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.java) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/triplet_sum.js) -- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_%20palindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/tree/main/Strings/is_palindrome.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) +- Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) From 3d034bc71cafad67dca025871eb239979e720dc5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:41:02 +0530 Subject: [PATCH 0798/1894] modify solution --- sorting/bubble_sort.cpp | 46 +++++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index c17ea866..1916228b 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -10,29 +10,31 @@ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] -#include +#include +#include + using namespace std; -void BubbleSort(int A[], int n){ - int flag = 0; - for(int i = 0; i < n - 1; i++){ - for(int j = 0; j < n - i; j++){ - if(A[j] > A[j+1]){ - int temp = A[j]; - A[j] = A[j+1]; - A[j+1] = temp; - flag = 1; // // hack if the array is already sorted, no need for redundant passes - } - } - if(flag == 0){ cout << "Already sorted so no further redundant passes best case O(n)"; break;} - } +void bubbleSort(vector& arr) { + int n = arr.size(); + // Traverse through all array elements + for (int i = 0; i < n - 1; i++) { + // Last i elements are already sorted + for (int j = 0; j < n - i - 1; j++) { + // Swap adjacent elements if they are in the wrong order + if (arr[j] > arr[j + 1]) { + swap(arr[j], arr[j + 1]); + } + } + } } -int main(){ - int A[] = {5,1,2,3,4,5}; - BubbleSort(A,6); - for(int i = 0; i < 6; i++){ - cout << A[i] << " "; - } - -return 0; + +int main() { + vector arr = {64, 25, 12, 22, 11}; + bubbleSort(arr); + cout << "Sorted array: "; + for (auto i : arr) { + cout << i << " "; + } + return 0; } From e925b7e39cc58df46874939dbb84891bc2b7ff91 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:42:10 +0530 Subject: [PATCH 0799/1894] modify solution --- sorting/bubble_sort.go | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/sorting/bubble_sort.go b/sorting/bubble_sort.go index e24a5a86..0a1e52ee 100644 --- a/sorting/bubble_sort.go +++ b/sorting/bubble_sort.go @@ -15,22 +15,28 @@ package main import "fmt" -func main() { - arr := [6]int{2, 1, 3, 5, 4, 0} - // arr := [6]int{0, 1, 2, 3, 4, 5} uncomment for best case +func bubbleSort(arr []int) { + n := len(arr) flag := true - for i := 0; i < 6; i++ { - for j := 0; j < 6 - i - 1; j++ { - if(arr[j] > arr[j + 1]) { - arr[j], arr[j + 1] = arr[j + 1], arr[j] - flag = false // hack if the array is already sorted, no need for redundant passes - } - } + // Traverse through all array elements + for i := 0; i < n-1; i++ { + // Last i elements are already sorted + for j := 0; j < n-i-1; j++ { + // Swap adjacent elements if they are in the wrong order + if arr[j] > arr[j+1] { + arr[j], arr[j+1] = arr[j+1], arr[j] + flag = false + } + } if flag { fmt.Println("Already sorted so no further redundant passes best case O(n)") break } - } - fmt.Println(arr) + } +} -} \ No newline at end of file +func main() { + arr := []int{64, 25, 12, 22, 11} + bubbleSort(arr) + fmt.Println("Sorted array:", arr) +} From 760b4db0c5d0e71b6d756865f2f7463a0b2c6b8a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:42:27 +0530 Subject: [PATCH 0800/1894] modify solution --- sorting/bubble_sort.js | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/sorting/bubble_sort.js b/sorting/bubble_sort.js index 76232be3..3672d5b9 100644 --- a/sorting/bubble_sort.js +++ b/sorting/bubble_sort.js @@ -11,23 +11,22 @@ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] -const inputArr = [4, 5, 67, 56, 3, 35, 45]; - -const bubbleSort = (arr) => { - let len = arr.length; - - //loop to access each array element - for (let i = 0; i < len - 1; i++) - //loop to compare array elements - for (let j = i + 1; j < len; j++) - //compare two adjacent elements - if (arr[i] > arr[j]) { - //swapping elements if elements are not in the intended order - let temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; +function bubbleSort(arr) { + var n = arr.length; + // Traverse through all array elements + for (var i = 0; i < n - 1; i++) { + // Last i elements are already sorted + for (var j = 0; j < n - i - 1; j++) { + // Swap adjacent elements if they are in the wrong order + if (arr[j] > arr[j + 1]) { + var temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; } - return arr; -}; -bubbleSort(inputArr); -console.log(inputArr); + } + } +} + +var arr = [64, 25, 12, 22, 11]; +bubbleSort(arr); +console.log("Sorted array: " + arr); From db0bd84f77b7bef4ef57dc29860ba2e348b9ac95 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:42:45 +0530 Subject: [PATCH 0801/1894] modify solution --- sorting/bubble_sort.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/sorting/bubble_sort.py b/sorting/bubble_sort.py index 7485a324..7492eff5 100644 --- a/sorting/bubble_sort.py +++ b/sorting/bubble_sort.py @@ -10,19 +10,17 @@ # Sample Input : [2, 1, 9, 3, 5, 4, 0] # Output : [0 1 2 3 4 5 9] -data = [] -n = int(input("Enter the number of elements")) # Total number of elements in an array -for i in range(0,n): - num = int(input()) # Asking user the element of an array - data.append(num) # Appending the element in an array +def bubbleSort(arr): + n = len(arr) + # Traverse through all array elements + for i in range(n - 1): + # Last i elements are already sorted + for j in range(0, n - i - 1): + # Swap adjacent elements if they are in the wrong order + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] -data_copy = data[:] # Making copy of the array data - -for i in range(0, len(data_copy)): - for j in range(0, len(data_copy) - i - 1): - if(data_copy[j] > data_copy[j + 1]): - data_copy[j], data_copy[j + 1] = data_copy[j + 1], data_copy[j] - -print(data_copy) -print(sorted(data)) +arr = [64, 25, 12, 22, 11] +bubbleSort(arr) +print("Sorted array:", arr) From 92856cbc0ec96fbb2a9cf229f6b5ec889088c04e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:44:11 +0530 Subject: [PATCH 0802/1894] modify solution --- sorting/bubble_sort.java | 49 ++++++++++++++++------------------------ 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/sorting/bubble_sort.java b/sorting/bubble_sort.java index 90088b91..0cfba00f 100644 --- a/sorting/bubble_sort.java +++ b/sorting/bubble_sort.java @@ -12,40 +12,29 @@ // Output : [0 1 2 3 4 5 9] - - -package sorting; - -import java.util.Arrays; - public class BubbleSort { - public static void main(String[] args) { - int[] nums = {4, 5, 6, 8, 17, 19, 45, -78, -87, 0, 11}; - bubble(nums); - System.out.println(Arrays.toString(nums)); - - - } - static void bubble(int[] arr){ - boolean swapped; - // run the steps n-1 times - for(int i = 0; i < arr.length; i++){ - swapped = false; - // for each step, max item will come at the last respective index - for(int j = 1; j < arr.length-i; j++){ - // swap if the item is smaller than the previous item - if (arr[j] > arr[j-1]){ + public static void bubbleSort(int[] arr) { + int n = arr.length; + // Traverse through all array elements + for (int i = 0; i < n - 1; i++) { + // Last i elements are already in place + for (int j = 0; j < n - i - 1; j++) { + // Swap adjacent elements if they are in the wrong order + if (arr[j] > arr[j + 1]) { int temp = arr[j]; - arr[j] = arr[j-1]; - arr[j-1] = temp; - swapped = true; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; } } - // if you did not swap for a particular of i, it means the array is sorted hence stop the program - if(!swapped){ - break; - } } } -} + public static void main(String[] args) { + int[] arr = {64, 34, 25, 12, 22, 11, 90}; + bubbleSort(arr); + System.out.println("Sorted array: "); + for (int i = 0; i < arr.length; i++) { + System.out.print(arr[i] + " "); + } + } +} From 0c1bd92c5c3ded2fee77c92ebbd9e57ffd921075 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:46:04 +0530 Subject: [PATCH 0803/1894] modufy description --- sorting/bubble_sort.cpp | 29 +++++++++++++++++++---------- sorting/bubble_sort.go | 29 +++++++++++++++++++---------- sorting/bubble_sort.java | 28 ++++++++++++++++++---------- sorting/bubble_sort.js | 29 +++++++++++++++++++---------- sorting/bubble_sort.py | 29 +++++++++++++++++++---------- 5 files changed, 94 insertions(+), 50 deletions(-) diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index 1916228b..d2437d91 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -1,15 +1,24 @@ -// Implementation of Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort +/* + Here's how the Bubble Sort algorithm works: -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case + 1. We start by comparing the first two elements of the array. If the first element is greater than the second + element, we swap them. + 2. We then compare the second and third elements. If the second element is greater than the third element, + we swap them. + 3. We continue this process until we reach the end of the array. At this point, the largest element will + be at the end of the array. + 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. + + The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when + the input array is already sorted. + + The space complexity is O(1) as Bubble Sort operates on the input array in-place. -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] + Bubble sort is O(n) on a list that is already sorted i.e. Best case + + Sample Input : [2, 1, 9, 3, 5, 4, 0] + Output : [0 1 2 3 4 5 9] +*/ #include #include diff --git a/sorting/bubble_sort.go b/sorting/bubble_sort.go index 0a1e52ee..e3c1da0a 100644 --- a/sorting/bubble_sort.go +++ b/sorting/bubble_sort.go @@ -1,15 +1,24 @@ -// Implementation of Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort +/* + Here's how the Bubble Sort algorithm works: -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case + 1. We start by comparing the first two elements of the array. If the first element is greater than the second + element, we swap them. + 2. We then compare the second and third elements. If the second element is greater than the third element, + we swap them. + 3. We continue this process until we reach the end of the array. At this point, the largest element will + be at the end of the array. + 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. + + The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when + the input array is already sorted. + + The space complexity is O(1) as Bubble Sort operates on the input array in-place. -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] + Bubble sort is O(n) on a list that is already sorted i.e. Best case + + Sample Input : [2, 1, 9, 3, 5, 4, 0] + Output : [0 1 2 3 4 5 9] +*/ package main diff --git a/sorting/bubble_sort.java b/sorting/bubble_sort.java index 0cfba00f..1a7a7803 100644 --- a/sorting/bubble_sort.java +++ b/sorting/bubble_sort.java @@ -1,16 +1,24 @@ -// Implementation of Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort +/* + Here's how the Bubble Sort algorithm works: -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case + 1. We start by comparing the first two elements of the array. If the first element is greater than the second + element, we swap them. + 2. We then compare the second and third elements. If the second element is greater than the third element, + we swap them. + 3. We continue this process until we reach the end of the array. At this point, the largest element will + be at the end of the array. + 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. + + The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when + the input array is already sorted. + + The space complexity is O(1) as Bubble Sort operates on the input array in-place. -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] + Bubble sort is O(n) on a list that is already sorted i.e. Best case + Sample Input : [2, 1, 9, 3, 5, 4, 0] + Output : [0 1 2 3 4 5 9] +*/ public class BubbleSort { public static void bubbleSort(int[] arr) { diff --git a/sorting/bubble_sort.js b/sorting/bubble_sort.js index 3672d5b9..af6b2ae4 100644 --- a/sorting/bubble_sort.js +++ b/sorting/bubble_sort.js @@ -1,15 +1,24 @@ -// Implementation of Bubble sort. -// Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -// that repeatedly steps through the input list element by element, -// comparing the current element with the one after it, swapping their values if needed. -// These passes through the list are repeated until no swaps had to be performed during a pass, -// meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort +/* + Here's how the Bubble Sort algorithm works: -// Time Complexity worst-case and average complexity O(n^{2}) -// Bubble sort is O(n) on a list that is already sorted i.e. Best case + 1. We start by comparing the first two elements of the array. If the first element is greater than the second + element, we swap them. + 2. We then compare the second and third elements. If the second element is greater than the third element, + we swap them. + 3. We continue this process until we reach the end of the array. At this point, the largest element will + be at the end of the array. + 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. + + The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when + the input array is already sorted. + + The space complexity is O(1) as Bubble Sort operates on the input array in-place. -// Sample Input : [2, 1, 9, 3, 5, 4, 0] -// Output : [0 1 2 3 4 5 9] + Bubble sort is O(n) on a list that is already sorted i.e. Best case + + Sample Input : [2, 1, 9, 3, 5, 4, 0] + Output : [0 1 2 3 4 5 9] +*/ function bubbleSort(arr) { var n = arr.length; diff --git a/sorting/bubble_sort.py b/sorting/bubble_sort.py index 7492eff5..16e30fd7 100644 --- a/sorting/bubble_sort.py +++ b/sorting/bubble_sort.py @@ -1,15 +1,24 @@ -# Implementation of Bubble sort. -# Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm -# that repeatedly steps through the input list element by element, -# comparing the current element with the one after it, swapping their values if needed. -# These passes through the list are repeated until no swaps had to be performed during a pass, -# meaning that the list has become fully sorted. (Source wiki) https://en.wikipedia.org/wiki/Bubble_sort +''' + Here's how the Bubble Sort algorithm works: -# Time Complexity worst-case and average complexity O(n^{2}) -# Bubble sort is O(n) on a list that is already sorted i.e. Best case + 1. We start by comparing the first two elements of the array. If the first element is greater than the second + element, we swap them. + 2. We then compare the second and third elements. If the second element is greater than the third element, + we swap them. + 3. We continue this process until we reach the end of the array. At this point, the largest element will + be at the end of the array. + 4. We then repeat steps 1-3 for the remaining unsorted portion of the array until the entire array is sorted. + + The time complexity of Bubble Sort is O(n^2) in the worst and average case, and O(n) in the best case when + the input array is already sorted. + + The space complexity is O(1) as Bubble Sort operates on the input array in-place. -# Sample Input : [2, 1, 9, 3, 5, 4, 0] -# Output : [0 1 2 3 4 5 9] + Bubble sort is O(n) on a list that is already sorted i.e. Best case + + Sample Input : [2, 1, 9, 3, 5, 4, 0] + Output : [0 1 2 3 4 5 9] +''' def bubbleSort(arr): n = len(arr) From 5be25ecf7cfb1fbc86aa2223291b7d1fa90c106f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:49:55 +0530 Subject: [PATCH 0804/1894] modify program --- sorting/insertion_sort.cpp | 44 +++++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 0b4e274d..381b4b96 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -17,25 +17,35 @@ Sample input: [0, 2, 1,-1, 10, 3, 4] Output: [-1 0 1 2 3 4 10] */ -#include -using namespace std; +#include +#include +using namespace std; -int main(){ - int temp = 0; - int array[] = {5,9,77,1,2,3}; - for (int i = 1; i < 6; i++) { - int j = i; - while (j > 0 && array[j] < array[j - 1]) { - temp = array[j]; - array[j] = array[j - 1]; - array[j - 1] = temp; - j -= 1; +void insertionSort(vector& arr) { + int n = arr.size(); + for(int i=1; i=0 && arr[j]>key) { + arr[j+1] = arr[j]; + j--; } + arr[j+1] = key; // insert the key at its sorted position + } +} + +int main() { + vector arr = {3, 5, 1, 4, 2}; + insertionSort(arr); + + cout << "Sorted Array: "; + for(int num: arr) { + cout << num << " "; } - for(int i = 0; i < 6; i++){ - cout << array[i] << " "; - } - -return 0; + cout << endl; + return 0; } From ff9f6d571dc2871e116cefd932db55ada8cdc9d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:53:10 +0530 Subject: [PATCH 0805/1894] modify description --- sorting/insertion_sort.cpp | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 381b4b96..1e905069 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,20 +1,23 @@ /* -Implementation of insertion sort in C++. -Insertion sort is a simple sorting algorith that iterates through -the list starting at the second element. We compare each element -to the preceding elements, slide over the preceding larger (or smaller) -elements, and insert the original element into the empty position. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + it in ascending order using the Insertion Sort algorithm. -Time Complexity worst-case and average complexity O(n^{2}) + The algorithm works by iterating over the array from the second element to the end. -Insertion sort is inefficient for large arrays. However it is fast for -small arrays and typically more efficient than bubble sort and selection -sort due to not making as many comparisons on average. + For each element, it compares it with the previous elements in the array and inserts it in the correct position. -Source: https://en.wikipedia.org/wiki/Insertion_sort + The current variable holds the value of the current element being compared. -Sample input: [0, 2, 1,-1, 10, 3, 4] -Output: [-1 0 1 2 3 4 10] + The j variable holds the index of the previous element being compared. + + The loop compares the current value with the previous values in the array and shifts the values to the right to make space for the current value. + + Once the correct position is found, the current value is inserted into the array. + + Finally, the sorted array is returned. In the main function, we define an array of integers, sort it using the InsertionSort function, and print the sorted array. + + Sample input: [0, 2, 1,-1, 10, 3, 4] + Output: [-1 0 1 2 3 4 10] */ #include @@ -22,6 +25,9 @@ Output: [-1 0 1 2 3 4 10] using namespace std; + +// InsertionSort is a function that takes an array of integers and sorts it in +// ascending order using the Insertion Sort algorithm. void insertionSort(vector& arr) { int n = arr.size(); for(int i=1; i Date: Mon, 24 Apr 2023 18:53:21 +0530 Subject: [PATCH 0806/1894] modify program --- sorting/insertion_sort.go | 71 ++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 30 deletions(-) diff --git a/sorting/insertion_sort.go b/sorting/insertion_sort.go index d6eaf0e6..abbc8fa0 100644 --- a/sorting/insertion_sort.go +++ b/sorting/insertion_sort.go @@ -1,44 +1,55 @@ /* -Implementation of insertion sort in go. -Insertion sort is a simple sorting algorith that iterates through -the list starting at the second element. We compare each element -to the preceding elements, slide over the preceding larger (or smaller) -elements, and insert the original element into the empty position. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + it in ascending order using the Insertion Sort algorithm. -Time Complexity worst-case and average complexity O(n^{2}) + The algorithm works by iterating over the array from the second element to the end. -Insertion sort is inefficient for large arrays. However it is fast for -small arrays and typically more efficient than bubble sort and selection -sort due to not making as many comparisons on average. + For each element, it compares it with the previous elements in the array and inserts it in the correct position. -Source: https://en.wikipedia.org/wiki/Insertion_sort + The current variable holds the value of the current element being compared. -Sample input: [0, 2, 1,-1, 10, 3, 4] -Output: [-1 0 1 2 3 4 10] + The j variable holds the index of the previous element being compared. + + The loop compares the current value with the previous values in the array and shifts the values to the right to make space for the current value. + + Once the correct position is found, the current value is inserted into the array. + + Finally, the sorted array is returned. In the main function, we define an array of integers, sort it using the InsertionSort function, and print the sorted array. + + Sample input: [0, 2, 1,-1, 10, 3, 4] + Output: [-1 0 1 2 3 4 10] */ package main import "fmt" -func main() { - a_lst := []int{0, 2, 1, -1, 10, 3, 4} - insertion_sort(a_lst) - fmt.Print(a_lst) -} - -/* - Divide the input array into two subarrays in place. The first subarray should be sorted at all times - and should start with a length of 1, while the second subarray should be unsorted. - Iterate through the unsorted subarray, inserting all of its elements into the sorted subarray - in the correct position by swapping them into place. Eventually, the entire array will be sorted. -*/ -func insertion_sort(array []int) { - for i := 1; i < len(array); i++ { - j := i - for j > 0 && array[j] < array[j - 1] { - array[j], array[j - 1] = array[j - 1], array[j] - j -= 1 +// InsertionSort is a function that takes an array of integers and sorts it in +// ascending order using the Insertion Sort algorithm. +func InsertionSort(arr []int) []int { + // Iterate over the array from the second element to the end + for i := 1; i < len(arr); i++ { + // Set the current value and the previous index + current := arr[i] + j := i - 1 + + // Compare the current value with the previous values in the array + for j >= 0 && arr[j] > current { + // Shift the values to the right to make space for the current value + arr[j+1] = arr[j] + j-- } + + // Insert the current value in the correct position + arr[j+1] = current } + + // Return the sorted array + return arr +} + +func main() { + arr := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} + sortedArr := InsertionSort(arr) + fmt.Println(sortedArr) } From cce74420aef61b3668585342955d8ebbb35fb5d2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 18:55:35 +0530 Subject: [PATCH 0807/1894] modify program --- sorting/insertion_sort.js | 67 +++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/sorting/insertion_sort.js b/sorting/insertion_sort.js index c24b003f..c7e26d4d 100644 --- a/sorting/insertion_sort.js +++ b/sorting/insertion_sort.js @@ -1,39 +1,46 @@ /* -Implementation of insertion sort in JS. -Insertion sort is a simple sorting algorith that iterates through -the list starting at the second element. We compare each element -to the preceding elements, slide over the preceding larger (or smaller) -elements, and insert the original element into the empty position. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + it in ascending order using the Insertion Sort algorithm. -Time Complexity worst-case and average complexity O(n^{2}) + The algorithm works by iterating over the array from the second element to the end. -Insertion sort is inefficient for large arrays. However it is fast for -small arrays and typically more efficient than bubble sort and selection -sort due to not making as many comparisons on average. + For each element, it compares it with the previous elements in the array and inserts it in the correct position. -Source: https://en.wikipedia.org/wiki/Insertion_sort + The current variable holds the value of the current element being compared. -Sample input: [0, 2, 1,-1, 10, 3, 4] -Output: [-1 0 1 2 3 4 10] + The j variable holds the index of the previous element being compared. + + The loop compares the current value with the previous values in the array and shifts the values to the right to make space for the current value. + + Once the correct position is found, the current value is inserted into the array. + + Finally, the sorted array is returned. In the main function, we define an array of integers, sort it using the InsertionSort function, and print the sorted array. + + Sample input: [0, 2, 1,-1, 10, 3, 4] + Output: [-1 0 1 2 3 4 10] */ -const inputArr = [4,5,67,56,3,35,45]; - -const insertionSort= (arr) => { - - //loop to access each array element - for (let i = 1; i < arr.length; i++) { - let currentValue = arr[i]; - const j = 0; - - // loop to Compare key with each element on the left of it until an element smaller than is found - for (let j = i - 1; j >= 0 && arr[j] > currentValue; j--) { - arr[j + 1] = arr[j]; - } - // Place key at after the element just smaller than it. - arr[j + 1] = currentValue; +/** + * Perform insertion sort on an array of integers in non-decreasing order. + * @param {number[]} arr - The input array to sort. + * @returns {number[]} The sorted array in non-decreasing order. + */ +function insertionSort(arr) { + // Loop through each element of the array, starting with the second. + for (let i = 1; i < arr.length; i++) { + // Save the current element to be inserted later. + let current = arr[i]; + // Loop through the sorted portion of the array backwards. + for (let j = i - 1; j >= 0 && arr[j] > current; j--) { + // Shift each element that is greater than the current element up one position. + arr[j + 1] = arr[j]; } - return arr; + // Insert the current element in its proper place. + arr[j + 1] = current; } - console.log(insertionSort(inputArr)); - \ No newline at end of file + // Return the sorted array. + return arr; +} + +const inputArr = [4, 5, 67, 56, 3, 35, 45]; +console.log(insertionSort(inputArr)); From 36ea36fdc799e09eedd70f05d1b94aa9853a933a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 19:00:11 +0530 Subject: [PATCH 0808/1894] modify program --- sorting/insertion_sort.py | 41 ++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/sorting/insertion_sort.py b/sorting/insertion_sort.py index 005bf603..888a1557 100644 --- a/sorting/insertion_sort.py +++ b/sorting/insertion_sort.py @@ -17,21 +17,26 @@ Output: [-1 0 1 2 3 4 10] """ -def main(): - a_lst = [0, 2, 1,-1, 10, 3, 4] - insertion_sort(a_lst) - print(a_lst) - -# Typing can be changed if needed as python supports comparison -# of types other than int (float, strings, etc.) -def insertion_sort(a_lst: list[int]) -> None: - for idx in range(1, len(a_lst)): - value = a_lst[idx] - position = idx - 1 - while 0 <= position and value < a_lst[position]: - a_lst[position + 1] = a_lst[position] - position -= 1 - a_lst[position + 1] = value - -if __name__ == "__main__": - main() +def insertion_sort(arr): + """ + Sorts an array in ascending order using the insertion sort algorithm. + + @param arr: list of integers to be sorted + @return: sorted list of integers + """ + # iterate through every element of the array + for i in range(1, len(arr)): + # store the current element and its index + current = arr[i] + j = i - 1 + + # move all elements greater than the current element to the right + while j >= 0 and arr[j] > current: + arr[j + 1] = arr[j] + j -= 1 + + # insert the current element in its correct position + arr[j + 1] = current + + # return the sorted array + return arr From d803983ae33cbbad95ab4d0c9b378ecd4788790f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 19:00:46 +0530 Subject: [PATCH 0809/1894] add description --- sorting/insertion_sort.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/sorting/insertion_sort.py b/sorting/insertion_sort.py index 888a1557..e7a645bf 100644 --- a/sorting/insertion_sort.py +++ b/sorting/insertion_sort.py @@ -1,20 +1,23 @@ """ -Implementation of insertion sort in go. -Insertion sort is a simple sorting algorith that iterates through -the list starting at the second element. We compare each element -to the preceding elements, slide over the preceding larger (or smaller) -elements, and insert the original element into the empty position. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + it in ascending order using the Insertion Sort algorithm. -Time Complexity worst-case and average complexity O(n^{2}) + The algorithm works by iterating over the array from the second element to the end. -Insertion sort is inefficient for large arrays. However it is fast for -small arrays and typically more efficient than bubble sort and selection -sort due to not making as many comparisons on average. + For each element, it compares it with the previous elements in the array and inserts it in the correct position. -Source: https://en.wikipedia.org/wiki/Insertion_sort + The current variable holds the value of the current element being compared. -Sample input: [0, 2, 1,-1, 10, 3, 4] -Output: [-1 0 1 2 3 4 10] + The j variable holds the index of the previous element being compared. + + The loop compares the current value with the previous values in the array and shifts the values to the right to make space for the current value. + + Once the correct position is found, the current value is inserted into the array. + + Finally, the sorted array is returned. In the main function, we define an array of integers, sort it using the InsertionSort function, and print the sorted array. + + Sample input: [0, 2, 1,-1, 10, 3, 4] + Output: [-1 0 1 2 3 4 10] """ def insertion_sort(arr): From 53cc4a75996e14727af2cf24cd935a929fb01297 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 24 Apr 2023 19:01:22 +0530 Subject: [PATCH 0810/1894] modify program --- sorting/insertion_sort.java | 81 ++++++++++++++++--------------------- 1 file changed, 35 insertions(+), 46 deletions(-) diff --git a/sorting/insertion_sort.java b/sorting/insertion_sort.java index 5ca92d88..085ac059 100644 --- a/sorting/insertion_sort.java +++ b/sorting/insertion_sort.java @@ -1,58 +1,47 @@ /* -Implementation of insertion sort in Java. -Insertion sort is a simple sorting algorith that iterates through -the list starting at the second element. We compare each element -to the preceding elements, slide over the preceding larger (or smaller) -elements, and insert the original element into the empty position. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + it in ascending order using the Insertion Sort algorithm. -Time Complexity worst-case and average complexity O(n^{2}) + The algorithm works by iterating over the array from the second element to the end. -Insertion sort is inefficient for large arrays. However it is fast for -small arrays and typically more efficient than bubble sort and selection -sort due to not making as many comparisons on average. + For each element, it compares it with the previous elements in the array and inserts it in the correct position. -Source: https://en.wikipedia.org/wiki/Insertion_sort + The current variable holds the value of the current element being compared. -Sample input: [0, 2, 1,-1, 10, 3, 4] -Output: [-1 0 1 2 3 4 10] -*/ - -import java.util.Arrays; + The j variable holds the index of the previous element being compared. -class InsertionSort - { + The loop compares the current value with the previous values in the array and shifts the values to the right to make space for the current value. - void insertionSort(int array[]) - { - int size = array.length; + Once the correct position is found, the current value is inserted into the array. - for (int step = 1; step < size; step++) - { - int key = array[step]; - int j = step - 1; + Finally, the sorted array is returned. In the main function, we define an array of integers, sort it using the InsertionSort function, and print the sorted array. - // Compare key with each element on the left of it until an element smaller than - // it is found. - // For descending order, change keyarray[j]. + Sample input: [0, 2, 1,-1, 10, 3, 4] + Output: [-1 0 1 2 3 4 10] +*/ - while (j >= 0 && key < array[j]) - { - array[j + 1] = array[j]; - --j; - } +// InsertionSort is a function that takes an array of integers and sorts it in +// ascending order using the Insertion Sort algorithm. +public class InsertionSort { + public static void insertionSort(int[] arr) { + int n = arr.length; + for (int i = 1; i < n; ++i) { + int key = arr[i]; + int j = i - 1; + + /* Move elements of arr[0..i-1], that are greater than key, to one + position ahead of their current position */ + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } - // Place key at after the element just smaller than it. - array[j + 1] = key; + public static void main(String[] args) { + int[] arr = { 12, 11, 13, 5, 6 }; + insertionSort(arr); + System.out.println(Arrays.toString(arr)); } - } - - // Driver code - public static void main(String args[]) - { - int[] data = { 9, 5, 1, 4, 3 }; - InsertionSort is = new InsertionSort(); - is.insertionSort(data); - System.out.println("Sorted Array in Ascending Order: "); - System.out.println(Arrays.toString(data)); - } -} \ No newline at end of file +} From a647c01c20306de4a6e3eb38aa011f51f351de23 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:13:22 +0530 Subject: [PATCH 0811/1894] add intro --- sorting/insertion_sort.cpp | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index 1e905069..83b6250e 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -1,5 +1,21 @@ /* - In this implementation, we define a function called InsertionSort that takes an array of integers and sorts + Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. + It starts with the second element of the array, compares it with the first element, and swaps them + if necessary. It then continues to the third element, compares it with the first and second elements, + and swaps it into the correct position. This process continues until the last element is compared and + sorted into its correct position in the sorted array. + + At each iteration, the algorithm assumes that the subarray to the left of the current element is already + sorted, and it searches for the correct position of the current element within that subarray by comparing + it to each element from right to left until it finds the correct position. Once it finds the correct + position, it shifts all the larger elements to the right to make space for the current element and + inserts it in its correct position. + + Insertion sort has an average-case time complexity of O(n^2) but can perform better than other O(n^2) + algorithms, such as bubble sort or selection sort, in certain cases. It is also an efficient algorithm + for small data sets or partially sorted data sets. + + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts it in ascending order using the Insertion Sort algorithm. The algorithm works by iterating over the array from the second element to the end. From 7c048a8ff43b0f804e309a9d4e01d3e4d31f0112 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:13:25 +0530 Subject: [PATCH 0812/1894] add intro --- sorting/insertion_sort.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/sorting/insertion_sort.go b/sorting/insertion_sort.go index abbc8fa0..bd64ae5a 100644 --- a/sorting/insertion_sort.go +++ b/sorting/insertion_sort.go @@ -1,4 +1,20 @@ /* + Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. + It starts with the second element of the array, compares it with the first element, and swaps them + if necessary. It then continues to the third element, compares it with the first and second elements, + and swaps it into the correct position. This process continues until the last element is compared and + sorted into its correct position in the sorted array. + + At each iteration, the algorithm assumes that the subarray to the left of the current element is already + sorted, and it searches for the correct position of the current element within that subarray by comparing + it to each element from right to left until it finds the correct position. Once it finds the correct + position, it shifts all the larger elements to the right to make space for the current element and + inserts it in its correct position. + + Insertion sort has an average-case time complexity of O(n^2) but can perform better than other O(n^2) + algorithms, such as bubble sort or selection sort, in certain cases. It is also an efficient algorithm + for small data sets or partially sorted data sets. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts it in ascending order using the Insertion Sort algorithm. From 6d699bf132b11a8c858518b0480e476fe1875b52 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:13:29 +0530 Subject: [PATCH 0813/1894] add intro --- sorting/insertion_sort.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/sorting/insertion_sort.java b/sorting/insertion_sort.java index 085ac059..f0f5fd68 100644 --- a/sorting/insertion_sort.java +++ b/sorting/insertion_sort.java @@ -1,4 +1,20 @@ /* + Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. + It starts with the second element of the array, compares it with the first element, and swaps them + if necessary. It then continues to the third element, compares it with the first and second elements, + and swaps it into the correct position. This process continues until the last element is compared and + sorted into its correct position in the sorted array. + + At each iteration, the algorithm assumes that the subarray to the left of the current element is already + sorted, and it searches for the correct position of the current element within that subarray by comparing + it to each element from right to left until it finds the correct position. Once it finds the correct + position, it shifts all the larger elements to the right to make space for the current element and + inserts it in its correct position. + + Insertion sort has an average-case time complexity of O(n^2) but can perform better than other O(n^2) + algorithms, such as bubble sort or selection sort, in certain cases. It is also an efficient algorithm + for small data sets or partially sorted data sets. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts it in ascending order using the Insertion Sort algorithm. From 39b585df6a7d30da0b9e426780f6373efa0e2ee0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:13:32 +0530 Subject: [PATCH 0814/1894] add intro --- sorting/insertion_sort.js | 16 ++++++++++++++++ sorting/insertion_sort.py | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/sorting/insertion_sort.js b/sorting/insertion_sort.js index c7e26d4d..89e5128c 100644 --- a/sorting/insertion_sort.js +++ b/sorting/insertion_sort.js @@ -1,4 +1,20 @@ /* + Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. + It starts with the second element of the array, compares it with the first element, and swaps them + if necessary. It then continues to the third element, compares it with the first and second elements, + and swaps it into the correct position. This process continues until the last element is compared and + sorted into its correct position in the sorted array. + + At each iteration, the algorithm assumes that the subarray to the left of the current element is already + sorted, and it searches for the correct position of the current element within that subarray by comparing + it to each element from right to left until it finds the correct position. Once it finds the correct + position, it shifts all the larger elements to the right to make space for the current element and + inserts it in its correct position. + + Insertion sort has an average-case time complexity of O(n^2) but can perform better than other O(n^2) + algorithms, such as bubble sort or selection sort, in certain cases. It is also an efficient algorithm + for small data sets or partially sorted data sets. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts it in ascending order using the Insertion Sort algorithm. diff --git a/sorting/insertion_sort.py b/sorting/insertion_sort.py index e7a645bf..c4b61a02 100644 --- a/sorting/insertion_sort.py +++ b/sorting/insertion_sort.py @@ -1,4 +1,20 @@ """ + Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. + It starts with the second element of the array, compares it with the first element, and swaps them + if necessary. It then continues to the third element, compares it with the first and second elements, + and swaps it into the correct position. This process continues until the last element is compared and + sorted into its correct position in the sorted array. + + At each iteration, the algorithm assumes that the subarray to the left of the current element is already + sorted, and it searches for the correct position of the current element within that subarray by comparing + it to each element from right to left until it finds the correct position. Once it finds the correct + position, it shifts all the larger elements to the right to make space for the current element and + inserts it in its correct position. + + Insertion sort has an average-case time complexity of O(n^2) but can perform better than other O(n^2) + algorithms, such as bubble sort or selection sort, in certain cases. It is also an efficient algorithm + for small data sets or partially sorted data sets. + In this implementation, we define a function called InsertionSort that takes an array of integers and sorts it in ascending order using the Insertion Sort algorithm. From 9330616d1c7f34778a56256e421b3eb3c9bbd911 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:18:37 +0530 Subject: [PATCH 0815/1894] update description --- sorting/selection_sort.cpp | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 984e3e24..1b780321 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -1,11 +1,26 @@ -// Implementation of selection sort. -// Selection sort is an in-place comparison sorting algorithm. -// It has an O(n^{2}), time complexity which makes it inefficient on large lists, -// and generally performs worse than the similar insertion sort. -// Selection sort is noted for its simplicity and has performance advantages -// over more complicated algorithms in certain situations, -// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort +/* + Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an + unsorted part of the array and putting it at the beginning of the array. + + In each iteration, the minimum element is found by comparing each element of the unsorted part of the array with the current minimum + element, and if a smaller element is found, it becomes the new minimum element. + + Once the minimum element is found, it is swapped with the first element of the unsorted part of the array. + This process is repeated until the entire array is sorted. The main idea behind selection sort is to divide + the array into two parts: a sorted part and an unsorted part. + + Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, the minimum element is selected from + the unsorted part and added to the end of the sorted part. + + The time complexity of selection sort is O(n^2) in both the best and worst cases, where n is the number + of elements in the array. This is because for each element in the array, it needs to compare it with + every other element to find the smallest one, which takes O(n) time. Since this process needs to be + repeated for each element, the overall time complexity becomes O(n^2). + + The space complexity of selection sort is O(1) because it does not require any extra space other than + the input array itself. It performs the sorting in place by swapping the elements within the array. +*/ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] #include From 37d799fe30fa0ea9348820b0e71cd5ba42d52f11 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:18:39 +0530 Subject: [PATCH 0816/1894] update description --- sorting/selection_sort.go | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sorting/selection_sort.go b/sorting/selection_sort.go index f17be560..6207a9c4 100644 --- a/sorting/selection_sort.go +++ b/sorting/selection_sort.go @@ -1,11 +1,26 @@ -// Implementation of selection sort. -// Selection sort is an in-place comparison sorting algorithm. -// It has an O(n^{2}) time complexity which makes it inefficient on large lists, -// and generally performs worse than the similar insertion sort. -// Selection sort is noted for its simplicity and has performance advantages -// over more complicated algorithms in certain situations, -// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort +/* + Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an + unsorted part of the array and putting it at the beginning of the array. + + In each iteration, the minimum element is found by comparing each element of the unsorted part of the array with the current minimum + element, and if a smaller element is found, it becomes the new minimum element. + + Once the minimum element is found, it is swapped with the first element of the unsorted part of the array. + This process is repeated until the entire array is sorted. The main idea behind selection sort is to divide + the array into two parts: a sorted part and an unsorted part. + + Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, the minimum element is selected from + the unsorted part and added to the end of the sorted part. + + The time complexity of selection sort is O(n^2) in both the best and worst cases, where n is the number + of elements in the array. This is because for each element in the array, it needs to compare it with + every other element to find the smallest one, which takes O(n) time. Since this process needs to be + repeated for each element, the overall time complexity becomes O(n^2). + + The space complexity of selection sort is O(1) because it does not require any extra space other than + the input array itself. It performs the sorting in place by swapping the elements within the array. +*/ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] package main From 20d960401b57ebe18306a306cddad3dd01df60f8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:18:42 +0530 Subject: [PATCH 0817/1894] update description --- sorting/selection_sort.java | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sorting/selection_sort.java b/sorting/selection_sort.java index 5540150c..e9db4247 100644 --- a/sorting/selection_sort.java +++ b/sorting/selection_sort.java @@ -1,11 +1,26 @@ -// Implementation of selection sort. -// Selection sort is an in-place comparison sorting algorithm. -// It has an O(n^{2}) time complexity which makes it inefficient on large lists, -// and generally performs worse than the similar insertion sort. -// Selection sort is noted for its simplicity and has performance advantages -// over more complicated algorithms in certain situations, -// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort +/* + Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an + unsorted part of the array and putting it at the beginning of the array. + + In each iteration, the minimum element is found by comparing each element of the unsorted part of the array with the current minimum + element, and if a smaller element is found, it becomes the new minimum element. + + Once the minimum element is found, it is swapped with the first element of the unsorted part of the array. + This process is repeated until the entire array is sorted. The main idea behind selection sort is to divide + the array into two parts: a sorted part and an unsorted part. + + Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, the minimum element is selected from + the unsorted part and added to the end of the sorted part. + + The time complexity of selection sort is O(n^2) in both the best and worst cases, where n is the number + of elements in the array. This is because for each element in the array, it needs to compare it with + every other element to find the smallest one, which takes O(n) time. Since this process needs to be + repeated for each element, the overall time complexity becomes O(n^2). + + The space complexity of selection sort is O(1) because it does not require any extra space other than + the input array itself. It performs the sorting in place by swapping the elements within the array. +*/ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] From 8379e3f39396079e66613fe9d7a1b6ceb4843920 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:18:45 +0530 Subject: [PATCH 0818/1894] update description --- sorting/selection_sort.js | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sorting/selection_sort.js b/sorting/selection_sort.js index e853183e..93913a28 100644 --- a/sorting/selection_sort.js +++ b/sorting/selection_sort.js @@ -1,11 +1,26 @@ -// Implementation of selection sort. -// Selection sort is an in-place comparison sorting algorithm. -// It has an O(n^{2}) time complexity which makes it inefficient on large lists, -// and generally performs worse than the similar insertion sort. -// Selection sort is noted for its simplicity and has performance advantages -// over more complicated algorithms in certain situations, -// particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort +/* + Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an + unsorted part of the array and putting it at the beginning of the array. + + In each iteration, the minimum element is found by comparing each element of the unsorted part of the array with the current minimum + element, and if a smaller element is found, it becomes the new minimum element. + + Once the minimum element is found, it is swapped with the first element of the unsorted part of the array. + This process is repeated until the entire array is sorted. The main idea behind selection sort is to divide + the array into two parts: a sorted part and an unsorted part. + + Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, the minimum element is selected from + the unsorted part and added to the end of the sorted part. + + The time complexity of selection sort is O(n^2) in both the best and worst cases, where n is the number + of elements in the array. This is because for each element in the array, it needs to compare it with + every other element to find the smallest one, which takes O(n) time. Since this process needs to be + repeated for each element, the overall time complexity becomes O(n^2). + + The space complexity of selection sort is O(1) because it does not require any extra space other than + the input array itself. It performs the sorting in place by swapping the elements within the array. +*/ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] const inputArr = [4, 5, 67, 56, 3, 35, 45]; From 58952817716aa267cdcc3d72583d68f876b854aa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:18:48 +0530 Subject: [PATCH 0819/1894] update description --- sorting/selection_sort.py | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sorting/selection_sort.py b/sorting/selection_sort.py index 48f923f2..7275b930 100644 --- a/sorting/selection_sort.py +++ b/sorting/selection_sort.py @@ -1,11 +1,26 @@ -# Implementation of selection sort. -# Selection sort is an in-place comparison sorting algorithm. -# It has an O(n^{2}) time complexity which makes it inefficient on large lists, -# and generally performs worse than the similar insertion sort. -# Selection sort is noted for its simplicity and has performance advantages -# over more complicated algorithms in certain situations, -# particularly where auxiliary memory is limited. (Source wiki) https://en.wikipedia.org/wiki/Selection_sort +''' + Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from an + unsorted part of the array and putting it at the beginning of the array. + + In each iteration, the minimum element is found by comparing each element of the unsorted part of the array with the current minimum + element, and if a smaller element is found, it becomes the new minimum element. + + Once the minimum element is found, it is swapped with the first element of the unsorted part of the array. + This process is repeated until the entire array is sorted. The main idea behind selection sort is to divide + the array into two parts: a sorted part and an unsorted part. + + Initially, the sorted part is empty, and the unsorted part is the entire array. In each iteration, the minimum element is selected from + the unsorted part and added to the end of the sorted part. + + The time complexity of selection sort is O(n^2) in both the best and worst cases, where n is the number + of elements in the array. This is because for each element in the array, it needs to compare it with + every other element to find the smallest one, which takes O(n) time. Since this process needs to be + repeated for each element, the overall time complexity becomes O(n^2). + + The space complexity of selection sort is O(1) because it does not require any extra space other than + the input array itself. It performs the sorting in place by swapping the elements within the array. +''' # Sample Input : [2, 1, 9, 3, 5, 4, 0] # Output : [0 1 2 3 4 5 9] From d1b74a9193397391522dfc397e949d07a3bafb8e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:21:46 +0530 Subject: [PATCH 0820/1894] add binary search in cpp --- Binary Search/binary_search.cpp | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Binary Search/binary_search.cpp diff --git a/Binary Search/binary_search.cpp b/Binary Search/binary_search.cpp new file mode 100644 index 00000000..097a284f --- /dev/null +++ b/Binary Search/binary_search.cpp @@ -0,0 +1,48 @@ +#include +#include + +using namespace std; + +// Binary search function +// Takes in a sorted vector of integers and a target value to search for +// Returns the index of the target value if found, -1 otherwise +int binarySearch(vector arr, int target) { + int left = 0; + int right = arr.size() - 1; + + // Loop until left and right pointers meet + while (left <= right) { + int mid = left + (right - left) / 2; + + // If the target is found, return the index + if (arr[mid] == target) { + return mid; + } + // If target is greater than the middle element, discard the left half + else if (arr[mid] < target) { + left = mid + 1; + } + // If target is smaller than the middle element, discard the right half + else { + right = mid - 1; + } + } + + // Target not found + return -1; +} + +// Driver code to test binary search function +int main() { + vector arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; + int target = 12; + int result = binarySearch(arr, target); + + if (result == -1) { + cout << "Element not found" << endl; + } + else { + cout << "Element found at index " << result << endl; + } + return 0; +} From acf501f7f8a1333ea9857679ac14cb15367f823e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Apr 2023 23:22:51 +0530 Subject: [PATCH 0821/1894] add description --- Binary Search/binary_search.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Binary Search/binary_search.cpp b/Binary Search/binary_search.cpp index 097a284f..835ec7a5 100644 --- a/Binary Search/binary_search.cpp +++ b/Binary Search/binary_search.cpp @@ -1,3 +1,16 @@ +/* + The binarySearch function takes in a sorted vector of integers arr and a target value target to search for. + The function initializes the left and right pointers to the first and last indices of the array respectively. + The function uses a while loop to keep searching until the left and right pointers meet. + Inside the loop, the function calculates the middle index by adding the left and right indices and dividing by 2. + If the middle element is equal to the target, the function returns the middle index. + If the target is greater than the middle element, the function discards the left half of the array and moves the left pointer to the middle + 1 index. + If the target is smaller than the middle element, the function discards the right half of the array and moves the right pointer to the middle - 1 index. + If the target is not found in the array, the function returns -1. + The driver code initializes a sorted array and a target value, and calls the binarySearch function to search for the target value. + The function returns the index of the target value, or -1 if it is not found. + The driver code prints the result of the search to the console. +*/ #include #include From a94046a6d33abc2ed3454ce2e679113275cb69fb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:20:05 +0530 Subject: [PATCH 0822/1894] modify program --- sorting/selection_sort.go | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/sorting/selection_sort.go b/sorting/selection_sort.go index 6207a9c4..24c45f6d 100644 --- a/sorting/selection_sort.go +++ b/sorting/selection_sort.go @@ -27,23 +27,30 @@ package main import "fmt" -func SelectionSort(arr []int, length int) []int { - for i := 0; i < length-1; i++ { - imin := i - for j := i + 1; j < length; j++ { - // find minumim element's index - if arr[j] < arr[imin] { - imin = j +// selectionSort sorts an array of integers in ascending order +// using the selection sort algorithm. +func selectionSort(arr []int) { + // Loop over the array from start to end + for i := 0; i < len(arr); i++ { + // Assume the current index contains the minimum value + minIdx := i + // Loop over the rest of the array to find the minimum value + for j := i + 1; j < len(arr); j++ { + // If a value is found that is smaller than the current minimum, + // update the minimum index + if arr[j] < arr[minIdx] { + minIdx = j } } - // bring min element to front - arr[i], arr[imin] = arr[imin], arr[i] + // Swap the minimum value with the current index + arr[i], arr[minIdx] = arr[minIdx], arr[i] } - return arr } func main() { - arr := []int{2, 1, 9, 3, 5, 4, 0} - msg := SelectionSort(arr, 7) - fmt.Println(msg) -} \ No newline at end of file + // Example usage + arr := []int{5, 3, 6, 2, 10} + fmt.Println("Before sorting:", arr) + selectionSort(arr) + fmt.Println("After sorting:", arr) +} From 099ce06c4d99c0dd88ab42e3fd2fcfd7007a9fa4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:21:58 +0530 Subject: [PATCH 0823/1894] modify program --- sorting/selection_sort.js | 45 +++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/sorting/selection_sort.js b/sorting/selection_sort.js index 93913a28..89d6c950 100644 --- a/sorting/selection_sort.js +++ b/sorting/selection_sort.js @@ -24,31 +24,30 @@ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] const inputArr = [4, 5, 67, 56, 3, 35, 45]; - -const selectionSort = (inputArr) => { - let n = inputArr.length; - - //loop to access each array element - for (let i = 0; i < n; i++) { - //assuming first array element as current minimum - let min = i; - - //loop to compare current minimum element to other array element - for (let j = i + 1; j < n; j++) { - //comparing and updating cureent minimum element - if (inputArr[j] < inputArr[min]) { - min = j; +/** + * Sorts an array using selection sort algorithm. + * @param {number[]} array - The array to be sorted. + * @returns {number[]} - The sorted array. + */ +function selectionSort(array) { + // Loop through the array from the start to the second last element + for (let i = 0; i < array.length - 1; i++) { + // Assume that the current element is the minimum + let minIndex = i; + // Loop through the rest of the array to find the minimum element + for (let j = i + 1; j < array.length; j++) { + if (array[j] < array[minIndex]) { + // If we find a smaller element, update the minimum index + minIndex = j; } } - - //swapping array elements if current minimum changes - if (min != i) { - let temp = inputArr[i]; - inputArr[i] = inputArr[min]; - inputArr[min] = temp; - } + // Swap the current element with the minimum element + let temp = array[i]; + array[i] = array[minIndex]; + array[minIndex] = temp; } - return inputArr; -}; + // Return the sorted array + return array; +} console.log(selectionSort(inputArr)); From c4db456ce891edd98858eeea55a115f32bb5c9e5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:22:57 +0530 Subject: [PATCH 0824/1894] modify program --- sorting/selection_sort.py | 40 ++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/sorting/selection_sort.py b/sorting/selection_sort.py index 7275b930..f04c3c1e 100644 --- a/sorting/selection_sort.py +++ b/sorting/selection_sort.py @@ -24,25 +24,31 @@ # Sample Input : [2, 1, 9, 3, 5, 4, 0] # Output : [0 1 2 3 4 5 9] -def selectionSort(array, size): - - for step in range(size): - min_idx = step - - for i in range(step + 1, size): - - # to sort in descending order, change > to < in this line - # select the minimum element in each loop - - if array[i] < array[min_idx]: - min_idx = i - - # put min at the correct position - (array[step], array[min_idx]) = (array[min_idx], array[step]) - +def selection_sort(arr): + """ + Sorts an array in ascending order using the selection sort algorithm. + + Args: + arr (list): An array of integers. + + Returns: + list: The sorted array in ascending order. + """ + # Loop through the array + for i in range(len(arr)): + # Find the minimum element in the unsorted portion of the array + min_idx = i + for j in range(i+1, len(arr)): + if arr[j] < arr[min_idx]: + min_idx = j + + # Swap the minimum element with the first element in the unsorted portion of the array + arr[i], arr[min_idx] = arr[min_idx], arr[i] + + return arr data = [-2, 45, 0, 11, -9] size = len(data) -selectionSort(data, size) +selection_sort(data, size) print('Sorted Array in Ascending Order:') print(data) \ No newline at end of file From 68092dc6feec7fd152e2c43718c856bc15606119 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:23:47 +0530 Subject: [PATCH 0825/1894] modify program --- sorting/selection_sort.cpp | 50 +++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 1b780321..0edf6b9b 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -23,27 +23,37 @@ */ // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] -#include +#include +#include + using namespace std; -void SelectionSort(int A[], int n){ - for(int i = 0; i < n - 1; i++){ - int imin = i; - for(int j = i + 1; j < n; j++){ - if(A[j] < A[imin]) - imin = j; - } - int temp = A[i]; - A[i] = A[imin]; - A[imin] = temp; - } +// Function to perform selection sort on a vector +void selectionSort(vector& arr) { + int n = arr.size(); + + // Iterate through the array + for (int i = 0; i < n - 1; i++) { + int minIdx = i; + + // Find the index of the minimum element in the unsorted part of the array + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the minimum element with the first element of the unsorted part of the array + swap(arr[i], arr[minIdx]); + } } -int main(){ - int A[] = {5,4,3,6,7,8,9,1,2,10}; - SelectionSort(A,10); - for(int i = 0; i < 10; i++){ - cout << A[i] << " "; - } - -return 0; + +int main() { + // Example usage + vector arr = {64, 25, 12, 22, 11}; + selectionSort(arr); + for (int i = 0; i < arr.size(); i++) { + cout << arr[i] << " "; + } + return 0; } From 477f3b48c1b49ecf5d98eae48e6e59e1cf14f751 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:24:54 +0530 Subject: [PATCH 0826/1894] modify program --- sorting/selection_sort.java | 59 +++++++++++++------------------------ 1 file changed, 21 insertions(+), 38 deletions(-) diff --git a/sorting/selection_sort.java b/sorting/selection_sort.java index e9db4247..3c816761 100644 --- a/sorting/selection_sort.java +++ b/sorting/selection_sort.java @@ -24,43 +24,26 @@ The space complexity of selection sort is O(1) because it does not require any e // Sample Input : [2, 1, 9, 3, 5, 4, 0] // Output : [0 1 2 3 4 5 9] -import java.util.Arrays; - -class SelectionSort { - void selectionSort(int array[]) - { - int size = array.length; - - for (int step = 0; step < size - 1; step++) - { - int min_idx = step; - - for (int i = step + 1; i < size; i++) - { - // To sort in descending order, change > to < in this line. - // Select the minimum element in each loop. - - if (array[i] < array[min_idx]) - { - min_idx = i; +/** + * Sorts an array of integers in ascending order using the Selection Sort algorithm. + * + * @param arr the array to be sorted + * @return the sorted array + */ +public static int[] selectionSort(int[] arr) { + // iterate through the array + for (int i = 0; i < arr.length - 1; i++) { + int minIdx = i; + // find the index of the smallest element in the unsorted portion of the array + for (int j = i + 1; j < arr.length; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } } - } - - // put min at the correct position - - int temp = array[step]; - array[step] = array[min_idx]; - array[min_idx] = temp; + // swap the smallest element with the first unsorted element + int temp = arr[minIdx]; + arr[minIdx] = arr[i]; + arr[i] = temp; } - } - - // driver code - public static void main(String args[]) - { - int[] data = { 20, 12, 10, 15, 2 }; - SelectionSort ss = new SelectionSort(); - ss.selectionSort(data); - System.out.println("Sorted Array in Ascending Order: "); - System.out.println(Arrays.toString(data)); - } -} \ No newline at end of file + return arr; +} From 32f899969e4f09492b3bf8aed08ec68f28a3cbc7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:27:51 +0530 Subject: [PATCH 0827/1894] add first non repeated character in go --- Hash Table/first_non_repeated_character.go | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Hash Table/first_non_repeated_character.go diff --git a/Hash Table/first_non_repeated_character.go b/Hash Table/first_non_repeated_character.go new file mode 100644 index 00000000..10c85254 --- /dev/null +++ b/Hash Table/first_non_repeated_character.go @@ -0,0 +1,23 @@ +package main + +// This function takes a string as input and returns the index of the first non-repeating character in the string. +func FirstNonRepeatingCharacter(str string) int { + // Create a map to store the frequency of each character in the string. + // The key of the map is a rune, which is an integer representation of a Unicode character. + // The value of the map is an integer representing the frequency of the corresponding character. + charFreq := make(map[rune]int) + // Loop through each character in the string and update its frequency in the map. + for _, char := range str { + charFreq[char] += 1 + } + // Loop through each character in the string again. + for idx, char := range str { + // If the frequency of the current character is 1, it means it is the first non-repeating character in the string. + if charFreq[char] == 1 { + // Return the index of the non-repeating character. + return idx + } + } + // If no non-repeating character is found in the string, return -1. + return -1 +} From af4226176d75e6aab905cbb9ea2f86f45924c916 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:28:53 +0530 Subject: [PATCH 0828/1894] add main func --- Hash Table/first_non_repeated_character.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Hash Table/first_non_repeated_character.go b/Hash Table/first_non_repeated_character.go index 10c85254..f965ceb7 100644 --- a/Hash Table/first_non_repeated_character.go +++ b/Hash Table/first_non_repeated_character.go @@ -1,5 +1,7 @@ package main +import "fmt" + // This function takes a string as input and returns the index of the first non-repeating character in the string. func FirstNonRepeatingCharacter(str string) int { // Create a map to store the frequency of each character in the string. @@ -21,3 +23,7 @@ func FirstNonRepeatingCharacter(str string) int { // If no non-repeating character is found in the string, return -1. return -1 } + +func main() { + fmt.Println(FirstNonRepeatingCharacter("abcdcaf")); // b index 1 +} \ No newline at end of file From cdae25c821909f53853f24285d611fde2d332c5e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:29:52 +0530 Subject: [PATCH 0829/1894] add description --- Hash Table/first_non_repeated_character.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Hash Table/first_non_repeated_character.go b/Hash Table/first_non_repeated_character.go index f965ceb7..a41b46f0 100644 --- a/Hash Table/first_non_repeated_character.go +++ b/Hash Table/first_non_repeated_character.go @@ -1,3 +1,25 @@ +/* + The FirstNonRepeatingCharacter function takes a string as input and returns the index of the + first non-repeating character in the string. If all the characters are repeated, then it returns -1. + + The function works by first creating an empty map called charFreq to keep track of the frequency of + each character in the string. Then, it iterates through each character in the string using a for loop. + + Inside the loop, it checks if the current character already exists in the charFreq map. + + If it does, then it increments its frequency by 1, and if it doesn't, it adds the character to the map + with a frequency of 1. + + After the map is constructed, the function iterates through the string again using another for loop, + this time tracking the index of each character using the idx variable. + + For each character, it checks its frequency in the charFreq map. + + If the frequency is 1, then the character is non-repeating and the function returns its index. + + If no non-repeating character is found, then the function returns -1. + +*/ package main import "fmt" From da1b58a712b37e608e314fecfe9da368d4ce91f6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:30:12 +0530 Subject: [PATCH 0830/1894] add time and space complexity --- Hash Table/first_non_repeated_character.go | 1 + 1 file changed, 1 insertion(+) diff --git a/Hash Table/first_non_repeated_character.go b/Hash Table/first_non_repeated_character.go index a41b46f0..28aec061 100644 --- a/Hash Table/first_non_repeated_character.go +++ b/Hash Table/first_non_repeated_character.go @@ -19,6 +19,7 @@ If no non-repeating character is found, then the function returns -1. + Overall, the function has a time complexity of O(n) since it loops through the string twice, and a space complexity of O(k), where k is the number of unique characters in the string, since the charFreq map stores the frequency of each unique character. */ package main From 340fd8bad43dc1901847c090be25e65f158e36f6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:33:19 +0530 Subject: [PATCH 0831/1894] add three largest numbers in go --- Arrays/find_three_largest_numbers.go | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Arrays/find_three_largest_numbers.go diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go new file mode 100644 index 00000000..e89e7a3d --- /dev/null +++ b/Arrays/find_three_largest_numbers.go @@ -0,0 +1,30 @@ +package main +import "math" + +func FindThreeLargestNumbers(array []int) []int { + triplets := []int{math.MinInt32, math.MinInt32, math.MinInt32} + for _, num := range array { + updateLargest(triplets, num) + } + return triplets +} + +func updateLargest(triplets []int, num int) { + if num > triplets[2] { + shiftAndUpdate(triplets, num, 2) + } else if num > triplets[1] { + shiftAndUpdate(triplets, num, 1) + } else if num > triplets[0] { + shiftAndUpdate(triplets, num, 0) + } +} + +func shiftAndUpdate(triplets []int, num int, idx int) { + for i := 0 ; i < idx + 1; i++ { + if i == idx { + triplets[i] = num + } else { + triplets[i] = triplets[i + 1] + } + } +} \ No newline at end of file From 962203d233d925f1ddcbff97f95e95122794ded9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Apr 2023 08:33:51 +0530 Subject: [PATCH 0832/1894] add question --- Arrays/find_three_largest_numbers.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go index e89e7a3d..30169f80 100644 --- a/Arrays/find_three_largest_numbers.go +++ b/Arrays/find_three_largest_numbers.go @@ -1,3 +1,8 @@ +/* + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. +*/ package main import "math" From a06a93b1b2ee8a1dbfa045935772be9b2f935064 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:31:07 +0530 Subject: [PATCH 0833/1894] add comments and modify program --- Arrays/find_three_largest_numbers.go | 49 +++++++++++++++++----------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go index 30169f80..a81d88b5 100644 --- a/Arrays/find_three_largest_numbers.go +++ b/Arrays/find_three_largest_numbers.go @@ -4,32 +4,43 @@ integers in the input array. */ package main + import "math" +// FindThreeLargestNumbers returns the three largest integers in the input array in descending order. func FindThreeLargestNumbers(array []int) []int { + // Initialize a slice to hold the three largest integers, starting with negative infinity. triplets := []int{math.MinInt32, math.MinInt32, math.MinInt32} - for _, num := range array { - updateLargest(triplets, num) - } - return triplets + for _, num := range array { + // For each number in the array, call the updateLargest function to determine if it should be included in the triplet. + updateLargest(triplets, num) + } + return triplets } +// updateLargest updates the triplet if the input number is larger than any of its elements. func updateLargest(triplets []int, num int) { - if num > triplets[2] { - shiftAndUpdate(triplets, num, 2) - } else if num > triplets[1] { - shiftAndUpdate(triplets, num, 1) - } else if num > triplets[0] { - shiftAndUpdate(triplets, num, 0) - } + // If the number is larger than the third-largest element in the triplet, shift the other elements to make room and add the number. + if num > triplets[2] { + shiftAndUpdate(triplets, num, 2) + // Otherwise, if the number is larger than the second-largest element, shift and update the triplet accordingly. + } else if num > triplets[1] { + shiftAndUpdate(triplets, num, 1) + // Otherwise, if the number is larger than the first-largest element, shift and update the triplet accordingly. + } else if num > triplets[0] { + shiftAndUpdate(triplets, num, 0) + } } +// shiftAndUpdate shifts the elements of the triplet to make room for a new number and adds the number to the specified index. func shiftAndUpdate(triplets []int, num int, idx int) { - for i := 0 ; i < idx + 1; i++ { - if i == idx { - triplets[i] = num - } else { - triplets[i] = triplets[i + 1] - } - } -} \ No newline at end of file + for i := 0; i < idx+1; i++ { + // If the loop reaches the specified index, add the new number to the triplet. + if i == idx { + triplets[i] = num + // Otherwise, shift the elements to the right. + } else { + triplets[i] = triplets[i+1] + } + } +} From 23e3f1eaa56e27b27a47a0a7870cd737d01fc13a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:32:35 +0530 Subject: [PATCH 0834/1894] add explanation --- Arrays/find_three_largest_numbers.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go index a81d88b5..89c2c9d0 100644 --- a/Arrays/find_three_largest_numbers.go +++ b/Arrays/find_three_largest_numbers.go @@ -3,6 +3,31 @@ without sorting the input array, returns a sorted array of the three largest integers in the input array. */ +/* Explanation + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. + + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. + + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. + + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. + + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. +*/ package main import "math" From 7c8f0f47c5b4522f002ead308d2f8f09ba57f164 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:35:57 +0530 Subject: [PATCH 0835/1894] add time and space complexity --- Arrays/find_three_largest_numbers.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go index 89c2c9d0..ebeeadd7 100644 --- a/Arrays/find_three_largest_numbers.go +++ b/Arrays/find_three_largest_numbers.go @@ -27,6 +27,8 @@ The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches the `idx` index. Then it updates the value at the `idx` index with the current number `num`. + + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array */ package main From 7e8fe00c88698d6a209d1dd1d643c7dc7178df2a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:48:37 +0530 Subject: [PATCH 0836/1894] add find three largest in c++ --- Arrays/find_three_largest_number.cpp | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Arrays/find_three_largest_number.cpp diff --git a/Arrays/find_three_largest_number.cpp b/Arrays/find_three_largest_number.cpp new file mode 100644 index 00000000..45330f47 --- /dev/null +++ b/Arrays/find_three_largest_number.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +using namespace std; + +void updateLargest(vector& triplets, int num); +void shiftAndUpdate(vector& triplets, int num, int idx); +vector findThreeLargestNumbers(vector& array); + +int main() { + vector array = {141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7}; + vector result = findThreeLargestNumbers(array); + for (int num : result) { + cout << num << " "; + } + cout << endl; + return 0; +} + +vector findThreeLargestNumbers(vector& array) { + vector triplets = {INT_MIN, INT_MIN, INT_MIN}; + for (int num : array) { + updateLargest(triplets, num); + } + return triplets; +} + +void updateLargest(vector& triplets, int num) { + if (num > triplets[2]) { + shiftAndUpdate(triplets, num, 2); + } else if (num > triplets[1]) { + shiftAndUpdate(triplets, num, 1); + } else if (num > triplets[0]) { + shiftAndUpdate(triplets, num, 0); + } +} + +void shiftAndUpdate(vector& triplets, int num, int idx) { + for (int i = 0; i < idx + 1; i++) { + if (i == idx) { + triplets[i] = num; + } else { + triplets[i] = triplets[i + 1]; + } + } +} From a713d2f90fd8f6ac680cf16be18eb5318edcacd2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:53:57 +0530 Subject: [PATCH 0837/1894] add comments --- Arrays/find_three_largest_number.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Arrays/find_three_largest_number.cpp b/Arrays/find_three_largest_number.cpp index 45330f47..aabd3055 100644 --- a/Arrays/find_three_largest_number.cpp +++ b/Arrays/find_three_largest_number.cpp @@ -5,13 +5,23 @@ using namespace std; +// Function to update the triplet if the input number is larger than any of its elements. void updateLargest(vector& triplets, int num); + +// Function to shift the elements of the triplet to make room for a new number and add the number to the specified index. void shiftAndUpdate(vector& triplets, int num, int idx); + +// Function to find the three largest integers in the input array in descending order. vector findThreeLargestNumbers(vector& array); int main() { + // Create an input array. vector array = {141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7}; + + // Find the three largest integers in the input array. vector result = findThreeLargestNumbers(array); + + // Output the three largest integers in descending order. for (int num : result) { cout << num << " "; } @@ -20,27 +30,38 @@ int main() { } vector findThreeLargestNumbers(vector& array) { + // Initialize a vector to hold the three largest integers, starting with negative infinity. vector triplets = {INT_MIN, INT_MIN, INT_MIN}; + + // Iterate over each number in the input array and call the updateLargest function to determine if it should be included in the triplet. for (int num : array) { updateLargest(triplets, num); } + + // Return the vector containing the three largest integers in descending order. return triplets; } void updateLargest(vector& triplets, int num) { + // If the number is larger than the third-largest element in the triplet, shift the other elements to make room and add the number. if (num > triplets[2]) { shiftAndUpdate(triplets, num, 2); + // Otherwise, if the number is larger than the second-largest element, shift and update the triplet accordingly. } else if (num > triplets[1]) { shiftAndUpdate(triplets, num, 1); + // Otherwise, if the number is larger than the first-largest element, shift and update the triplet accordingly. } else if (num > triplets[0]) { shiftAndUpdate(triplets, num, 0); } } void shiftAndUpdate(vector& triplets, int num, int idx) { + // Shift the elements of the triplet to the right starting at the specified index, and add the new number to the specified index. for (int i = 0; i < idx + 1; i++) { + // If the loop reaches the specified index, add the new number to the triplet. if (i == idx) { triplets[i] = num; + // Otherwise, shift the elements to the right. } else { triplets[i] = triplets[i + 1]; } From cea4605057a6f5a439dd53eaa95acba835e37083 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Apr 2023 08:54:22 +0530 Subject: [PATCH 0838/1894] add description --- Arrays/find_three_largest_number.cpp | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Arrays/find_three_largest_number.cpp b/Arrays/find_three_largest_number.cpp index aabd3055..8fe6dc75 100644 --- a/Arrays/find_three_largest_number.cpp +++ b/Arrays/find_three_largest_number.cpp @@ -1,3 +1,35 @@ +/* + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. +*/ +/* Explanation + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. + + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. + + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. + + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. + + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. + + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array +*/ #include #include #include From be3de185eee3939deef1c16d03096af898e4cffa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:53:03 +0530 Subject: [PATCH 0839/1894] modify program --- Arrays/is_monotonic.go | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/Arrays/is_monotonic.go b/Arrays/is_monotonic.go index 0703f433..fde55827 100644 --- a/Arrays/is_monotonic.go +++ b/Arrays/is_monotonic.go @@ -6,29 +6,24 @@ package main import "fmt" -func IsMonotonic(Arr []int) bool { - if len(Arr) < 2 { - return true - } - - isIncreasing := 0 - for i := 1; i < len(Arr); i++ { - if isIncreasing == 0 { - if Arr[i - 1] > Arr[i] { - isIncreasing = -1 // means we will check for decreasing - } else if Arr[i - 1] < Arr[i] { - isIncreasing = 1 // means we will check for increasing - } - } - if isIncreasing == 1 && Arr[i - 1] > Arr[i] { - return false // in increasing array element before other element cannot be less so return false +func IsMonotonic(array []int) bool { + // assume the array is non-decreasing until we find a decreasing element + isNonDecreasing := true + // assume the array is non-increasing until we find an increasing element + isNonIncreasing := true + for i := 1; i < len(array); i++ { + if array[i] < array[i - 1] { + // if the current element is less than the previous element, the array is not non-decreasing + isNonDecreasing = false } - if isIncreasing == -1 && Arr[i - 1] < Arr[i] { - return false // in decreasing array element after other element cannot be greater so return false + if array[i] > array[i - 1] { + // if the current element is greater than the previous element, the array is not non-increasing + isNonIncreasing = false } } - return true + // return true if the array is either non-decreasing or non-increasing + return isNonDecreasing || isNonIncreasing } func main() { From ee7a12129b99ab3c2936fcbe3194b1bf8a58a4ca Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:53:48 +0530 Subject: [PATCH 0840/1894] add comments --- Arrays/is_monotonic.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Arrays/is_monotonic.go b/Arrays/is_monotonic.go index fde55827..23f32b2c 100644 --- a/Arrays/is_monotonic.go +++ b/Arrays/is_monotonic.go @@ -1,6 +1,19 @@ /* An array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing. Mathematically, An array A is continuously increasing if for all i <= j, A[i] <= A[j]. + + The IsMonotonic function takes an array of integers and returns a boolean value indicating whether the array + is monotonic or not. A monotonic array is one in which the elements are either non-increasing or non-decreasing. + + The function works by initializing two boolean variables, isNonDecreasing and isNonIncreasing, to true. + It then iterates over the array from the first element to the second-to-last element, comparing each element to the next one. + + If the current element is less than the next element, it sets isNonDecreasing to false, indicating that the + array is not non-decreasing. If the current element is greater than the next element, it sets isNonIncreasing to false, + indicating that the array is not non-increasing. + + At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, + indicating that the array is monotonic. Otherwise, it returns false. */ package main From 13d09cebdc3310a896c0779efda4796ae6c618ae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:54:10 +0530 Subject: [PATCH 0841/1894] add time and space complexity --- Arrays/is_monotonic.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Arrays/is_monotonic.go b/Arrays/is_monotonic.go index 23f32b2c..003b1a35 100644 --- a/Arrays/is_monotonic.go +++ b/Arrays/is_monotonic.go @@ -14,6 +14,8 @@ At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, indicating that the array is monotonic. Otherwise, it returns false. + + O(n) time | O(1) space - where n is the length of the array */ package main From 61fdc6c380d89e24c0f2369c5927f06fc2d75169 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:55:46 +0530 Subject: [PATCH 0842/1894] add move element to end --- Arrays/move_element_to_end.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Arrays/move_element_to_end.go diff --git a/Arrays/move_element_to_end.go b/Arrays/move_element_to_end.go new file mode 100644 index 00000000..5fc8fd0d --- /dev/null +++ b/Arrays/move_element_to_end.go @@ -0,0 +1,15 @@ +package main + +func MoveElementToEnd(array []int, toMove int) []int { + index := 0 // initialize a variable to keep track of the index where elements should be moved to + for i := 0; i < len(array); i++ { // loop through the entire array + if array[i] != toMove { // check if the current element is not equal to the element to be moved + array[index] = array[i] // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i]) + index++ // increment the index variable by 1 to keep track of the index where the next non-target element should be moved + } + } + for i := index; i < len(array); i++ { // loop through the remaining elements in the array from index to the end + array[i] = toMove // set each element to be the target element + } + return array // return the modified array +} From ea9d43ed4dca7faee79a5336d72481fa463e5270 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:56:26 +0530 Subject: [PATCH 0843/1894] add description --- Arrays/move_element_to_end.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Arrays/move_element_to_end.go b/Arrays/move_element_to_end.go index 5fc8fd0d..052643d2 100644 --- a/Arrays/move_element_to_end.go +++ b/Arrays/move_element_to_end.go @@ -1,3 +1,19 @@ +/* + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, + and returns a modified array with all instances of toMove moved to the end of the array. + + The function first initializes an integer variable index to 0, which will keep track of the index of the first + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the + current element is not equal to toMove, it replaces the element at the index position with the current element + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the + beginning of the array. + + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the + end of the array. + +Finally, the modified array is returned. +*/ package main func MoveElementToEnd(array []int, toMove int) []int { From ec5b0beddd8a22d33a5f141e16b8642680819271 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 19:56:53 +0530 Subject: [PATCH 0844/1894] add time and space complexity --- Arrays/move_element_to_end.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Arrays/move_element_to_end.go b/Arrays/move_element_to_end.go index 052643d2..553ddd38 100644 --- a/Arrays/move_element_to_end.go +++ b/Arrays/move_element_to_end.go @@ -12,7 +12,9 @@ the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the end of the array. -Finally, the modified array is returned. + Finally, the modified array is returned. + + O(n) time | O(1) space - where n is the length of the array */ package main From c09a478b13cbfea4c7dd00fe83719b388e0da3e7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 20:02:48 +0530 Subject: [PATCH 0845/1894] add is monotonic in c++ --- Arrays/is_monotonic.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Arrays/is_monotonic.cpp diff --git a/Arrays/is_monotonic.cpp b/Arrays/is_monotonic.cpp new file mode 100644 index 00000000..526e6b48 --- /dev/null +++ b/Arrays/is_monotonic.cpp @@ -0,0 +1,24 @@ +#include +#include + +using namespace std; + +bool IsMonotonic(vector& array) { + bool isNonDecreasing = true; // flag to track if array is non-decreasing + bool isNonIncreasing = true; // flag to track if array is non-increasing + + // iterate through the array starting at index 1 + for (int i = 1; i < array.size(); i++) { + if (array[i] < array[i - 1]) { + // if the current element is less than the previous element, array is not non-decreasing + isNonDecreasing = false; + } + if (array[i] > array[i - 1]) { + // if the current element is greater than the previous element, array is not non-increasing + isNonIncreasing = false; + } + } + + // if either flag is true, return true indicating that array is monotonic + return isNonDecreasing || isNonIncreasing; +} \ No newline at end of file From c3aa287afac5fc8b96ef5958132e47fbc494d344 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 20:03:04 +0530 Subject: [PATCH 0846/1894] add main func --- Arrays/is_monotonic.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Arrays/is_monotonic.cpp b/Arrays/is_monotonic.cpp index 526e6b48..6bfcd091 100644 --- a/Arrays/is_monotonic.cpp +++ b/Arrays/is_monotonic.cpp @@ -21,4 +21,13 @@ bool IsMonotonic(vector& array) { // if either flag is true, return true indicating that array is monotonic return isNonDecreasing || isNonIncreasing; +} + +int main() { + // example usage + vector arr = {1, 2, 3, 3, 4, 5}; + bool isMonotonic = IsMonotonic(arr); + cout << "Array is monotonic: " << isMonotonic << endl; + + return 0; } \ No newline at end of file From 9b5ff11d97a77cf8df92eea28ef9a32d2ceecc05 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Apr 2023 20:03:16 +0530 Subject: [PATCH 0847/1894] add description --- Arrays/is_monotonic.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Arrays/is_monotonic.cpp b/Arrays/is_monotonic.cpp index 6bfcd091..fb6dbbb9 100644 --- a/Arrays/is_monotonic.cpp +++ b/Arrays/is_monotonic.cpp @@ -1,3 +1,22 @@ +/* + An array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing. + Mathematically, An array A is continuously increasing if for all i <= j, A[i] <= A[j]. + + The IsMonotonic function takes an array of integers and returns a boolean value indicating whether the array + is monotonic or not. A monotonic array is one in which the elements are either non-increasing or non-decreasing. + + The function works by initializing two boolean variables, isNonDecreasing and isNonIncreasing, to true. + It then iterates over the array from the first element to the second-to-last element, comparing each element to the next one. + + If the current element is less than the next element, it sets isNonDecreasing to false, indicating that the + array is not non-decreasing. If the current element is greater than the next element, it sets isNonIncreasing to false, + indicating that the array is not non-increasing. + + At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, + indicating that the array is monotonic. Otherwise, it returns false. + + O(n) time | O(1) space - where n is the length of the array +*/ #include #include From 30e01bea87461fe205cdadd5537ef18dcf51b627 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:12:02 +0530 Subject: [PATCH 0848/1894] add smallest difference in go --- Arrays/smallest_difference.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Arrays/smallest_difference.go diff --git a/Arrays/smallest_difference.go b/Arrays/smallest_difference.go new file mode 100644 index 00000000..af32ed99 --- /dev/null +++ b/Arrays/smallest_difference.go @@ -0,0 +1,29 @@ +package main +import ( + "math" + "sort" +) +func SmallestDifference(array1, array2 []int) []int { + current, smallest := math.MaxInt32, math.MaxInt32 + sort.Ints(array1) + sort.Ints(array2) + idx1, idx2 := 0, 0 + result := []int{} + for idx1 < len(array1) && idx2 < len(array2) { + first, second := array1[idx1], array2[idx2] + if first < second { + current = second - first + idx1++ + } else if second < first { + current = first - second + idx2++ + } else { + return []int{first, second} + } + if smallest > current { + smallest = current + result = []int{first, second} + } + } + return result +} \ No newline at end of file From 49de05c45f7a411966e2c5954cd56f9b64a0a68d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:12:17 +0530 Subject: [PATCH 0849/1894] add comments --- Arrays/smallest_difference.go | 63 ++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 24 deletions(-) diff --git a/Arrays/smallest_difference.go b/Arrays/smallest_difference.go index af32ed99..0986caa9 100644 --- a/Arrays/smallest_difference.go +++ b/Arrays/smallest_difference.go @@ -1,29 +1,44 @@ package main + import ( - "math" - "sort" + "math" + "sort" ) + +// SmallestDifference takes two integer slices as input and returns a slice with two integers. +// The two integers in the returned slice have the smallest absolute difference among all pairs +// of integers from the two input slices. func SmallestDifference(array1, array2 []int) []int { + // Initialize variables for the smallest difference and the current difference being calculated current, smallest := math.MaxInt32, math.MaxInt32 - sort.Ints(array1) - sort.Ints(array2) - idx1, idx2 := 0, 0 - result := []int{} - for idx1 < len(array1) && idx2 < len(array2) { - first, second := array1[idx1], array2[idx2] - if first < second { - current = second - first - idx1++ - } else if second < first { - current = first - second - idx2++ - } else { - return []int{first, second} - } - if smallest > current { - smallest = current - result = []int{first, second} - } - } - return result -} \ No newline at end of file + // Sort the input slices + sort.Ints(array1) + sort.Ints(array2) + // Initialize variables for the indices for the two slices + idx1, idx2 := 0, 0 + // Initialize an empty slice for the result + result := []int{} + // Loop through the two slices until we reach the end of one of the slices + for idx1 < len(array1) && idx2 < len(array2) { + // Get the values at the current indices for the two slices + first, second := array1[idx1], array2[idx2] + // Calculate the current difference between the two values + if first < second { + current = second - first + idx1++ + } else if second < first { + current = first - second + idx2++ + } else { + // If the two values are equal, we can return the pair + return []int{first, second} + } + // Update the smallest difference and result slice if the current difference is smaller + if smallest > current { + smallest = current + result = []int{first, second} + } + } + // Return the pair with the smallest absolute difference + return result +} From 8b42a3468299dc2056e7d95d98afcc8007bb74a5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:15:10 +0530 Subject: [PATCH 0850/1894] add description --- Arrays/smallest_difference.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Arrays/smallest_difference.go b/Arrays/smallest_difference.go index 0986caa9..a95ec456 100644 --- a/Arrays/smallest_difference.go +++ b/Arrays/smallest_difference.go @@ -1,3 +1,22 @@ +/* + + This code implements the Smallest Difference problem which takes two arrays of integers as input and returns a pair of integers, + one from each array, with the smallest absolute difference between them. + + The function first initializes two variables current and smallest to the maximum integer value. It then sorts both input arrays + in ascending order using the sort.Ints function from the sort package. + + The function then iterates through both arrays using two pointers, idx1 and idx2, initialized to 0. Inside the loop, it compares + the elements at the current indices of the two arrays, first and second, and calculates the absolute difference between + them in the current variable. + + If current is smaller than the smallest variable, it updates smallest to current and assigns the current pair of integers + to the result variable. + + The function returns the result variable, which contains the pair of integers with the smallest absolute difference. + + If there are identical integers in the two input arrays, the function will return them immediately, without any further comparisons. +*/ package main import ( From 9dba0463ecc904a61abb7ae33b3068848d0a01c9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:15:27 +0530 Subject: [PATCH 0851/1894] add questioon with sample io --- Arrays/smallest_difference.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Arrays/smallest_difference.go b/Arrays/smallest_difference.go index a95ec456..14b54300 100644 --- a/Arrays/smallest_difference.go +++ b/Arrays/smallest_difference.go @@ -1,4 +1,18 @@ /* + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + This code implements the Smallest Difference problem which takes two arrays of integers as input and returns a pair of integers, one from each array, with the smallest absolute difference between them. From eea713e1e5a9dd35fbc3ba44c2297f11654a8510 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:15:56 +0530 Subject: [PATCH 0852/1894] add time and space complexity --- Arrays/smallest_difference.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Arrays/smallest_difference.go b/Arrays/smallest_difference.go index 14b54300..714a829b 100644 --- a/Arrays/smallest_difference.go +++ b/Arrays/smallest_difference.go @@ -30,6 +30,8 @@ The function returns the result variable, which contains the pair of integers with the smallest absolute difference. If there are identical integers in the two input arrays, the function will return them immediately, without any further comparisons. + + O(nlog(n) + mlog(m)) time | O(1) space - where n is the length of the first input array and m is the length of the second input array */ package main From 4214165365849eed6b1bfcb12b15dba2edf76336 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:20:36 +0530 Subject: [PATCH 0853/1894] add smallest diff in c++ --- Arrays/smallest_difference.cpp | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Arrays/smallest_difference.cpp diff --git a/Arrays/smallest_difference.cpp b/Arrays/smallest_difference.cpp new file mode 100644 index 00000000..d60365d6 --- /dev/null +++ b/Arrays/smallest_difference.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include + +using namespace std; + +// SmallestDifference takes in two slices of integers and returns a pair of integers, one from each slice, such that their +// absolute difference is as close to zero as possible. If multiple pairs have the same absolute difference, SmallestDifference +// returns the pair whose elements come first in the respective slices. +// Time complexity: O(nlog(n) + mlog(m)), where n and m are the lengths of array1 and array2, respectively +// Space complexity: O(1) +vector SmallestDifference(vector array1, vector array2) { + // Initialize variables to track the smallest absolute difference seen so far and the current absolute difference + int current = INT_MAX, smallest = INT_MAX; + // Sort the input arrays in ascending order to enable efficient searching for the pair with the smallest absolute difference + sort(array1.begin(), array1.end()); + sort(array2.begin(), array2.end()); + // Initialize variables to track the current index in each array + int idx1 = 0, idx2 = 0; + // Initialize an empty vector to store the pair of integers with the smallest absolute difference + vector result; + // Loop through both arrays until the end of at least one of them is reached + while (idx1 < array1.size() && idx2 < array2.size()) { + // Get the current elements from both arrays + int first = array1[idx1], second = array2[idx2]; + // Compute the absolute difference between the current elements + if (first < second) { + current = second - first; + idx1++; + } else if (second < first) { + current = first - second; + idx2++; + } else { + // If the current elements are equal, we have found a pair with an absolute difference of 0 and can return it + return vector{first, second}; + } + // If the current absolute difference is smaller than the smallest seen so far, update the smallest difference and the result vector + if (smallest > current) { + smallest = current; + result = vector{first, second}; + } + } + // Return the pair of integers with the smallest absolute difference + return result; +} + + +int main() { + vector array1 = {1, 3, 15, 11, 2}; + vector array2 = {23, 127, 235, 19, 8}; + vector result = SmallestDifference(array1, array2); + cout << "Smallest difference pair: [" << result[0] << ", " << result[1] << "]" << endl; + return 0; +} From 152fb96e396522275f27113b6a12c85e7c3d38e3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:22:34 +0530 Subject: [PATCH 0854/1894] add description --- Arrays/smallest_difference.cpp | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/Arrays/smallest_difference.cpp b/Arrays/smallest_difference.cpp index d60365d6..ef87f76c 100644 --- a/Arrays/smallest_difference.cpp +++ b/Arrays/smallest_difference.cpp @@ -1,3 +1,29 @@ +/* + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + + + The code finds the pair of elements from two arrays, array1 and array2, whose absolute difference is the smallest + among all possible pairs. It does this by first sorting both arrays and then using two pointers (idx1 and idx2) + to iterate through the arrays. At each iteration, it compares the current element of array1 and array2, + and updates smallest (the smallest absolute difference so far) and result (the pair of elements that give + the smallest absolute difference) if the absolute difference between the current elements is smaller than + the current smallest. The function returns the result at the end. + + Time complexity: O(nlog(n) + mlog(m)), where n and m are the lengths of array1 and array2, respectively + Space complexity: O(1) +*/ #include #include #include @@ -5,11 +31,9 @@ using namespace std; -// SmallestDifference takes in two slices of integers and returns a pair of integers, one from each slice, such that their +// SmallestDifference takes in two Vector of integers and returns a pair of integers, one from each Vector, such that their // absolute difference is as close to zero as possible. If multiple pairs have the same absolute difference, SmallestDifference // returns the pair whose elements come first in the respective slices. -// Time complexity: O(nlog(n) + mlog(m)), where n and m are the lengths of array1 and array2, respectively -// Space complexity: O(1) vector SmallestDifference(vector array1, vector array2) { // Initialize variables to track the smallest absolute difference seen so far and the current absolute difference int current = INT_MAX, smallest = INT_MAX; From f9cb185f78c85b341fcf6ec6f330b1770a99ca8d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:24:35 +0530 Subject: [PATCH 0855/1894] add javascript version of smallest difference --- Arrays/smallest_difference.js | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Arrays/smallest_difference.js diff --git a/Arrays/smallest_difference.js b/Arrays/smallest_difference.js new file mode 100644 index 00000000..b6cd65f9 --- /dev/null +++ b/Arrays/smallest_difference.js @@ -0,0 +1,38 @@ +/** + * Given two arrays of integers, finds a pair of values (one value from each array) + * that have the smallest difference. Returns the pair as an array. + * @param {number[]} array1 - The first array of integers + * @param {number[]} array2 - The second array of integers + * @returns {number[]} - The pair of values that have the smallest difference + */ +function smallestDifference(array1, array2) { + let currentDiff = Infinity; // initialize current difference to a large number + let smallestDiff = Infinity; // initialize smallest difference to a large number + let result = []; // initialize result array + array1.sort((a, b) => a - b); // sort the first array in ascending order + array2.sort((a, b) => a - b); // sort the second array in ascending order + let idx1 = 0; // initialize index for first array + let idx2 = 0; // initialize index for second array + while (idx1 < array1.length && idx2 < array2.length) { + const first = array1[idx1]; + const second = array2[idx2]; + if (first < second) { + // if the value from first array is smaller + currentDiff = second - first; // update the current difference + idx1++; // move the index of first array to the right + } else if (second < first) { + // if the value from second array is smaller + currentDiff = first - second; // update the current difference + idx2++; // move the index of second array to the right + } else { + // if the values are equal, the smallest difference is 0 + return [first, second]; + } + if (smallestDiff > currentDiff) { + // if the current difference is smaller than the smallest difference so far + smallestDiff = currentDiff; // update the smallest difference + result = [first, second]; // update the result array + } + } + return result; +} From 7d9a354685a25fee72c8abb668ce8dd6b0edffb0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:25:31 +0530 Subject: [PATCH 0856/1894] add description --- Arrays/smallest_difference.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Arrays/smallest_difference.js b/Arrays/smallest_difference.js index b6cd65f9..8d5829b2 100644 --- a/Arrays/smallest_difference.js +++ b/Arrays/smallest_difference.js @@ -1,3 +1,27 @@ +/* + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + The smallestDifference function takes in two arrays of integers and finds the pair of values (one from each array) + that have the smallest difference. It does this by sorting the two arrays in ascending order, and then iterating + through both arrays using two index variables. At each step, the function calculates the difference between the + values pointed to by the index variables, updates the current difference, and moves the index of the array with + the smaller value to the right. If the values are equal, the function returns the pair as an array. + The function keeps track of the smallest difference seen so far, and updates the result array accordingly. + Finally, the function returns the result array containing the pair with the smallest difference. + + O(nlog(n) + mlog(m)) time | O(1) space - where n is the length of the first input array and m is the length of the second input array +*/ /** * Given two arrays of integers, finds a pair of values (one value from each array) * that have the smallest difference. Returns the pair as an array. From b38bd39c8c21469a1272f9c10777de18016ce26f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:28:20 +0530 Subject: [PATCH 0857/1894] add python version of smallest diff --- Arrays/smallest_difference.py | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Arrays/smallest_difference.py diff --git a/Arrays/smallest_difference.py b/Arrays/smallest_difference.py new file mode 100644 index 00000000..d419c4b9 --- /dev/null +++ b/Arrays/smallest_difference.py @@ -0,0 +1,51 @@ +from typing import List +import math + +def smallest_difference(array1: List[int], array2: List[int]) -> List[int]: + """ + Finds the pair of integers, one from each of the two given arrays, with the smallest difference between them. + + Args: + array1: A list of integers. + array2: A list of integers. + + Returns: + A list of two integers, where the first integer is from array1 and the second is from array2, and the absolute + difference between them is the smallest among all such pairs. + + Example: + >>> smallest_difference([1, 3, 15, 11, 2], [23, 127, 235, 19, 8]) + [11, 8] + """ + current = math.inf + smallest = math.inf + result = [] + + # Sort both input arrays in ascending order + array1.sort() + array2.sort() + + # Initialize two pointers, one for each array + idx1, idx2 = 0, 0 + + # Loop through both arrays while the pointers are still within bounds + while idx1 < len(array1) and idx2 < len(array2): + first, second = array1[idx1], array2[idx2] + + # Calculate the absolute difference between the two current numbers + current = abs(first - second) + + # Update the smallest difference and the result if the current difference is smaller + if current < smallest: + smallest = current + result = [first, second] + + # If the first number is smaller than the second number, increment the pointer + # for the first array, otherwise increment the pointer for the second array. + if first < second: + idx1 += 1 + else: + idx2 += 1 + + # Return the result + return result From 84d02c2d0e630bd76d12c51f95f9d27f77f4482d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:28:47 +0530 Subject: [PATCH 0858/1894] add main func --- Arrays/smallest_difference.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Arrays/smallest_difference.py b/Arrays/smallest_difference.py index d419c4b9..efdc6c06 100644 --- a/Arrays/smallest_difference.py +++ b/Arrays/smallest_difference.py @@ -49,3 +49,14 @@ def smallest_difference(array1: List[int], array2: List[int]) -> List[int]: # Return the result return result + +def main(): + array1 = [1, 3, 15, 11, 2] + array2 = [23, 127, 235, 19, 8] + result = smallest_difference(array1, array2) + print("Array 1:", array1) + print("Array 2:", array2) + print("Smallest Difference Pair:", result) + +if __name__ == "__main__": + main() \ No newline at end of file From f6cc5610f5833b8d8612fbf8bf95151a2346dc5c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 29 Apr 2023 09:29:49 +0530 Subject: [PATCH 0859/1894] add description --- Arrays/smallest_difference.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Arrays/smallest_difference.py b/Arrays/smallest_difference.py index efdc6c06..a468367f 100644 --- a/Arrays/smallest_difference.py +++ b/Arrays/smallest_difference.py @@ -1,3 +1,25 @@ +''' + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + + The smallest_difference function takes two arrays of integers as input and returns a list of two integers, where the first integer + is from the first array and the second is from the second array, and the absolute difference between them is the smallest among + all such pairs. It achieves this by sorting the two arrays and then iterating through them in parallel, keeping track of the + current smallest difference and the pair of integers that produced it. The function returns the pair with the smallest difference. + + O(nlog(n) + mlog(m)) time | O(1) space - where n is the length of the first input array and m is the length of the second input array +''' from typing import List import math From 3232e0b37dd61be2accee11abbd5212e8329e053 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:44:23 +0530 Subject: [PATCH 0860/1894] move to 2d folder --- {Arrays => 2D Arrays (Matrix)}/spiral_traverse.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Arrays => 2D Arrays (Matrix)}/spiral_traverse.java (100%) diff --git a/Arrays/spiral_traverse.java b/2D Arrays (Matrix)/spiral_traverse.java similarity index 100% rename from Arrays/spiral_traverse.java rename to 2D Arrays (Matrix)/spiral_traverse.java From 761528134ad9c6aadd9fcecfe08d15067eab5b98 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:44:52 +0530 Subject: [PATCH 0861/1894] add spiral traversal in go --- 2D Arrays (Matrix)/spiral_traverse.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 2D Arrays (Matrix)/spiral_traverse.go diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go new file mode 100644 index 00000000..e69de29b From d2610a0fbc78f40c5ccf2001d5e368702832eb7b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:46:19 +0530 Subject: [PATCH 0862/1894] add comments --- 2D Arrays (Matrix)/spiral_traverse.go | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go index e69de29b..56ee1463 100644 --- a/2D Arrays (Matrix)/spiral_traverse.go +++ b/2D Arrays (Matrix)/spiral_traverse.go @@ -0,0 +1,48 @@ +package main + +func SpiralTraverse(array [][]int) []int { + // Initialize an empty slice to hold the result + result := []int{} + // If the input array is empty, return the empty result + if len(array) == 0 { + return result + } + // Initialize variables to keep track of the boundaries of the matrix + startRow, endRow := 0, len(array)-1 + startCol, endCol := 0, len(array[0])-1 + + // Traverse the matrix in a spiral order + for startRow <= endRow && startCol <= endCol { + // Traverse the top row from left to right + for col := startCol; col <= endCol; col++ { + result = append(result, array[startRow][col]) + } + // Traverse the rightmost column from top to bottom + for row := startRow + 1; row <= endRow; row++ { + result = append(result, array[row][endCol]) + } + // Traverse the bottom row from right to left, if there is more than one row + for col := endCol - 1; col >= startCol; col-- { + // If there is only one row left, break the loop to avoid duplicating the elements + if startRow == endRow { + break + } + result = append(result, array[endRow][col]) + } + // Traverse the leftmost column from bottom to top, if there is more than one column + for row := endRow - 1; row > startRow; row-- { + // If there is only one column left, break the loop to avoid duplicating the elements + if startCol == endCol { + break + } + result = append(result, array[row][startCol]) + } + // Update the boundaries of the matrix + startRow++ + endRow-- + startCol++ + endCol-- + } + // Return the result slice + return result +} From f2fd324d667e4ada978fdf82920118b8f553c245 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:47:52 +0530 Subject: [PATCH 0863/1894] add main func --- 2D Arrays (Matrix)/spiral_traverse.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go index 56ee1463..c72fefd4 100644 --- a/2D Arrays (Matrix)/spiral_traverse.go +++ b/2D Arrays (Matrix)/spiral_traverse.go @@ -1,5 +1,7 @@ package main +import "fmt" + func SpiralTraverse(array [][]int) []int { // Initialize an empty slice to hold the result result := []int{} @@ -46,3 +48,18 @@ func SpiralTraverse(array [][]int) []int { // Return the result slice return result } + +func main() { + // Example 2D array + array := [][]int{ + {1, 2, 3, 4}, + {10, 11, 12, 5}, + {9, 8, 7, 6}, + } + + // Call SpiralTraverse function on array + result := SpiralTraverse(array) + + // Print the result to console + fmt.Println(result) +} \ No newline at end of file From 47b791ddef9b578c0bc3046d993182996cf9a8e4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:48:52 +0530 Subject: [PATCH 0864/1894] add question --- 2D Arrays (Matrix)/spiral_traverse.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go index c72fefd4..1fb8ee6b 100644 --- a/2D Arrays (Matrix)/spiral_traverse.go +++ b/2D Arrays (Matrix)/spiral_traverse.go @@ -1,3 +1,12 @@ +/* + Write a function that takes in an n x m two-dimensional array (that can be + square-shaped when n == m) and returns a one-dimensional array of all the + array's elements in spiral order. + + Spiral order starts at the top left corner of the two-dimensional array, goes + to the right, and proceeds in a spiral pattern all the way until every element + has been visited. +*/ package main import "fmt" From 4ef70595596d2b0017c188aa68765a1cd14ec828 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:50:29 +0530 Subject: [PATCH 0865/1894] add explanation --- 2D Arrays (Matrix)/spiral_traverse.go | 32 ++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go index 1fb8ee6b..8eeaa915 100644 --- a/2D Arrays (Matrix)/spiral_traverse.go +++ b/2D Arrays (Matrix)/spiral_traverse.go @@ -1,11 +1,31 @@ /* - Write a function that takes in an n x m two-dimensional array (that can be - square-shaped when n == m) and returns a one-dimensional array of all the - array's elements in spiral order. + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and + returns a one-dimensional array of all the array's elements in spiral order. - Spiral order starts at the top left corner of the two-dimensional array, goes - to the right, and proceeds in a spiral pattern all the way until every element - has been visited. + Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds + in a spiral pattern all the way until every element has been visited. + + Explanation: + + The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the + elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise. + + The function first initializes an empty slice result to hold the elements of the spiral traversal. + If the input array is empty, the function immediately returns the empty result. + + Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the + boundaries of the matrix. These variables will be updated as the function traverses the matrix. + + The function then enters a loop that traverses the matrix in a spiral order. The loop continues + as long as startRow <= endRow and startCol <= endCol, which means that there are still elements + in the matrix to be traversed. + + The first step in the loop is to traverse the top row of the matrix from left to right, and append + each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom, + and append each element to the result slice. If there is more than one row in the matrix, the function then traverses + the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left, + the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix, + the function traverses the left */ package main From 44dcc3fd5d867ca0892f57491f2203052a4db100 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:50:56 +0530 Subject: [PATCH 0866/1894] add time and space complexity --- 2D Arrays (Matrix)/spiral_traverse.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/2D Arrays (Matrix)/spiral_traverse.go b/2D Arrays (Matrix)/spiral_traverse.go index 8eeaa915..8287b6cd 100644 --- a/2D Arrays (Matrix)/spiral_traverse.go +++ b/2D Arrays (Matrix)/spiral_traverse.go @@ -26,6 +26,8 @@ the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left, the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix, the function traverses the left + + O(n) time | O(n) space - where n is the total number of elements in the array */ package main From b28250cadf0620cc8b4f6beaf3e39b73e954be90 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:51:25 +0530 Subject: [PATCH 0867/1894] update description --- 2D Arrays (Matrix)/spiral_traverse.java | 39 +++++++++++++++---------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/2D Arrays (Matrix)/spiral_traverse.java b/2D Arrays (Matrix)/spiral_traverse.java index 29cb5506..d9d88cb5 100644 --- a/2D Arrays (Matrix)/spiral_traverse.java +++ b/2D Arrays (Matrix)/spiral_traverse.java @@ -1,26 +1,35 @@ -import java.util.*; +/* + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and + returns a one-dimensional array of all the array's elements in spiral order. -/** - * + Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds + in a spiral pattern all the way until every element has been visited. - Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and returns a one-dimensional array of all the array's elements in spiral order. + Explanation: - Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds in a spiral pattern all the way until every element has been visited. - Sample Input + The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the + elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise. - array = [ - [1, 2, 3, 4], - [12, 13, 14, 5], - [11, 16, 15, 6], - [10, 9, 8, 7], - ] + The function first initializes an empty slice result to hold the elements of the spiral traversal. + If the input array is empty, the function immediately returns the empty result. - Sample Output + Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the + boundaries of the matrix. These variables will be updated as the function traverses the matrix. - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + The function then enters a loop that traverses the matrix in a spiral order. The loop continues + as long as startRow <= endRow and startCol <= endCol, which means that there are still elements + in the matrix to be traversed. + The first step in the loop is to traverse the top row of the matrix from left to right, and append + each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom, + and append each element to the result slice. If there is more than one row in the matrix, the function then traverses + the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left, + the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix, + the function traverses the left - */ + O(n) time | O(n) space - where n is the total number of elements in the array +*/ +import java.util.*; public class SpiralTraverse { public static void main(String[] args) { From 8b0e3469969bf9fc4e4d5facceef577e88238964 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:56:07 +0530 Subject: [PATCH 0868/1894] update spiral_print version for c++ with comments --- 2D Arrays (Matrix)/matrix_spiral_print.cpp | 83 ++++++++++++---------- 1 file changed, 47 insertions(+), 36 deletions(-) diff --git a/2D Arrays (Matrix)/matrix_spiral_print.cpp b/2D Arrays (Matrix)/matrix_spiral_print.cpp index 41241c72..8b41530d 100644 --- a/2D Arrays (Matrix)/matrix_spiral_print.cpp +++ b/2D Arrays (Matrix)/matrix_spiral_print.cpp @@ -1,49 +1,60 @@ // Printing Matrix in spiral order #include using namespace std; -void print_spiral(int Mat[][10], int R, int C){ - int startRow = 0, endRow = R-1, startCol = 0, endCol = C-1; - while(startRow <= endRow && startCol <= endCol){ - // Print first row - for(int i = startCol; i <= endCol; i++){ - cout << Mat[startRow][i]; + +#include +using namespace std; + +vector SpiralTraverse(vector> array) { + vector result; // vector to store the spiral traversal + int rows = array.size(); // number of rows in the input array + int cols = array[0].size(); // number of columns in the input array + int startRow = 0, endRow = rows - 1; // indices for the start and end row of the current subarray + int startCol = 0, endCol = cols - 1; // indices for the start and end column of the current subarray + + // loop until the entire input array is traversed + while (startRow <= endRow && startCol <= endCol) { + // traverse the top row from left to right + for (int col = startCol; col <= endCol; col++) { + result.push_back(array[startRow][col]); } - startRow++; - // print end col - for(int i = startRow; i <= endRow; i++){ - cout << Mat[i][endCol]; + // traverse the right column from top to bottom + for (int row = startRow + 1; row <= endRow; row++) { + result.push_back(array[row][endCol]); } - endCol--; - // Print end row - if(endRow > startRow){ - for(int i = endCol; i >= startCol; i--){ - cout << Mat[endRow][i]; + // traverse the bottom row from right to left + for (int col = endCol - 1; col >= startCol; col--) { + // check if there is only one row in the subarray + if (startRow == endRow) { + break; } - endRow--; + result.push_back(array[endRow][col]); } - // print start row - if(startCol < endCol){ - for(int i = endRow; i >= startRow; i--){ - cout << Mat[i][startCol]; + // traverse the left column from bottom to top + for (int row = endRow - 1; row > startRow; row--) { + // check if there is only one column in the subarray + if (startCol == endCol) { + break; } - startCol++; - } - } -} -int main(){ - int Mat[10][10], R, C; - cin >> R >> C; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> Mat[i][j]; + result.push_back(array[row][startCol]); } + // update the indices for the next subarray to be traversed + startRow++; + endRow--; + startCol++; + endCol--; } - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; + + return result; +} + +int main() { + vector> array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + vector result = SpiralTraverse(array); + cout << "Spiral traversal: "; + for (int i = 0; i < result.size(); i++) { + cout << result[i] << " "; } - print_spiral(Mat, R, C); + cout << endl; return 0; } \ No newline at end of file From b4c6c50624eb42b64512ef2c22457f9db771645d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Apr 2023 13:56:52 +0530 Subject: [PATCH 0869/1894] update description and rename file --- ...x_spiral_print.cpp => spiral_traverse.cpp} | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) rename 2D Arrays (Matrix)/{matrix_spiral_print.cpp => spiral_traverse.cpp} (52%) diff --git a/2D Arrays (Matrix)/matrix_spiral_print.cpp b/2D Arrays (Matrix)/spiral_traverse.cpp similarity index 52% rename from 2D Arrays (Matrix)/matrix_spiral_print.cpp rename to 2D Arrays (Matrix)/spiral_traverse.cpp index 8b41530d..da8b879f 100644 --- a/2D Arrays (Matrix)/matrix_spiral_print.cpp +++ b/2D Arrays (Matrix)/spiral_traverse.cpp @@ -1,4 +1,34 @@ -// Printing Matrix in spiral order +/* + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) and + returns a one-dimensional array of all the array's elements in spiral order. + + Spiral order starts at the top left corner of the two-dimensional array, goes to the right, and proceeds + in a spiral pattern all the way until every element has been visited. + + Explanation: + + The SpiralTraverse function takes a 2D integer array array and returns a 1D integer slice that contains the + elements of array traversed in a spiral order, starting from the top-left corner and moving clockwise. + + The function first initializes an empty slice result to hold the elements of the spiral traversal. + If the input array is empty, the function immediately returns the empty result. + + Next, the function initializes variables startRow, endRow, startCol, and endCol to keep track of the + boundaries of the matrix. These variables will be updated as the function traverses the matrix. + + The function then enters a loop that traverses the matrix in a spiral order. The loop continues + as long as startRow <= endRow and startCol <= endCol, which means that there are still elements + in the matrix to be traversed. + + The first step in the loop is to traverse the top row of the matrix from left to right, and append + each element to the result slice. The next step is to traverse the rightmost column of the matrix from top to bottom, + and append each element to the result slice. If there is more than one row in the matrix, the function then traverses + the bottom row of the matrix from right to left, and appends each element to the result slice. If there is only one row left, + the loop is broken to avoid duplicating the elements. Finally, if there is more than one column in the matrix, + the function traverses the left + + O(n) time | O(n) space - where n is the total number of elements in the array +*/ #include using namespace std; From f3eb8f497b00ba9607e3c92c2c1dd97acd46ad42 Mon Sep 17 00:00:00 2001 From: TANISHA JAISWAL Date: Mon, 1 May 2023 00:23:34 +0530 Subject: [PATCH 0870/1894] Create Palindrome_Number_Java.java Java program for checking whether a number is palindrome. --- Math/Palindrome_Number_Java.java | 48 ++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Math/Palindrome_Number_Java.java diff --git a/Math/Palindrome_Number_Java.java b/Math/Palindrome_Number_Java.java new file mode 100644 index 00000000..6e91df90 --- /dev/null +++ b/Math/Palindrome_Number_Java.java @@ -0,0 +1,48 @@ +/* Question : Given an integer x, return true if x is a palindrome, and false otherwise. + +Example 1: + +Input: x = 121 +Output: true +Explanation: 121 reads as 121 from left to right and from right to left. +Example 2: + +Input: x = -121 +Output: false +Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. +Example 3: + +Input: x = 10 +Output: false +Explanation: Reads 01 from right to left. Therefore it is not a palindrome. + + +Constraints: + +-231 <= x <= 231 - 1 */ + +class Solution { + public boolean isPalindrome(int x) { + if(x < 0){ + return false; + } + + //Checking if the number is equal to its reverse, if true, it is a palindrome + return x == rev(x); + } + + + // Function to find reverse of a number + + public int reverse(int n){ + int reverse = 0; + while(n != 0){ + int digit = n % 10; + rev = digit + reverse * 10; + n /= 10; + } + + return reverse; + } +} + From 7c08b7549a76aeea36156b6a43bd5d953caf60a0 Mon Sep 17 00:00:00 2001 From: TANISHA JAISWAL Date: Mon, 1 May 2023 00:59:49 +0530 Subject: [PATCH 0871/1894] Create find_three_largest_numbers.java A function that returns a sorted array of the three largest integers in the input array. --- Arrays/find_three_largest_numbers.java | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Arrays/find_three_largest_numbers.java diff --git a/Arrays/find_three_largest_numbers.java b/Arrays/find_three_largest_numbers.java new file mode 100644 index 00000000..05007a09 --- /dev/null +++ b/Arrays/find_three_largest_numbers.java @@ -0,0 +1,36 @@ +/* + +Problem Statement : + +Write a function that takes in an array of at least three integers and, without sorting the input array, returns a sorted array of the three largest integers in the input array. + +Explanation: + +Here's how the function works: + +1. We create a new array result with three elements to store the three largest integers. +2. We loop through the input array, and for each integer, we compare it to the largest integer in result. +3. If the integer is larger than the largest integer in result, we shift the elements in result down one position and add the integer to the end. +4. If the integer is larger than the second largest integer in result, we shift the elements in result down one position starting from the second position and add the integer to the second position. +5. If the integer is larger than the third largest integer in result, we add the integer to the third position. +6. At the end of the loop, result will contain the three largest integers in the input array, sorted in descending order. + +*/ + +public static int[] findThreeLargest(int[] array) { + int[] result = new int[3]; + for (int num : array) { + if (num > result[2]) { + result[0] = result[1]; + result[1] = result[2]; + result[2] = num; + } else if (num > result[1]) { + result[0] = result[1]; + result[1] = num; + } else if (num > result[0]) { + result[0] = num; + } + } + return result; +} + From dcbfe1fcc47a60a45bf9a8628197b832b9578d1e Mon Sep 17 00:00:00 2001 From: srinivas892 <103558109+srinivas892@users.noreply.github.com> Date: Mon, 1 May 2023 15:53:27 +0530 Subject: [PATCH 0872/1894] Create Reverse_Integer.cpp --- Math/Reverse_Integer.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/Reverse_Integer.cpp diff --git a/Math/Reverse_Integer.cpp b/Math/Reverse_Integer.cpp new file mode 100644 index 00000000..11003a17 --- /dev/null +++ b/Math/Reverse_Integer.cpp @@ -0,0 +1,37 @@ +/* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. + +Assume the environment does not allow you to store 64-bit integers (signed or unsigned). +Example 1: + +Input: x = 123 +Output: 321 +Example 2: + +Input: x = -123 +Output: -321 +Example 3: + +Input: x = 120 +Output: 21 + + +Constraints: + +-2^31 <= x <= 2^31 - 1 +*/ +// function for reversing the integer; + + int reverse(int x) { + int ans =0; + if(x > INT_MAX || x < INT_MIN) // checking the integer is in range of -2^31 <= x <= 2^31 - 1 + return 0; + while(x != 0){ + if(ans > INT_MAX/10 || ans < INT_MIN/10) // -2^31 <= x <= 2^31 - 1 this condition for border values of range + return 0; + ans = ans*10; // we increaing the unit position each itereation + ans += x%10; // here we finding the last unit elemet so that we can add in ans + x /=10; // decreamenting the value or we can say elemenating the last unit element that we are find + + } + return ans; // returning the ans; + } From be779f491e893e57f89e71be87792761f5f92329 Mon Sep 17 00:00:00 2001 From: Suraj S Date: Mon, 1 May 2023 19:28:45 +0530 Subject: [PATCH 0873/1894] Create bucket-sort.js --- sorting/bucket-sort.js | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 sorting/bucket-sort.js diff --git a/sorting/bucket-sort.js b/sorting/bucket-sort.js new file mode 100644 index 00000000..ec057f31 --- /dev/null +++ b/sorting/bucket-sort.js @@ -0,0 +1,51 @@ +function bucketSort(arr, bucketSize = 5) { + if (arr.length === 0) { + return arr; + } + + // Determine minimum and maximum values in the array + let minValue = arr[0]; + let maxValue = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] < minValue) { + minValue = arr[i]; + } else if (arr[i] > maxValue) { + maxValue = arr[i]; + } + } + + // Determine number of buckets needed and initialize empty buckets + const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; + const buckets = new Array(bucketCount); + for (let i = 0; i < bucketCount; i++) { + buckets[i] = []; + } + + // Assign array elements to buckets based on their value + for (let i = 0; i < arr.length; i++) { + const bucketIndex = Math.floor((arr[i] - minValue) / bucketSize); + buckets[bucketIndex].push(arr[i]); + } + + // Sort each bucket using another sorting algorithm (here, insertion sort) + const sortedArray = []; + for (let i = 0; i < buckets.length; i++) { + const bucket = buckets[i]; + insertionSort(bucket); + sortedArray.push(...bucket); + } + + return sortedArray; +} + +function insertionSort(arr) { + for (let i = 1; i < arr.length; i++) { + const currentValue = arr[i]; + let j = i - 1; + while (j >= 0 && arr[j] > currentValue) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = currentValue; + } +} From 259d1b96e34c33068e71417ad51bcc169526e165 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Mon, 1 May 2023 19:41:32 +0530 Subject: [PATCH 0874/1894] Added Code for Find Intersection of 2 Linked List [Problem 160 of LeetCode] --- .../intersection_of_two_linked_lists.cpp | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Linked List/intersection_of_two_linked_lists.cpp diff --git a/Linked List/intersection_of_two_linked_lists.cpp b/Linked List/intersection_of_two_linked_lists.cpp new file mode 100644 index 00000000..8439bd65 --- /dev/null +++ b/Linked List/intersection_of_two_linked_lists.cpp @@ -0,0 +1,79 @@ +/* + + Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. + + + Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 + Output: Intersected at '8' + + Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 + Output: Intersected at '2' + + Constraints: + + > The number of nodes of listA is in the m. + > The number of nodes of listB is in the n. + > 1 <= m, n <= 3 * 104 + > 1 <= Node.val <= 105 + > 0 <= skipA < m + > 0 <= skipB < n + > intersectVal is 0 if listA and listB do not intersect. + > intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect. + +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + // Define basic variables needed + int len1=0; + int len2=0; + ListNode* tempA=headA; + ListNode* tempB=headB; + + // Calculate the length of both Linked Lists and store in len1 and len2 + while(tempA!=NULL) + { + len1++; + tempA=tempA->next; + } + while(tempB!=NULL) + { + len2++; + tempB=tempB->next; + } + + // Here, we assume that length of Linked-List A is less than or equal + // to that of Linked List B + if(len1>len2){ + swap(headA,headB); + } + + // Re-initialize variables + tempA=headA; + tempB=headB; + int n=abs(len2-len1); + while(n--) + { + tempB=tempB->next; + } + + // Finally, Find the Intersection Node + while(tempA!=tempB) + { + tempA=tempA->next; + tempB=tempB->next; + } + + // Return the final answer + return tempA; + } +}; \ No newline at end of file From c24fa2aa3e9cbc926a8789083d009ef7b585e28e Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Mon, 1 May 2023 19:50:25 +0530 Subject: [PATCH 0875/1894] Add Two Numbers in C++ #620 --- Linked List/addTwoNumbers.cpp | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Linked List/addTwoNumbers.cpp diff --git a/Linked List/addTwoNumbers.cpp b/Linked List/addTwoNumbers.cpp new file mode 100644 index 00000000..67d3dc6e --- /dev/null +++ b/Linked List/addTwoNumbers.cpp @@ -0,0 +1,75 @@ +/* + You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + + You may assume the two numbers do not contain any leading zero, except the number 0 itself. + + Input: l1 = [2,4,3], l2 = [5,6,4] + Output: [7,0,8] + + Input: l1 = [0], l2 = [0] + Output: [0] + + Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] + Output: [8,9,9,9,0,0,0,1] + + Constraints: + + > The number of nodes in each linked list is in the range [1, 100]. + > 0 <= Node.val <= 9 + > It is guaranteed that the list represents a number that does not have leading zeros. + +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + ListNode* ansHead=new ListNode((l1->val+l2->val)%10); + ListNode* ans=ansHead; + int carry=(l1->val+l2->val)/10; + l1=l1->next; + l2=l2->next; + while(l1!=NULL && l2!=NULL) + { + ListNode* temp= new ListNode((l1->val + l2->val + carry)%10); + carry = (l1->val + l2->val + carry)/10; + l1=l1->next; + l2=l2->next; + ans->next=temp; + ans=temp; + } + while(l1!=NULL) + { + ListNode* temp= new ListNode((l1->val + carry)%10); + carry = (l1->val + carry)/10; + l1=l1->next; + ans->next=temp; + ans=temp; + } + while(l2!=NULL) + { + ListNode* temp= new ListNode((l2->val + carry)%10); + carry = (l2->val + carry)/10; + l2=l2->next; + ans->next=temp; + ans=temp; + } + if (carry>0) + { + ListNode* temp= new ListNode(carry); + ans->next=temp; + ans=temp; + } + return ansHead; + } +}; \ No newline at end of file From 140eadc503876a695ec89b34675e42c268712855 Mon Sep 17 00:00:00 2001 From: Mehul Kumar <45559139+WonderSTK@users.noreply.github.com> Date: Mon, 1 May 2023 21:01:16 +0530 Subject: [PATCH 0876/1894] Create graphs_bfs_snakes_ladder.js --- Graphs/graphs_bfs_snakes_ladder.js | 133 +++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Graphs/graphs_bfs_snakes_ladder.js diff --git a/Graphs/graphs_bfs_snakes_ladder.js b/Graphs/graphs_bfs_snakes_ladder.js new file mode 100644 index 00000000..8b100dd1 --- /dev/null +++ b/Graphs/graphs_bfs_snakes_ladder.js @@ -0,0 +1,133 @@ +// Define the number of squares on the board + +const BOARD_SIZE = 100; + +// Define the start and end points of the snakes and ladders + +const snakesAndLadders = { + + 14: 4, 19: 8, 22: 20, 41: 38, 50: 39, 54: 34, 66: 53, 68: 63, 79: 67, 83: 72, + + 92: 88, 97: 76, 8: 15, 13: 23, 37: 43, 40: 48, 57: 63, 61: 69, 65: 72, 75: 83, + + 78: 87, 80: 92, 88: 94 + +}; + +// Define a function to build the game graph + +function buildGraph() { + + const graph = {}; + + for (let i = 1; i <= BOARD_SIZE; i++) { + + graph[i] = []; + + for (let j = i + 1; j <= i + 6 && j <= BOARD_SIZE; j++) { + + if (snakesAndLadders[j]) { + + graph[i].push(snakesAndLadders[j]); + + } else { + + graph[i].push(j); + + } + + } + + } + + return graph; + +} + +// Define the main function of the game + +function playGame() { + + // Build the game graph + + const graph = buildGraph(); + + // Define the starting node and the goal node + + const startNode = 1; + + const goalNode = BOARD_SIZE; + + // Define a queue for BFS + + const queue = [startNode]; + + // Define a visited set for BFS + + const visited = new Set(); + + visited.add(startNode); + + // Define a map for BFS to keep track of the parent node + + const parentMap = new Map(); + + parentMap.set(startNode, null); + + // Loop until the goal node is found or the queue is empty + + while (queue.length > 0) { + + // Dequeue the next node from the queue + + const currentNode = queue.shift(); + + // If the goal node is found, reconstruct the path and return it + + if (currentNode === goalNode) { + + const path = []; + + let node = currentNode; + + while (node !== null) { + + path.unshift(node); + + node = parentMap.get(node); + + } + + return path; + + } + + // Loop through the neighbors of the current node + + for (const neighbor of graph[currentNode]) { + + // If the neighbor has not been visited, add it to the queue + + if (!visited.has(neighbor)) { + + queue.push(neighbor); + + visited.add(neighbor); + + parentMap.set(neighbor, currentNode); + + } + + } + + } + + // If the goal node is not found, return null + + return null; + +} + +// Play the game and print the result + +console.log(playGame()); From bdf8b15c2d4ade4eec534f82a8677769145d2717 Mon Sep 17 00:00:00 2001 From: abhishekbhonde Date: Mon, 1 May 2023 21:39:57 +0530 Subject: [PATCH 0877/1894] added bucket sort --- sorting/bucket_sort.java | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 sorting/bucket_sort.java diff --git a/sorting/bucket_sort.java b/sorting/bucket_sort.java new file mode 100644 index 00000000..b07b2a03 --- /dev/null +++ b/sorting/bucket_sort.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.Collections; + +public class Bucket_Sort { + public static void bucketSort(double[] arr) { + int n = arr.length; + ArrayList[] buckets = new ArrayList[n]; + + // Create empty buckets + for (int i = 0; i < n; i++) { + buckets[i] = new ArrayList<>(); + } + + // Add elements to corresponding buckets + for (int i = 0; i < n; i++) { + int bucketIndex = (int) (n * arr[i]); + buckets[bucketIndex].add(arr[i]); + } + + // Sort individual buckets + for (int i = 0; i < n; i++) { + Collections.sort(buckets[i]); + } + + // Concatenate all buckets + int index = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < buckets[i].size(); j++) { + arr[index++] = buckets[i].get(j); + } + } + } + + public static void main(String[] args) { + double[] arr = {0.8, 0.3, 0.2, 0.9, 0.1, 0.6, 0.4, 0.7, 0.5, 0.0}; + bucketSort(arr); + System.out.println("Sorted array:"); + for (double d : arr) { + System.out.print(d + " "); + } + } +} From 43c33132f211e5d070558f09778535bd1240762a Mon Sep 17 00:00:00 2001 From: Thriver <97860789+SuyashSingh01@users.noreply.github.com> Date: Mon, 1 May 2023 23:02:28 +0530 Subject: [PATCH 0878/1894] rename the file Binary Search: Find First and Last Position of Element in Sorted Array in Javascript --- Binary Search/Binary_search_arr.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Binary Search/Binary_search_arr.js diff --git a/Binary Search/Binary_search_arr.js b/Binary Search/Binary_search_arr.js new file mode 100644 index 00000000..c2d3d1a6 --- /dev/null +++ b/Binary Search/Binary_search_arr.js @@ -0,0 +1,30 @@ +/** + * Finds the first and last occurrence of a target value in a sorted array. + * + * @param {number[]} N - The sorted array of numbers. + * @param {number} T - The target value to search for. + * @returns {number[]} An array containing the first and last index of the target value, or [-1,-1] if not found. + */ +const searchRange = function(N, T) { + // Helper function to perform binary search on the array + const find = (target, arr, left=0, right=arr.length) => { + while (left <= right) { + // Calculate the middle index + let mid = left + right >> 1; + // If the middle element is less than the target, move the left pointer to mid + 1 + if (arr[mid] < target) left = mid + 1; + // If the middle element is greater than or equal to the target, move the right pointer to mid - 1 + else right = mid - 1; + } + // Return the left pointer, which will be the index of the target or the insertion point if not found + return left; + }; + + // Find the leftmost index of the target value + let Tleft = find(T, N); + // If the target value is not found in the array, return [-1,-1] + if (N[Tleft] !== T) return [-1,-1]; + // Find the rightmost index of the target value + return [Tleft, find(T+1, N, Tleft) - 1]; + }; + \ No newline at end of file From 92ea44f70063b63b0c38b44c0856bdac66c14c4b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 1 May 2023 23:22:12 +0530 Subject: [PATCH 0879/1894] add first duplicate value --- Hash Table/first_duplicate_value.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Hash Table/first_duplicate_value.go diff --git a/Hash Table/first_duplicate_value.go b/Hash Table/first_duplicate_value.go new file mode 100644 index 00000000..2fcaa6e9 --- /dev/null +++ b/Hash Table/first_duplicate_value.go @@ -0,0 +1,12 @@ +package main + +func FirstDuplicateValue(array []int) int { + seenSoFar := make(map[int]bool) + for _, num := range array { + if _, valueExists := seenSoFar[num]; valueExists { + return num + } + seenSoFar[num] = true + } + return -1 +} From b639ac4b60eced6bf84044ad3721dbb9cba1552f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 1 May 2023 23:22:48 +0530 Subject: [PATCH 0880/1894] add main func --- Hash Table/first_duplicate_value.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Hash Table/first_duplicate_value.go b/Hash Table/first_duplicate_value.go index 2fcaa6e9..dc2085a3 100644 --- a/Hash Table/first_duplicate_value.go +++ b/Hash Table/first_duplicate_value.go @@ -1,5 +1,7 @@ package main +import "fmt" + func FirstDuplicateValue(array []int) int { seenSoFar := make(map[int]bool) for _, num := range array { @@ -10,3 +12,9 @@ func FirstDuplicateValue(array []int) int { } return -1 } + +func main() { + array := []int{2, 1, 5, 2, 3, 3, 4} + firstDuplicate := FirstDuplicateValue(array) + fmt.Println(firstDuplicate) +} From 821eb3956e107af21d27c13f76254c21b637ef5b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 1 May 2023 23:25:49 +0530 Subject: [PATCH 0881/1894] add description time and space complexity --- Hash Table/first_duplicate_value.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Hash Table/first_duplicate_value.go b/Hash Table/first_duplicate_value.go index dc2085a3..61ec19d6 100644 --- a/Hash Table/first_duplicate_value.go +++ b/Hash Table/first_duplicate_value.go @@ -1,3 +1,19 @@ +/* + + Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function + that returns the first integer that appears more than once (when the array is read from left to right). + + The time complexity of the `FirstDuplicateValue` function is O(n), where n is the length of the + input `array`. This is because the function iterates through the array once, performing constant + time operations (checking if a value exists in a hash map and inserting values into the hash map). + The worst case scenario is that the function iterates through the entire array without finding a + duplicate, resulting in O(n) time complexity. + + The space complexity of the given implementation is O(n), where n is the length of the input array. + This is because we are using a hash table (implemented as a map in Go) to store the elements we have + seen so far. In the worst case, where there are no duplicates in the array, we will end up storing + all n elements in the hash table, which would require O(n) space. +*/ package main import "fmt" From eb7bc15099c6deba0ccc2e89f77cf435a78bef6d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 1 May 2023 23:26:55 +0530 Subject: [PATCH 0882/1894] add explanation --- Hash Table/first_duplicate_value.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Hash Table/first_duplicate_value.go b/Hash Table/first_duplicate_value.go index 61ec19d6..ab9a3998 100644 --- a/Hash Table/first_duplicate_value.go +++ b/Hash Table/first_duplicate_value.go @@ -18,6 +18,14 @@ package main import "fmt" +/* + This function takes an array of integers as input and returns the first duplicate value found in + the array. It uses a hash table, implemented as a Go map, to keep track of the numbers seen so far. + For each number in the input array, the function checks if it has already been seen before by + checking if it exists as a key in the map. If it has been seen before, the function returns + the number as it is the first duplicate value found. Otherwise, the function adds the number + to the map with a value of true to indicate that it has been seen. +*/ func FirstDuplicateValue(array []int) int { seenSoFar := make(map[int]bool) for _, num := range array { From 41fb278dc54f9f54b1870fb712c878aace363755 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:27:40 +0530 Subject: [PATCH 0883/1894] add longest peak --- Arrays/longest_peak.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Arrays/longest_peak.go diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go new file mode 100644 index 00000000..520ab25b --- /dev/null +++ b/Arrays/longest_peak.go @@ -0,0 +1,29 @@ +package main + +func LongestPeak(array []int) int { + longestPeak := 0 + i := 1 + for i < len(array)-1 { + isPeak := array[i-1] < array[i] && array[i] > array[i+1] + if !isPeak { + i += 1 + continue + } + + leftIndex := i - 2 + for leftIndex >= 0 && array[leftIndex] < array[leftIndex+1] { + leftIndex-- + } + + rightIndex := i + 2 + for rightIndex < len(array) && array[rightIndex] < array[rightIndex-1] { + rightIndex++ + } + currentPeak := rightIndex - leftIndex - 1 + if currentPeak > longestPeak { + longestPeak = currentPeak + } + i = rightIndex + } + return longestPeak +} \ No newline at end of file From cde1c1ba2f05053d568d8b8f8eef8784bc25bc6d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:29:11 +0530 Subject: [PATCH 0884/1894] add main func --- Arrays/longest_peak.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go index 520ab25b..80e319e8 100644 --- a/Arrays/longest_peak.go +++ b/Arrays/longest_peak.go @@ -1,5 +1,7 @@ package main +import "fmt" + func LongestPeak(array []int) int { longestPeak := 0 i := 1 @@ -26,4 +28,10 @@ func LongestPeak(array []int) int { i = rightIndex } return longestPeak +} + +func main() { + array := []int{1, 2, 3, 4, 5, 4, 3, 2, 1} + longestPeak := LongestPeak(array) + fmt.Println(longestPeak) // Output: 9 } \ No newline at end of file From 23fe9d66f0aa58b42d2ea55076d470fcaa90e0a9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:29:34 +0530 Subject: [PATCH 0885/1894] add comments --- Arrays/longest_peak.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go index 80e319e8..b8cd7d4f 100644 --- a/Arrays/longest_peak.go +++ b/Arrays/longest_peak.go @@ -2,29 +2,40 @@ package main import "fmt" +// LongestPeak function takes an integer array and returns the length of the longest peak in the array. func LongestPeak(array []int) int { longestPeak := 0 i := 1 for i < len(array)-1 { + // check if i is a peak (i.e., it's greater than its neighbors) isPeak := array[i-1] < array[i] && array[i] > array[i+1] if !isPeak { + // if i is not a peak, move to the next element i += 1 continue } + // search left of i to find the beginning of the peak leftIndex := i - 2 for leftIndex >= 0 && array[leftIndex] < array[leftIndex+1] { leftIndex-- } + // search right of i to find the end of the peak rightIndex := i + 2 for rightIndex < len(array) && array[rightIndex] < array[rightIndex-1] { rightIndex++ } + + // calculate the length of the current peak currentPeak := rightIndex - leftIndex - 1 + + // update longestPeak if currentPeak is longer if currentPeak > longestPeak { longestPeak = currentPeak } + + // move i to the end of the current peak i = rightIndex } return longestPeak From 9c00ff9f8fb421ec1aa4add8bdf6e05849c15964 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:31:38 +0530 Subject: [PATCH 0886/1894] add description and explanation --- Arrays/longest_peak.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go index b8cd7d4f..1f4ac253 100644 --- a/Arrays/longest_peak.go +++ b/Arrays/longest_peak.go @@ -1,3 +1,34 @@ +/* + + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), + at which point they become strictly decreasing. At least three integers are required to form a peak. + + The code defines a function named LongestPeak that takes an array of integers as an argument and returns an integer + representing the length of the longest "peak" in the array. + + A "peak" is defined as a sequence of integers in the array that begins with an increasing sequence of integers, + reaches a maximum value (the "peak"), and ends with a decreasing sequence of integers. + + The function first initializes a variable longestPeak to 0, which will be used to store the length of the longest + peak found so far. It then initializes a variable i to 1, which will be used to iterate over the elements of the array. + + The function then enters a loop that continues until i is less than len(array) - 1. Inside the loop, the function checks + whether the current element at i is a peak, by comparing it to its neighboring elements. If it is not a peak, the loop continues by incrementing i. + + If the current element at i is a peak, the function searches to the left and right of the peak to find the beginning + and end of the peak. It does this by iterating left and right from the peak until it finds a decreasing sequence of + integers, using the variables leftIndex and rightIndex. + + Once the function has found the beginning and end of the peak, it calculates the length of the peak using the formula + rightIndex - leftIndex - 1. If the length of the current peak is greater than the current longest peak, it updates + longestPeak to the length of the current peak. + + Finally, the function updates the value of i to be the end of the peak (rightIndex), so that the loop will skip over + the entire peak and continue iterating from the end of the peak. + + The function returns the value of longestPeak once it has finished iterating over the array. +*/ package main import "fmt" From bebf5ab0a74bc20e41ab375d478849154620684d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:32:19 +0530 Subject: [PATCH 0887/1894] add time and space complexity --- Arrays/longest_peak.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go index 1f4ac253..cefc7e08 100644 --- a/Arrays/longest_peak.go +++ b/Arrays/longest_peak.go @@ -28,6 +28,10 @@ the entire peak and continue iterating from the end of the peak. The function returns the value of longestPeak once it has finished iterating over the array. + + The time complexity of the LongestPeak function is O(n), where n is the length of the input array, because it iterates through the array only once. + + The space complexity of the function is O(1), because it uses a constant amount of extra space, regardless of the size of the input array. */ package main From c4855c6a6bd88b8d8f53bb8d9b2c655101657196 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 2 May 2023 08:44:58 +0530 Subject: [PATCH 0888/1894] add sample io --- Hash Table/first_duplicate_value.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Hash Table/first_duplicate_value.go b/Hash Table/first_duplicate_value.go index ab9a3998..fa5cb47d 100644 --- a/Hash Table/first_duplicate_value.go +++ b/Hash Table/first_duplicate_value.go @@ -3,6 +3,9 @@ Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function that returns the first integer that appears more than once (when the array is read from left to right). + Sample Input = [2, 1, 5, 2, 3, 3, 4] + Output : 2 + The time complexity of the `FirstDuplicateValue` function is O(n), where n is the length of the input `array`. This is because the function iterates through the array once, performing constant time operations (checking if a value exists in a hash map and inserting values into the hash map). From e8bd067248893fba27ca59e42f3309c86c33cd43 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Tue, 2 May 2023 14:28:16 +0530 Subject: [PATCH 0889/1894] Linked list: Implement Doubly linked list in C++ --- .../implementation_Doubly_Linked_List.cpp | 196 ++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 Linked List/implementation_Doubly_Linked_List.cpp diff --git a/Linked List/implementation_Doubly_Linked_List.cpp b/Linked List/implementation_Doubly_Linked_List.cpp new file mode 100644 index 00000000..2990f96c --- /dev/null +++ b/Linked List/implementation_Doubly_Linked_List.cpp @@ -0,0 +1,196 @@ +/* Implementation of Doubly Linked List with Basic Functions: + > Addition of Node At Head + > Addition of Node At Tail + > Addition of Node In Between Of Linked List + > Deletion of Node At Head + > Deletion of Node At Tail + > Deletion of Intermediary Node Linked List + > Forward Traversal of Linked List + > Backward Traversal of Linked List +*/ +#include +using namespace std; + +// Define a doubly linked list node + +struct Node { + int val; + struct Node* next; + struct Node* prev; +}; + +// Function to inserts node at the head of the list +void insertAtHead(Node** head, int data) +{ + Node* temp = new Node; + temp->val = data; + + temp->next = (*head); + temp->prev = NULL; + + if ((*head) != NULL) + (*head)->prev = temp; + + (*head) = temp; +} + +// Function to inserts node at the tail of the list +void insertAtTail(Node** head, int data) +{ + + Node* temp = new Node; + temp->val = data; + temp->next = NULL; + + if (*head == NULL) { + temp->prev = NULL; + *head = temp; + return; + } + + Node* tail = *head; + + while (tail->next != NULL) + { + tail = tail->next; + } + + tail->next = temp; + temp->prev = tail; +} + +// Function to inserts after intermediary node +void insertAfterNode(Node* myNode, int data) +{ + if (myNode == NULL) return; + + Node* temp = new Node; + temp->val = data; + + temp->next = myNode->next; + myNode->next = temp; + temp->prev = myNode; + + if (temp->next != NULL) + temp->next->prev = temp; +} + +// Function to inserts node at the head of the list +Node* deleteAtHead(Node* head) +{ + if(head==NULL) return NULL; + Node* temp = head; + head = temp->next; + + head->prev = NULL; + delete temp; + return head; + +} + +// Function to inserts node at the tail of the list +void deleteAtTail(Node* head) +{ + if(head==NULL) return; + Node* temp = head; + while (temp->next != NULL) + { + temp = temp->next; + } + Node* tail=temp->prev; + tail->next=NULL; + delete temp; +} + +// Function to delete an intermediary node +void deleteNode(Node* myNode) +{ + if (myNode == NULL) return; + + Node* nextNode = myNode->next; + Node* prevNode = myNode->prev; + + nextNode->prev=prevNode; + prevNode->next=nextNode; + + delete myNode; +} + +// Function for forward Traversal +void displayList_F(Node* head) { + if(head==NULL) return; + Node* temp=head; + + while (temp != NULL) { + cout<val<<" "; + temp = temp->next; + } +} + +// Function for backward Traversal +void displayList_B(Node* head) { + if(head==NULL) return; + displayList_B(head->next); + cout<val<<" "; +} + +//main program +int main() { + /* Start with the empty list */ + Node* head = NULL; + + // Insert 40 as last node + insertAtTail(&head, 40); + + // insert 20 at the head + insertAtHead(&head, 20); + + // Insert 10 at the beginning. + insertAtHead(&head, 10); + + // Insert 50 at the end. + insertAtTail(&head, 50); + + // Insert 30, after 20. + insertAfterNode(head->next, 30); + + //Forward Traversal + cout<<"\n Forward Traversal of Doubly linked list is \n "<next->next); + + //Forward Traversal + cout<<"\n Forward Traversal of Doubly linked list is \n "< Date: Tue, 2 May 2023 14:50:07 +0530 Subject: [PATCH 0890/1894] Find first duplicate value in C++ --- Linked List/find_first_duplicate_value.cpp | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Linked List/find_first_duplicate_value.cpp diff --git a/Linked List/find_first_duplicate_value.cpp b/Linked List/find_first_duplicate_value.cpp new file mode 100644 index 00000000..3d1f894e --- /dev/null +++ b/Linked List/find_first_duplicate_value.cpp @@ -0,0 +1,43 @@ +/* + Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function + that returns the first integer that appears more than once (when the array is read from left to right). + + Sample Input = [2, 1, 5, 2, 3, 3, 4] + Output : 2 + + Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution +*/ + +#include +using namespace std; + +class Solution{ +public: + // O(N) time complexity and O(N) Space Complexity Solution + int findDuplicate1(vector& nums) + { + int N=nums.size(); + + // Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity + vector trk(N,false); + + for(int i=0;i& nums) + { + int N=nums.size(); + for(int i=0;i Date: Tue, 2 May 2023 15:30:31 +0530 Subject: [PATCH 0891/1894] String: Add Reverse Words in a String in C++ --- Strings/reverse_words_in_a_string.cpp | 51 +++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Strings/reverse_words_in_a_string.cpp diff --git a/Strings/reverse_words_in_a_string.cpp b/Strings/reverse_words_in_a_string.cpp new file mode 100644 index 00000000..3e331ff0 --- /dev/null +++ b/Strings/reverse_words_in_a_string.cpp @@ -0,0 +1,51 @@ +/* + Given an input string s, reverse the order of the words. + A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. + Return a string of the words in reverse order concatenated by a single space. + + [Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.] + + + Input: s = "the sky is blue" + Output: "blue is sky the" + + Input: s = " hello world " + Output: "world hello" + + Input: s = "a good example" + Output: "example good a" + + Constraints: + + > 1 <= s.length <= 104 + > s contains English letters (upper-case and lower-case), digits, and spaces ' '. + > There is at least one word in s. + +*/ +class Solution { +public: + string reverseWords(string s) { + stack st; + string ans; + string curr_word=""; + for(int i=0;i Date: Tue, 2 May 2023 16:30:23 +0530 Subject: [PATCH 0892/1894] Array: Find Longest peak of an array in C++ + Explanaition Added For Reverse Words In A String In C++ --- Arrays/find_longest_peak_of_an_array.cpp | 62 ++++++++++++++++++++++++ Strings/reverse_words_in_a_string.cpp | 9 ++++ 2 files changed, 71 insertions(+) create mode 100644 Arrays/find_longest_peak_of_an_array.cpp diff --git a/Arrays/find_longest_peak_of_an_array.cpp b/Arrays/find_longest_peak_of_an_array.cpp new file mode 100644 index 00000000..c27986ea --- /dev/null +++ b/Arrays/find_longest_peak_of_an_array.cpp @@ -0,0 +1,62 @@ +/* + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak. + + Sample Input = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3] + Output = 6 // 0, 10, 6, 5, -1, -3 +*/ +#include +using namespace std; +class Solution{ + public: + int maxPeakLength(vector nums) + { + + // Intitialize the required variables + bool beforePeak=true; + int maxLen=0; + int curLen=0; + + // Traverse through the array to find peaks + for(int i=0;inums[i+1]) + { + // Transiting into the latter strictly decreasing part of the peak + if(curLen<1){ + curLen=0; + beforePeak=true; + } + curLen++; + beforePeak=false; + } + else if(!beforePeak && nums[i]nums[i-1]) i-=2; + else if(nums[i]==nums[i-1]) i-=1; + beforePeak=true; + } + } + + // Return the final answer + return maxLen; + } +}; \ No newline at end of file diff --git a/Strings/reverse_words_in_a_string.cpp b/Strings/reverse_words_in_a_string.cpp index 3e331ff0..3b9a169a 100644 --- a/Strings/reverse_words_in_a_string.cpp +++ b/Strings/reverse_words_in_a_string.cpp @@ -25,9 +25,12 @@ class Solution { public: string reverseWords(string s) { + // Intitalize variables we will be needing stack st; string ans; string curr_word=""; + + // Traverse through the string and push each word into the stack seperated by ' '. for(int i=0;i Date: Tue, 2 May 2023 17:34:04 +0530 Subject: [PATCH 0893/1894] adding the three largest number problem --- Arrays/three_largest_numper.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Arrays/three_largest_numper.py diff --git a/Arrays/three_largest_numper.py b/Arrays/three_largest_numper.py new file mode 100644 index 00000000..17591fcc --- /dev/null +++ b/Arrays/three_largest_numper.py @@ -0,0 +1,16 @@ + + +class Solution: + def three_max_noo(self,arr: List[int])-> List[int]: + # give int minvalue to a,b,c + a,b,c= -9999,-9999,-9999 + # we will iterate through the array and compare the values + for i in arr: + if i > a: + a, b, c = i, a, b + elif i > b: + b, c = i, b + elif i > c: + c = i + # return the three max values as a sorted array + return [a, b, c] \ No newline at end of file From 2471ddb1838e4cf1376c84ccf7e854e69219bcfd Mon Sep 17 00:00:00 2001 From: Maximilian Firla Date: Tue, 2 May 2023 15:15:38 +0200 Subject: [PATCH 0894/1894] resolves ticket #1052 find three largest Integer in Javascript --- Arrays/find_three_largest_integers.js | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Arrays/find_three_largest_integers.js diff --git a/Arrays/find_three_largest_integers.js b/Arrays/find_three_largest_integers.js new file mode 100644 index 00000000..750ed1f0 --- /dev/null +++ b/Arrays/find_three_largest_integers.js @@ -0,0 +1,81 @@ +/* +Write a function that takes in an array of at least three integers and, +without sorting the input array, returns a sorted array of the three largest integers in the input array. + + +Approach: + +Before implementing the task logic the array will be checked to see if it meets the criteria. +Here the input array will be checked to see if it´s at least 3 elements big and if it +only contains integers. + +After that the logic is implemented. +Because the given array should not be sorted for this task, the used logic works as following: +1. Initialize a result array with 3 values, each of these 3 is initialized as -Infinity +2. Check if first element of array is bigger than the third result value + 2.1 If value is bigger set new value (will be true for the first check as initialized with -Infinity) + 2.2 shift current numbers in result array + 2.3 checks if element is bigger than value 2, and also value 1 - following above logic +3. Sorty the result array in descending order and console logs the result. +*/ + +function findThreeLargestInteger(array) { + + /************************************************************************ + * This block checks if given array matches the criteria * + ************************************************************************/ + let arrayLength = 0; + let onlyIntegers = true; + // iterate over given array and check each element + array.forEach(element => { + // is element an integer + if (!Number.isInteger(element)) { + onlyIntegers = false; + } + // count length of array + arrayLength++; + }); + + + /************************************************************************ + * Implementing the task logic * + ************************************************************************/ + if (onlyIntegers && arrayLength >= 3) { + // initialize result array with -Infinite + let result = [-Infinity, -Infinity, -Infinity]; + + // Loop through the input array + for (const num of array) { + // Check if the current number is larger than the third largest number + if (num > result[2]) { + // Shift the current numbers down the result array + result[0] = result[1]; + result[1] = result[2]; + result[2] = num; + } else if (num > result[1]) { + // Shift the current numbers down the result array + result[0] = result[1]; + result[1] = num; + } else if (num > result[0]) { + // Shift the current number down the result array + result[0] = num; + } + } + // sorts the result in descending order (big to small) + result.sort(function (a, b) { return b - a }); + console.log(result); + + } else { + console.log("The passed array does not match the expected criteria."); + } + +} + +const testArray = [5, -3, 5, 100, 3, 55, 999, -18]; +const functionCheck = findThreeLargestInteger(testArray); // prints [999, 100, 55] to console + +const arrayToShort = [100, 999]; +const unctionCheck1 = findThreeLargestInteger(arrayToShort); // prints "The passed array does not match the expected criteria." to console + +const arrayNoInt = [100, 999, 8.5]; +const unctionCheck2 = findThreeLargestInteger(arrayNoInt); // prints "The passed array does not match the expected criteria." to console \ No newline at end of file From 73fa7f121d99a5b43252005d16b4c798a721bf64 Mon Sep 17 00:00:00 2001 From: Subham5401 Date: Tue, 2 May 2023 18:48:57 +0530 Subject: [PATCH 0895/1894] issue #1082: Array: Find first duplicate value in Python --- Arrays/find_first_duplicate_value.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Arrays/find_first_duplicate_value.py diff --git a/Arrays/find_first_duplicate_value.py b/Arrays/find_first_duplicate_value.py new file mode 100644 index 00000000..b0232851 --- /dev/null +++ b/Arrays/find_first_duplicate_value.py @@ -0,0 +1,26 @@ +''' +In the code I implemented a solution using Floyd's Tortoise and Hare algorithm +for finding the first integer that appears more than once in an array of integers. + +The first solution has a time complexity of O(n) and a space complexity of O(1). +It uses the fact that the integers in the array are between 1 and n, inclusive, where n is the length of the array. +The solution works by using the array itself as a hash table, +by marking an integer as negative if it is encountered for the first time, +and returning it if it is already marked negative. + +''' + +def find_duplicate(nums): + slow = fast = nums[0] + while True: + slow = nums[slow] + fast = nums[nums[fast]] + if slow == fast: + break + + slow = nums[0] + while slow != fast: + slow = nums[slow] + fast = nums[fast] + + return slow From fc34b5d94e64d196ca7280f76d021519893919e3 Mon Sep 17 00:00:00 2001 From: vandit98 Date: Tue, 2 May 2023 18:57:37 +0530 Subject: [PATCH 0896/1894] adding question --- Arrays/three_largest_numper.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Arrays/three_largest_numper.py b/Arrays/three_largest_numper.py index 17591fcc..b454b367 100644 --- a/Arrays/three_largest_numper.py +++ b/Arrays/three_largest_numper.py @@ -1,4 +1,11 @@ +""" +Write a function that takes in an array of at least three integers and, +without sorting the input array, returns a sorted array of the three largest +integers in the input array. + +""" + class Solution: def three_max_noo(self,arr: List[int])-> List[int]: From 12b1247fbe5717c02e562b7e5ea0963cb2d0f0fe Mon Sep 17 00:00:00 2001 From: vandit98 Date: Tue, 2 May 2023 19:23:02 +0530 Subject: [PATCH 0897/1894] added meaning comment and approach --- Arrays/three_largest_no.py | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Arrays/three_largest_no.py diff --git a/Arrays/three_largest_no.py b/Arrays/three_largest_no.py new file mode 100644 index 00000000..85713111 --- /dev/null +++ b/Arrays/three_largest_no.py @@ -0,0 +1,40 @@ + + +""" +Write a function that takes in an array of at least three integers and, +without sorting the input array, returns a sorted array of the three largest +integers in the input array. + +# Approach + +- We will use three variables to store the three max values and initialize them with int_minimum +- We will iterate through the array and compare the values with the three variables +- If the value is greater than the first variable, we will update the variables +- If the value is greater than the second variable, we will update the variables +- If the value is greater than the third variable, we will update the variables +- Return the three variables as a sorted array + +""" + + + +def three_max_noo(arr:list)-> list: + # give int minvalue to a,b, + max_1,max_2,max_3= -9999,-9999,-9999 + # we will iterate through the array and compare the values + for i in arr: + if i > max_1: + max_1,max_2,max_3 = i, max_1, max_2 + elif i > max_2: + max_2, max_3 = i, max_2 + elif i > max_3: + max_3 = i + # return the three max values as a sorted array + return [max_1, max_2, max_3] + + +# example-1 +arr=[141,1,17,-7,-17,-27,18,541,8,7,7] +print(three_max_noo(arr)) + +# sample output [541, 141, 18] From 473d2c1af71bf9fdd7eff328797f7bc5b1b51828 Mon Sep 17 00:00:00 2001 From: Nkiriobasi Date: Tue, 2 May 2023 14:53:02 +0100 Subject: [PATCH 0898/1894] implemented finding first duplicate in an array --- .../linear_search_first_duplicate_value.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Searching/linear_search_first_duplicate_value.js diff --git a/Searching/linear_search_first_duplicate_value.js b/Searching/linear_search_first_duplicate_value.js new file mode 100644 index 00000000..fa86cc19 --- /dev/null +++ b/Searching/linear_search_first_duplicate_value.js @@ -0,0 +1,33 @@ +// Linear search in an array of integers + + +// Big-O = O(n) time complexity +// Big-O = O(1) space complexity +const firstDuplicate2 = arr => { + for(let i = 0; i < arr.length; i++){ + if(arr.lastIndexOf(arr[i]) !== i){ + return arr[i]; + }; + }; + return "No duplicates found!"; +} + +console.log(firstDuplicate2([2, 1, 5, 2, 3, 3, 4])); + + + + +// Big-O = O(n) time complexity +// Big-O = O(n) space complexity +const firstDuplicate1 = arr => { + let elementSet = new Set(); + + for (let i = 0; i < arr.length; i++) { + if (elementSet.has(arr[i])) return arr[i]; + elementSet.add(arr[i]); + } + return "No duplicates found!"; +} + +console.log(firstDuplicate1([2, 1, 5, 2, 3, 3, 4])); + From 228709cbe72714278534bc2bfbf829625ad41ce2 Mon Sep 17 00:00:00 2001 From: vandit98 Date: Tue, 2 May 2023 19:23:51 +0530 Subject: [PATCH 0899/1894] removed one file --- Arrays/three_largest_numper.py | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 Arrays/three_largest_numper.py diff --git a/Arrays/three_largest_numper.py b/Arrays/three_largest_numper.py deleted file mode 100644 index b454b367..00000000 --- a/Arrays/three_largest_numper.py +++ /dev/null @@ -1,23 +0,0 @@ - -""" -Write a function that takes in an array of at least three integers and, -without sorting the input array, returns a sorted array of the three largest -integers in the input array. - -""" - - -class Solution: - def three_max_noo(self,arr: List[int])-> List[int]: - # give int minvalue to a,b,c - a,b,c= -9999,-9999,-9999 - # we will iterate through the array and compare the values - for i in arr: - if i > a: - a, b, c = i, a, b - elif i > b: - b, c = i, b - elif i > c: - c = i - # return the three max values as a sorted array - return [a, b, c] \ No newline at end of file From 56038bf00c92284ec0952bc5666e1fe244e7cbde Mon Sep 17 00:00:00 2001 From: vandit98 Date: Tue, 2 May 2023 19:24:41 +0530 Subject: [PATCH 0900/1894] minor change --- Arrays/three_largest_no.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Arrays/three_largest_no.py b/Arrays/three_largest_no.py index 85713111..3a66684f 100644 --- a/Arrays/three_largest_no.py +++ b/Arrays/three_largest_no.py @@ -18,7 +18,7 @@ -def three_max_noo(arr:list)-> list: +def three_max_no(arr:list)-> list: # give int minvalue to a,b, max_1,max_2,max_3= -9999,-9999,-9999 # we will iterate through the array and compare the values @@ -35,6 +35,6 @@ def three_max_noo(arr:list)-> list: # example-1 arr=[141,1,17,-7,-17,-27,18,541,8,7,7] -print(three_max_noo(arr)) +print(three_max_no(arr)) # sample output [541, 141, 18] From 9fd50eaa173a7104ce89e7d14590ca37389afdc5 Mon Sep 17 00:00:00 2001 From: vandit98 Date: Tue, 2 May 2023 19:25:55 +0530 Subject: [PATCH 0901/1894] added few more comment --- Arrays/three_largest_no.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Arrays/three_largest_no.py b/Arrays/three_largest_no.py index 3a66684f..46b879d2 100644 --- a/Arrays/three_largest_no.py +++ b/Arrays/three_largest_no.py @@ -24,10 +24,13 @@ def three_max_no(arr:list)-> list: # we will iterate through the array and compare the values for i in arr: if i > max_1: + # if the value is greater than the first variable, we will update the variables max_1,max_2,max_3 = i, max_1, max_2 elif i > max_2: + # if the value is greater than the second variable, we will update the variables max_2, max_3 = i, max_2 elif i > max_3: + # if the value is greater than the third variable, we will update the variables max_3 = i # return the three max values as a sorted array return [max_1, max_2, max_3] From e5e549041f710d7f06c738683b73be67d0a4badf Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Tue, 2 May 2023 19:49:16 +0530 Subject: [PATCH 0902/1894] Math: Count Numbers with Unique Digits in C++ --- Math/countNumbersWithUniqueDigits.cpp | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Math/countNumbersWithUniqueDigits.cpp diff --git a/Math/countNumbersWithUniqueDigits.cpp b/Math/countNumbersWithUniqueDigits.cpp new file mode 100644 index 00000000..44b48027 --- /dev/null +++ b/Math/countNumbersWithUniqueDigits.cpp @@ -0,0 +1,41 @@ +/* + Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n. + + Input: n = 2 + Output: 91 + + Input: n = 0 + Output: 1 + + Constraints: + > 0 <= n <= 8 +*/ + +class Solution { +public: + +/* + By using concepts of permutation and combination, we can count the unique numbers for N digits. + For the first digit we can choose any 1 digit from 1-9 + For the latter digits we can choose any 1 digit from 0-9 except the digits already used + +*/ + int countNumbersWithUniqueDigits(int n) { + int ans=0; + for(int i=0;i Date: Tue, 2 May 2023 20:04:03 +0530 Subject: [PATCH 0903/1894] Math: Shuffle an Array in C++ --- Math/shuffle_an_array.cpp | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Math/shuffle_an_array.cpp diff --git a/Math/shuffle_an_array.cpp b/Math/shuffle_an_array.cpp new file mode 100644 index 00000000..07bc14ac --- /dev/null +++ b/Math/shuffle_an_array.cpp @@ -0,0 +1,60 @@ +/* + Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. + + Implement the Solution class: + Solution(int[] nums) Initializes the object with the integer array nums. + int[] reset() Resets the array to its original configuration and returns it. + int[] shuffle() Returns a random shuffling of the array. + + Input + ["Solution", "shuffle", "reset", "shuffle"] + [[[1, 2, 3]], [], [], []] + Output + [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] + + Constraints: + > 1 <= nums.length <= 50 + > -106 <= nums[i] <= 106 + > All the elements of nums are unique. + > At most 104 calls in total will be made to reset and shuffle. +*/ + +class Solution { +public: + // lets make 2 variables, one to storethe shuffled version of the given array and the other to store the original version + vector shuffled; + vector original; + Solution(vector& nums) { + // Push the elements of given array to required variables as Initialization + for(int i=0;i reset() { + // Return the variable storing the original version of the array + return original; + } + + vector shuffle() { + int N=shuffled.size(); + // shuffle the variable storing the shuffled version of the array randomly + for(int i=0;i param_1 = obj->reset(); + * vector param_2 = obj->shuffle(); + */ \ No newline at end of file From 5a3d43621b27350ae95e0ec4c7f434289b62d0c7 Mon Sep 17 00:00:00 2001 From: SNEHA CHAUHAN Date: Tue, 2 May 2023 20:10:55 +0530 Subject: [PATCH 0904/1894] Implementation of Singly Linked list --- .../implementation_singly_linked_list.cpp | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 Linked List/implementation_singly_linked_list.cpp diff --git a/Linked List/implementation_singly_linked_list.cpp b/Linked List/implementation_singly_linked_list.cpp new file mode 100644 index 00000000..514dbd9c --- /dev/null +++ b/Linked List/implementation_singly_linked_list.cpp @@ -0,0 +1,155 @@ +// Implementation of singly LinkedList +// Program Author : SNEHA CHAUHAN + +/*A class and a Node class can be used individually in C++ to represent a linked list. The class contains two elements, data and a next pointer that links to the next node. */ +/*Three function are implementing in the Linked list class*/ +/*InsertNode: Insetion can be done at the end the linked list*/ +/*DeleteNode: Deletion is done using index of the node*/ +/*PrintNode: Print the Linked list*/ +#include +using namespace std; + +// Class Represent node of the linked list +class Node +{ +public: + int data; + Node *next; + + // Default Constructor + Node() + { + data = 0; + next = NULL; + } + + // // Parameterized Constructor + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +// Linked list class +class Linkedlist +{ + Node *head; + +public: + Linkedlist() + { + head = NULL; + } + + // Function for Instering a node in the Linked list + void insertNode(int data) + { + // Create the new Node. + Node *newNode = new Node(data); + + // Assign to head + if (head == NULL) + { + head = newNode; + return; + } + + // Traverse till end of list + Node *temp = head; + while (temp->next != NULL) + { + // Update temp + temp = temp->next; + } + // Insert at the last. + temp->next = newNode; + } + // Function for Deleting a node in the Linked list at given position + void deleteNode(int index) + { + Node *temp1 = head, *temp2 = NULL; + int ListLen = 0; + + if (head == NULL) + { + cout << "List empty." << endl; + return; + } + + // Find length of the linked-list. + while (temp1 != NULL) + { + temp1 = temp1->next; + ListLen++; + } + + // Check if the position to be + // deleted is greater than the length + // of the linked list. + if (ListLen < index) + { + cout << "Index out of range" + << endl; + return; + } + + // Declare temp1 + temp1 = head; + + // Deleting the head. + if (index == 1) + { + // Update head + head = head->next; + delete temp1; + return; + } + + // Traverse the list to + // find the node to be deleted. + while (index-- > 1) + { + // Update temp2 + temp2 = temp1; + // Update temp1 + temp1 = temp1->next; + } + + // Change the next pointer + // of the previous node. + temp2->next = temp1->next; + + // Delete the node + delete temp1; + } + void printList() + { + Node *temp = head; + + // Check for empty list. + if (head == NULL) + { + cout << "List empty" << endl; + return; + } + + // Traverse the list. + while (temp != NULL) + { + cout << temp->data << " "; + temp = temp->next; + } + } +}; + +int main() +{ + Linkedlist list; + list.insertNode(4); + list.insertNode(2); + list.insertNode(3); + list.insertNode(8); + + list.printList(); +} \ No newline at end of file From b6e4c9a03c29506bbc9e465c5bae810f61ff5d86 Mon Sep 17 00:00:00 2001 From: Thriver <97860789+SuyashSingh01@users.noreply.github.com> Date: Tue, 2 May 2023 21:16:48 +0530 Subject: [PATCH 0905/1894] Rename the file name Math: Find Total Hamming Distance in C++ --- Math/Find_Hamming_dis.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Math/Find_Hamming_dis.cpp diff --git a/Math/Find_Hamming_dis.cpp b/Math/Find_Hamming_dis.cpp new file mode 100644 index 00000000..0c74d808 --- /dev/null +++ b/Math/Find_Hamming_dis.cpp @@ -0,0 +1,30 @@ +#include +#include + +using namespace std; + +class Solution { +public: + int totalHammingDistance(vector& nums) { + int ans = 0; + int n = nums.size(); + for(int i = 0; i < 32; i++) { + int c = 0; + for(int j = 0; j < n; j++) { + if((nums[j] & (1 << i))) { + c++; + } + } + ans += (c * (n - c)); + } + return ans; + } +}; + +int main() { + // Example usage + vector nums = {4, 14, 2}; + Solution s; + int result = s.totalHammingDistance(nums); + return 0; +} From e5f326b38f11bc7d8bc87e609624477358ad689f Mon Sep 17 00:00:00 2001 From: Ujjawal Date: Tue, 2 May 2023 22:18:49 +0530 Subject: [PATCH 0906/1894] =?UTF-8?q?Add=20Two=20Numbers=20in=20Javascript?= =?UTF-8?q?=E2=9C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Linked List/addTwoNumbers.js | 80 ++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Linked List/addTwoNumbers.js diff --git a/Linked List/addTwoNumbers.js b/Linked List/addTwoNumbers.js new file mode 100644 index 00000000..3cd0104c --- /dev/null +++ b/Linked List/addTwoNumbers.js @@ -0,0 +1,80 @@ +// Linked List: Add Two Numbers in Javascript #622 + +/* + + You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + + You may assume the two numbers do not contain any leading zero, except the number 0 itself. + + Example 1: + - Input: l1 = [2,4,3], l2 = [5,6,4] + - Output: [7,0,8] + - Explanation: 342 + 465 = 807. + + Example 2: + - Input: l1 = [0], l2 = [0] + - Output: [0] + + Example 3: + - Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] + - Output: [8,9,9,9,0,0,0,1] + + Constraints: + - The number of nodes in each linked list is in the range [1, 100]. + - 0 <= Node.val <= 9 + - It is guaranteed that the list represents a number that does not have leading zeros. + +*/ + +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ + +var addTwoNumbers = function (l1, l2) { + const head = new ListNode(); // creating a new LL. + let temp = head; // assign head into temp to traverse the LL. + let carry = 0; // to store carry that we will get during the add operation. + + while (l1 || l2) { + // loop will get executed until one of the LL becomes null. + let sum = carry; + + //perform summation with both LL one by one and assign it to the sum variable. + if (l1) { + sum += l1.val; + l1 = l1.next; + } + + if (l2) { + sum += l2.val; + l2 = l2.next; + } + + // to store the carry part we will do sum/10 and store it's floor value to carry variable. For Example: + /* + if sum = 12 + so, sum/10 = 1.2 + and Math.floor(1.2) = 1 and we get our carry part. + > carry = 1. + */ + carry = Math.floor(sum / 10); + temp.next = new ListNode(sum % 10); // at this point we are removing carry part from sum and adding remaining part into the ll. + temp = temp.next; + } + + if (carry > 0) { + // after the completion of summation, if there is any cary left it will be added to list. + temp.next = new ListNode(carry); + } + + return head.next; // return the head of the node so ll can be traverse. +}; From fd92f4321d744f103dfa8d308263df13fd8c325e Mon Sep 17 00:00:00 2001 From: Hades62442 <83868670+Hades62442@users.noreply.github.com> Date: Tue, 2 May 2023 18:12:56 +0100 Subject: [PATCH 0907/1894] create roman to integer in python --- Hash Table/roman_to_integer.py | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Hash Table/roman_to_integer.py diff --git a/Hash Table/roman_to_integer.py b/Hash Table/roman_to_integer.py new file mode 100644 index 00000000..58e4e88e --- /dev/null +++ b/Hash Table/roman_to_integer.py @@ -0,0 +1,42 @@ +# Roman to Integer +''' + The function takes a string s as an input and returns the corresponding integer value + by converting the string from Roman numerals to its integer value. + + It does this by iterating through the string. If the current character has a lower + value than the character after it, the current character value is subtracted from + the total, so that it is added correctly. + + Otherwise, the current character value is added to the total. + + Finally, the total integer value is returned. +''' + +def roman_to_int(s: str) -> int: + # define mapping of values to symbols + symbols = { + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000 + } + + # initialise integer to return total value + total = 0 + + # iterate through characters + for i in range(len(s) - 1): + # if the symbol after current symbol is less than it, + # subtract it from the total value + if symbols[s[i]] < symbols[s[i+1]]: + total -= symbols[s[i]] + # else, just add the corresponding value + else: + total += symbols[s[i]] + # add the last value + total += symbols[s[-1]] + + return total \ No newline at end of file From 80f94e18823ef871a8ab005794b185841bf32548 Mon Sep 17 00:00:00 2001 From: Faizan Siddiqui Date: Wed, 3 May 2023 00:47:43 +0530 Subject: [PATCH 0908/1894] Added cpp code for sign of the product of array --- Arrays/sign_of_the_product_of_an_array.cpp | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Arrays/sign_of_the_product_of_an_array.cpp diff --git a/Arrays/sign_of_the_product_of_an_array.cpp b/Arrays/sign_of_the_product_of_an_array.cpp new file mode 100644 index 00000000..7aca6f15 --- /dev/null +++ b/Arrays/sign_of_the_product_of_an_array.cpp @@ -0,0 +1,99 @@ +// Leetcode 1822 : Sign of the Product of an Array +/* +QUESTION +There is a function signFunc(x) that returns: + +1 if x is positive. +-1 if x is negative. +0 if x is equal to 0. +You are given an integer array nums. Let product be the product of all values in the array nums. +Return signFunc(product). +Example 1: + +Input: nums = [-1,-2,-3,-4,3,2,1] +Output: 1 +Explanation: The product of all values in the array is 144, and signFunc(144) = 1 +Example 2: + +Input: nums = [1,5,0,2,-3] +Output: 0 +Explanation: The product of all values in the array is 0, and signFunc(0) = 0 +Example 3: + +Input: nums = [-1,1,-1,1,-1] +Output: -1 +Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 + +Constraints: +1 <= nums.length <= 1000 +-100 <= nums[i] <= 100 + +CODE EXPLANATION WITH DRY RUN + +Suppose we have the following input vector: +{-1, -2, -3, -4, 3, 2, 1} +We want to find the sign of the product of all elements in the vector. + +Here's how the code will execute: + +1-We define the input vector nums in the main function. +2-We call the arraySign function with nums as the argument. +3-The arraySign function initializes the sign variable to 1. +4-The function iterates over each element of the nums vector using a range-based for loop. +5-On the first iteration, num is -1. The element is negative, so the sign variable is multiplied by -1, changing its value to -1. +6-On the second iteration, num is -2. The element is negative, so the sign variable is multiplied by -1 again, changing its value to 1. +7-On the third iteration, num is -3. The element is negative, so the sign variable is multiplied by -1, changing its value to -1. +8-On the fourth iteration, num is -4. The element is negative, so the sign variable is multiplied by -1 again, changing its value to 1. +9-On the fifth iteration, num is 3. The element is positive, so the sign variable is not changed and remains 1. +10-On the sixth iteration, num is 2. The element is positive, so the sign variable is not changed and remains 1. +11-On the seventh iteration, num is 1. The element is positive, so the sign variable is not changed and remains 1. +12-The arraySign function returns sign, which has a value of 1. +13-In the main function, we check if sign is equal to 1. It is, so we print "Product is Positive" to the console. +Therefore, the output of the program will be: +"Product is Positive" +*/ +#include +#include +using namespace std; + +// Function to find the sign of the product of all elements in the input vector +int arraySign(vector &nums) +{ + int ans = 1; // Initialize answer to 1 + // Iterate over each element of the vector + for (int i = 0; i < nums.size(); i++) + { + // If element is negative, change answer to -1 + if (nums[i] < 0) + { + ans *= -1; + } + // If element is zero, answer is 0 and loop is exited + else if (nums[i] == 0) + { + ans = 0; + break; + } + } + return ans; // Return answer +} + +int main() +{ + // Example usage + vector nums = {-1, -2, -3, -4, 3, 2, 1}; + int ans = arraySign(nums); // Print the sign of the product of the vector + if (ans == 1) + { + cout << "Product is Positive"; + } + else if (ans == -1) + { + cout << "Product is Negative"; + } + else + { + cout << "Product is Zero"; + } + return 0; +} \ No newline at end of file From 234549f1a93497a25fac7ad634455d395d496b67 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 3 May 2023 07:46:41 +0530 Subject: [PATCH 0909/1894] update contributing.md --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 67f75882..e85e9f41 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,6 +17,7 @@ Contributions are always welcome! - Add question on top of file - Add sample input and output - Explain approach with comments +- Add Time and Space complexity - Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) - Send a Pull Request (PR) against main branch From 2afe55fd86688be2407498bd65613d32c2f10a61 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Wed, 3 May 2023 10:16:43 +0530 Subject: [PATCH 0910/1894] Math: Find K Closest Points to Origin in C++ --- Math/k_closest_points_to_origin.cpp | 45 +++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Math/k_closest_points_to_origin.cpp diff --git a/Math/k_closest_points_to_origin.cpp b/Math/k_closest_points_to_origin.cpp new file mode 100644 index 00000000..3c790b39 --- /dev/null +++ b/Math/k_closest_points_to_origin.cpp @@ -0,0 +1,45 @@ +/* + Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + + Input: points = [[1,3],[-2,2]], k = 1 + Output: [[-2,2]] + + Input: points = [[3,3],[5,-1],[-2,4]], k = 2 + Output: [[3,3],[-2,4]] + + Constraints: + > 1 <= k <= points.length <= 104 + > -104 < xi, yi < 104 + +*/ +class Solution { +public: + vector> kClosest(vector>& points, int k) { + // Lets define some variables we will be needing + vector> ans; + vector> sorted; + + // For each point in the list points lets store distance_from_origin and point index as a pair + for(int i=0;i Date: Wed, 3 May 2023 10:47:50 +0530 Subject: [PATCH 0911/1894] Add Find Maximum in Sliding Window in Go Solution --- Sliding Window/find_max.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Sliding Window/find_max.go diff --git a/Sliding Window/find_max.go b/Sliding Window/find_max.go new file mode 100644 index 00000000..0880d623 --- /dev/null +++ b/Sliding Window/find_max.go @@ -0,0 +1,33 @@ +package main +import "fmt" + +func printKMax(arr []int, N int, K int) { + + var j, max int + + for i := 0; i <= N-K; i++ { + max = arr[i] + + for j = 1; j < K; j++ { + if arr[i+j] > max { + max = arr[i+j] + } + } + fmt.Printf("%d ", max) + } +} + +func main() { + + var N, K int + fmt.Scan(&N) + + arr := make([]int, N) + for i := 0; i < N; i++ { + fmt.Scan(&arr[i]) + } + + fmt.Scan(&K) + + printKMax(arr, N, K) +} From 17685bf5afb0cd62f27ffc42a67742a0192b8e66 Mon Sep 17 00:00:00 2001 From: Harsit-Agarwalla Date: Wed, 3 May 2023 11:09:35 +0530 Subject: [PATCH 0912/1894] Update Find maximum in Sliding Window solution --- Sliding Window/find_max.go | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/Sliding Window/find_max.go b/Sliding Window/find_max.go index 0880d623..d2ba9983 100644 --- a/Sliding Window/find_max.go +++ b/Sliding Window/find_max.go @@ -1,3 +1,23 @@ +// Statement: + +//// Given an array and an integer K, find the maximum for each and every contiguous subarray of size K. + +// Example: + +//// Input: N = 5 arr[] = {5, 4, 1, 7, 3}, K = 2 +//// Output: 5 4 7 7 +//// Explanation: Maximum of 5, 4 is 5 +//// Maximum of 4, 1 is 4 +//// Maximum of 1, 7 is 7 +//// Maximum of 7, 3 is 7 + +// Complexity: + +//// Time Complexity: O(N*K) +//// Space Complexity: O(1) + +// Code: + package main import "fmt" @@ -5,10 +25,11 @@ func printKMax(arr []int, N int, K int) { var j, max int + // Finding the maximum elemnt in each window for i := 0; i <= N-K; i++ { max = arr[i] - for j = 1; j < K; j++ { + for j = 1; j < K; j++ { if arr[i+j] > max { max = arr[i+j] } @@ -19,15 +40,15 @@ func printKMax(arr []int, N int, K int) { func main() { - var N, K int - fmt.Scan(&N) + var N, K int // Variable declaration + fmt.Scan(&N) // Initialise length of array - arr := make([]int, N) - for i := 0; i < N; i++ { + arr := make([]int, N) // Array Declaration + for i := 0; i < N; i++ { // Array Initialisation fmt.Scan(&arr[i]) } - fmt.Scan(&K) + fmt.Scan(&K) // Window length initialisation - printKMax(arr, N, K) + printKMax(arr, N, K) // Function call to print maximum element in the window } From 90e821d221ec2c008ed0b6ccafe70d45744d59e1 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Wed, 3 May 2023 11:26:24 +0530 Subject: [PATCH 0913/1894] Implemented_Singly_linked_list_in_Python --- Linked List/Singly_linked_list_in_Python.py | 43 +++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Linked List/Singly_linked_list_in_Python.py diff --git a/Linked List/Singly_linked_list_in_Python.py b/Linked List/Singly_linked_list_in_Python.py new file mode 100644 index 00000000..1344f871 --- /dev/null +++ b/Linked List/Singly_linked_list_in_Python.py @@ -0,0 +1,43 @@ + +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + + def append(self, data): + new_node = Node(data) + if not self.head: + self.head = new_node + return + curr_node = self.head + while curr_node.next: + curr_node = curr_node.next + curr_node.next = new_node + + def prepend(self, data): + new_node = Node(data) + new_node.next = self.head + self.head = new_node + + def delete_node(self, data): + if not self.head: + return + if self.head.data == data: + self.head = self.head.next + return + curr_node = self.head + while curr_node.next: + if curr_node.next.data == data: + curr_node.next = curr_node.next.next + return + curr_node = curr_node.next + + def print_list(self): + curr_node = self.head + while curr_node: + print(curr_node.data) + curr_node = curr_node.next From 604a1d9e08bfbd4bb4e1edab95310d8aa8dfae24 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Wed, 3 May 2023 12:14:34 +0530 Subject: [PATCH 0914/1894] Implemented singly linked list in python --- Linked List/Singly_linked_list_in_Python.py | 28 ++++++++++++--------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Linked List/Singly_linked_list_in_Python.py b/Linked List/Singly_linked_list_in_Python.py index 1344f871..b2326ee9 100644 --- a/Linked List/Singly_linked_list_in_Python.py +++ b/Linked List/Singly_linked_list_in_Python.py @@ -1,43 +1,47 @@ +''' +This is an implementation of a singly linked list in Python with a Node class and a LinkedList class. The Node class represents each element of the linked list and the LinkedList class has methods to manipulate the list, including append, prepend, delete_node, and print_list. +''' class Node: def __init__(self, data): self.data = data - self.next = None + self.next = None # The next node in the list class LinkedList: def __init__(self): - self.head = None + self.head = None # The first node in the list def append(self, data): new_node = Node(data) - if not self.head: + if not self.head: # If the list is empty, set the new node as the head self.head = new_node return curr_node = self.head - while curr_node.next: + while curr_node.next: # Traverse to the last node in the list curr_node = curr_node.next - curr_node.next = new_node + curr_node.next = new_node # Set the next node of the last node to the new node def prepend(self, data): new_node = Node(data) - new_node.next = self.head - self.head = new_node + new_node.next = self.head # Set the next node of the new node to the current head + self.head = new_node # Set the new node as the new head def delete_node(self, data): - if not self.head: + if not self.head: # If the list is empty, do nothing return - if self.head.data == data: + if self.head.data == data: # If the head is the node to delete, set the next node as the new head self.head = self.head.next return curr_node = self.head - while curr_node.next: - if curr_node.next.data == data: + while curr_node.next: # Traverse the list until the last node + if curr_node.next.data == data: # If the next node is the node to delete, set the next node of the current node to the node after the next node curr_node.next = curr_node.next.next return curr_node = curr_node.next def print_list(self): curr_node = self.head - while curr_node: + while curr_node: # Traverse the list and print each node's data print(curr_node.data) curr_node = curr_node.next + From 99e438e877b90119c0851d5aa5fb570595409475 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Wed, 3 May 2023 12:38:53 +0530 Subject: [PATCH 0915/1894] Array: Find Squares of a Sorted Array in C++ --- Arrays/squares_of_a_sorted_array.cpp | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Arrays/squares_of_a_sorted_array.cpp diff --git a/Arrays/squares_of_a_sorted_array.cpp b/Arrays/squares_of_a_sorted_array.cpp new file mode 100644 index 00000000..aed496b0 --- /dev/null +++ b/Arrays/squares_of_a_sorted_array.cpp @@ -0,0 +1,46 @@ +/* + Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. + + Input: nums = [-4,-1,0,3,10] + Output: [0,1,9,16,100] + + Input: nums = [-7,-3,2,3,11] + Output: [4,9,9,49,121] + + Constraints: + > 1 <= nums.length <= 104 + > -104 <= nums[i] <= 104 + > nums is sorted in non-decreasing order. +*/ + +class Solution { +public: + int N=10001; + vector sortedSquares(vector& nums) { + // Initialize variables + vector trk(N,0); + + // Store the frquency of the absolute of each number from the list + for(int i=0;i0) + { + int square=i*i; + while(trk[i]) + { + ans.push_back(square); + trk[i]--; + } + } + } + + // Return the final ans + return ans; + } +}; \ No newline at end of file From 62e1c9bbeed259f5bff2ce896dfe626b5ec2a61d Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Wed, 3 May 2023 12:39:58 +0530 Subject: [PATCH 0916/1894] Added Requested Changes to Math: Shuffle an Array in C++ --- Math/shuffle_an_array.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Math/shuffle_an_array.cpp b/Math/shuffle_an_array.cpp index 07bc14ac..413408af 100644 --- a/Math/shuffle_an_array.cpp +++ b/Math/shuffle_an_array.cpp @@ -19,9 +19,19 @@ > At most 104 calls in total will be made to reset and shuffle. */ +/* + APPROACH + + 1. Use two lists to store the original nums array. + 2. We can keep one array as it is and return it whenever the reset() function is called. + 3. We use the second list to shuffle the permutation of elements and return a shuffled array when shuffle() function is called. + 4. For shuffling, choose 2 indices on random basis from the array and swap them. Repeat for n times. (n=size of the array) + +*/ +// O(N) Time-Complexity and O(N) Space-Complexity Solution class Solution { public: - // lets make 2 variables, one to storethe shuffled version of the given array and the other to store the original version + // lets make 2 variables, one to store the shuffled version of the given array and the other to store the original version vector shuffled; vector original; Solution(vector& nums) { From e59113c98126ebec5479de266bcd05bdda799f35 Mon Sep 17 00:00:00 2001 From: Thriver <97860789+SuyashSingh01@users.noreply.github.com> Date: Wed, 3 May 2023 14:17:26 +0530 Subject: [PATCH 0917/1894] Update Find_Hamming_dis.cpp --- Math/Find_Hamming_dis.cpp | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/Math/Find_Hamming_dis.cpp b/Math/Find_Hamming_dis.cpp index 0c74d808..59e2e943 100644 --- a/Math/Find_Hamming_dis.cpp +++ b/Math/Find_Hamming_dis.cpp @@ -1,5 +1,26 @@ -#include +/* +Example: +Input: nums = [4,14,2] +Output: 6 + +Explanation: +In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just +showing the four bits relevant in this case). +The answer will be: +HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + +Detailed Explanation: +The totalHammingDistance function takes a reference to a vector of integers nums, and returns the total Hamming distance between all possible pairs of elements in the vector. + +In the function, we initialize the answer ans to 0, and the size of the vector n is obtained using the size() method of the vector. We then loop through all 32 bits (since we are dealing with 32-bit integers), and for each bit position i, we count the number of elements in nums with the i-th bit set by looping through all elements and checking if the bit is set using bitwise AND operator &. + +The count c is then multiplied by (n-c), which gives the number of pairs with different bits at the i-th position. This count is added to the answer ans. Finally, the function returns the total Hamming distance. +The main function is just an example usage, where we create a vector nums and call the totalHammingDistance method of a Solution object to get the total Hamming distance between all possible pairs of elements in nums. +*/ +// code: + #include +#include using namespace std; @@ -28,3 +49,4 @@ int main() { int result = s.totalHammingDistance(nums); return 0; } + From 12de90c9c42d70c1ef35dfa145c29ddd42fa5aab Mon Sep 17 00:00:00 2001 From: Nkiriobasi Date: Wed, 3 May 2023 09:51:10 +0100 Subject: [PATCH 0918/1894] explain my solution with brief description about the problem and detailed line by line comments about how the code is working --- .../linear_search_first_duplicate_value.js | 51 ++++++++++++++----- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/Searching/linear_search_first_duplicate_value.js b/Searching/linear_search_first_duplicate_value.js index fa86cc19..7a76df3a 100644 --- a/Searching/linear_search_first_duplicate_value.js +++ b/Searching/linear_search_first_duplicate_value.js @@ -1,33 +1,60 @@ -// Linear search in an array of integers +/* PROBLEM STATEMENT */ +/* Given an array of integers between 1 and n, inclusive, where n is the length of the array, + write a function that returns the first integer that appears more than once (when the array + is read from left to right). +*/ -// Big-O = O(n) time complexity -// Big-O = O(1) space complexity -const firstDuplicate2 = arr => { + + +/* The difference between the two solutions provided is that the first solution has a space complexity + of 0(1), meaning constant space complexity, while the second solution has a space complexity of 0(n), + meaning linear space complexity. finally both solutions has a time complexity of 0(n), meaning linear + time complexity. +*/ + + + +// Big-O = O(n) time complexity +// Big-O = O(1) space complexity +const firstDuplicate1 = arr => { + + // firstly iterate/loop through the given array for(let i = 0; i < arr.length; i++){ - if(arr.lastIndexOf(arr[i]) !== i){ - return arr[i]; - }; + // then use the Array.prototype.lastIndexOf() method to check for duplicates. + // finally return the first number that appers more than once. + if(arr.lastIndexOf(arr[i]) !== i) return arr[i]; }; - return "No duplicates found!"; + + // return the message No duplicate found, if no dupliacte is found after the iteration process. + return "No duplicate found!"; } -console.log(firstDuplicate2([2, 1, 5, 2, 3, 3, 4])); +console.log(firstDuplicate1([2, 1, 5, 2, 3, 3, 4])); // Big-O = O(n) time complexity // Big-O = O(n) space complexity -const firstDuplicate1 = arr => { - let elementSet = new Set(); +const firstDuplicate2 = arr => { + // first off, let's create our Set object + // this Set object will allow us to store each element from the given array as a unique value + let elementSet = new Set(); + + // then iterate/loop through the given array for (let i = 0; i < arr.length; i++) { + // we'll check to see if the Set already contains the element that we're currently on in our loop + // if it exists, then we've found our first duplicate! We'll return that value and be done if (elementSet.has(arr[i])) return arr[i]; + // if the element isn't in our Set yet, then we add it to the Set and move on to the next element in the array. elementSet.add(arr[i]); } + + // return the message No duplicate found, if no dupliacte is found after the iteration process. return "No duplicates found!"; } -console.log(firstDuplicate1([2, 1, 5, 2, 3, 3, 4])); +console.log(firstDuplicate2([2, 1, 5, 2, 3, 3, 4])); From 00eb767b34352ab306b2fbb2e11545e5b0a3fd66 Mon Sep 17 00:00:00 2001 From: Kumari Ranjana Yadav Date: Wed, 3 May 2023 14:23:02 +0530 Subject: [PATCH 0919/1894] Two Pointers: Add Dutch national flag problem in C++ #319 SOLVED --- Arrays/Dutch-national-flag.cpp | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Arrays/Dutch-national-flag.cpp diff --git a/Arrays/Dutch-national-flag.cpp b/Arrays/Dutch-national-flag.cpp new file mode 100644 index 00000000..a3a1cec2 --- /dev/null +++ b/Arrays/Dutch-national-flag.cpp @@ -0,0 +1,47 @@ + +// Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + +// We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + +// Input: nums = [2,0,2,1,1,0] +// Output: [0,0,1,1,2,2] + + + +#include +using namespace std; + +void sortColors(vector &nums) +{ + // created 3 variables start , low and end which are pointing start and low which are pointing to first index , end is pointing to last index . + + int start = 0, low = 0, end = nums.size() - 1; + while (low <= end) + { + if (nums[low] == 0) // checking if element of low is 0 . If yes then swap to start and low . + { + swap(nums[low], nums[start]); + start++, low++; + } + else if (nums[low] == 1) // checking if element at low index is 1 , If yes then increase the index by 1 . + { + low++; + } + else // else swap the element of low index to end . + { + swap(nums[low], nums[end]); + end--; + } + } +} +int main() +{ + vector nums{2, 0, 2, 1, 1, 0}; + sortColors(nums); + + // Printing array's elements .. + for (auto i : nums) + { + cout << i << " "; + } +} From 41bef7500824855907b681c497fd38f6ef1003ad Mon Sep 17 00:00:00 2001 From: Kumari Ranjana Yadav Date: Wed, 3 May 2023 17:41:23 +0530 Subject: [PATCH 0920/1894] Two Pointers: Add Dutch national flag problem added time and space complexity --- Arrays/Dutch-national-flag.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Arrays/Dutch-national-flag.cpp b/Arrays/Dutch-national-flag.cpp index a3a1cec2..fe4d1a00 100644 --- a/Arrays/Dutch-national-flag.cpp +++ b/Arrays/Dutch-national-flag.cpp @@ -6,6 +6,12 @@ // Input: nums = [2,0,2,1,1,0] // Output: [0,0,1,1,2,2] +// Time and space complexity of the solution + +// Time complexity: O(n) +// Space complexity: O(1) + + #include From d65a600ea39bb027daa00cbeed658bfa23b6cc2d Mon Sep 17 00:00:00 2001 From: Kumari Ranjana Yadav Date: Wed, 3 May 2023 18:36:52 +0530 Subject: [PATCH 0921/1894] Linked List: Find Middle of the Linked List in C++ #360 SOLVED --- Linked List/middleOfTheLinkedList.cpp | 75 +++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Linked List/middleOfTheLinkedList.cpp diff --git a/Linked List/middleOfTheLinkedList.cpp b/Linked List/middleOfTheLinkedList.cpp new file mode 100644 index 00000000..e1c3c71d --- /dev/null +++ b/Linked List/middleOfTheLinkedList.cpp @@ -0,0 +1,75 @@ +// Given the head of a singly linked list, return the middle node of the linked list. +// If there are two middle nodes, return the second middle node. + +// Input: head = [1,2,3,4,5] +// Output: [3,4,5] +// Explanation: The middle node of the list is node 3. + +// TIME ANS SPACE COMPLEXITY OF THE SOLUTION IS :: +// Time complexity: O(n) +// Space complexity: O(1) + +#include +using namespace std; + +// creating Node manualy +class Node +{ +public: + int data; + Node *next; + + Node() + { + this->data = 0; + this->next = NULL; + } + Node(int data) + { + this->data = data; + this->next = NULL; + } +}; + +Node *middleNode(Node *head) +{ + + Node *slow = head; + Node *fast = head; + + // Move slow pointer by one node at a time and fast pointer two nodes at a time. + // While fast pointer reaches the end, slow pointer must have reached the middle node. + + while (fast != NULL) + { + fast = fast->next; + if (fast != NULL) + { + fast = fast->next; + slow = slow->next; + } + } + return slow; // return slow as ans +} + +int main() +{ + // creating nodes. + Node *first = new Node(1); + Node *second = new Node(2); + Node *third = new Node(3); + Node *fourth = new Node(4); + Node *fifth = new Node(5); + + // head of linked list + Node *head = first; + + // Creating connection of nodes + first->next = second; + second->next = third; + third->next = fourth; + fourth->next = fifth; + + cout << "The middle node of the list is node " << middleNode(head)->data << endl; + return 0; +} \ No newline at end of file From b947509443f43a3b9eacb4a16ef4b8755f1af3c4 Mon Sep 17 00:00:00 2001 From: Subham5401 Date: Wed, 3 May 2023 18:44:42 +0530 Subject: [PATCH 0922/1894] issue #1080: Find first duplicate value in Java --- Arrays/find_first_duplicate_value.java | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Arrays/find_first_duplicate_value.java diff --git a/Arrays/find_first_duplicate_value.java b/Arrays/find_first_duplicate_value.java new file mode 100644 index 00000000..f371d094 --- /dev/null +++ b/Arrays/find_first_duplicate_value.java @@ -0,0 +1,53 @@ +/* Sure, here's a brief explanation of each solution: + +Solution 1 (O(n) time, O(1) space): +This solution uses Floyd's Tortoise and Hare algorithm to find the first duplicate value in the array. +It initializes two pointers, a slow pointer and a fast pointer, to the first value in the array. +The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. +When they meet at a certain point, it indicates that there is a cycle in the array. +Then, the slow pointer is reset to the first value, and both pointers move one step at a time until they meet again, +which is the start of the cycle (i.e., the first duplicate value in the array). + +Solution 2 (O(n) time, O(n) space): +This solution uses a HashSet to keep track of the integers that have been seen so far in the array. +As the array is iterated over, each integer is checked to see if it is already in the set. +If it is, then it is returned as the first integer that appears more than once. +If no such integer is found, then -1 is returned. This solution has a time complexity of O(n) and a space complexity of O(n). */ + +// Solution 1: O(n) time and O(1) space +public static int findDuplicate(int[] nums) { + // iterate through the array + for (int i = 0; i < nums.length; i++) { + // calculate the absolute value of the current element + int val = Math.abs(nums[i]); + // check if the value at the calculated index is negative + if (nums[val - 1] < 0) { + // if it is, return the absolute value of the current element + return val; + } + // otherwise, negate the value at the calculated index + nums[val - 1] = -nums[val - 1]; + } + // if no duplicate is found, return -1 + return -1; +} + + +// Solution 2: O(n) time and O(n) space solution: +public static int findDuplicate(int[] nums) { + // create a set to keep track of visited elements + Set visited = new HashSet<>(); + // iterate through the array + for (int num : nums) { + // check if the current element has already been visited + if (visited.contains(num)) { + // if it has, return the current element + return num; + } + // otherwise, add it to the set of visited elements + visited.add(num); + } + // if no duplicate is found, return -1 + return -1; +} + From 240ed7eb7d544e37fd2512a76998bbedc7b681c9 Mon Sep 17 00:00:00 2001 From: Sagar Date: Wed, 3 May 2023 22:47:29 +0530 Subject: [PATCH 0923/1894] Solved add two numbers leetcode problem --- Linked List/addTwoNumbers.cpp | 182 ++++++++++++++++++++++++---------- 1 file changed, 130 insertions(+), 52 deletions(-) diff --git a/Linked List/addTwoNumbers.cpp b/Linked List/addTwoNumbers.cpp index 67d3dc6e..03e5ff33 100644 --- a/Linked List/addTwoNumbers.cpp +++ b/Linked List/addTwoNumbers.cpp @@ -1,25 +1,3 @@ -/* - You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. - - You may assume the two numbers do not contain any leading zero, except the number 0 itself. - - Input: l1 = [2,4,3], l2 = [5,6,4] - Output: [7,0,8] - - Input: l1 = [0], l2 = [0] - Output: [0] - - Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] - Output: [8,9,9,9,0,0,0,1] - - Constraints: - - > The number of nodes in each linked list is in the range [1, 100]. - > 0 <= Node.val <= 9 - > It is guaranteed that the list represents a number that does not have leading zeros. - -*/ - /** * Definition for singly-linked list. * struct ListNode { @@ -30,45 +8,145 @@ * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ -class Solution { +class Solution +{ public: - ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) + { + ListNode *ansHead = new ListNode((l1->val + l2->val) % 10); + ListNode *ans = ansHead; + int carry = (l1->val + l2->val) / 10; + l1 = l1->next; + l2 = l2->next; + while (l1 != NULL && l2 != NULL) + { + ListNode *temp = new ListNode((l1->val + l2->val + carry) % 10); + carry = (l1->val + l2->val + carry) / 10; + l1 = l1->next; + l2 = l2->next; + ans->next = temp; + ans = temp; + } + while (l1 != NULL) + { + ListNode *temp = new ListNode((l1->val + carry) % 10); + carry = (l1->val + carry) / 10; + l1 = l1->next; + ans->next = temp; + ans = temp; + } + while (l2 != NULL) + { + ListNode *temp = new ListNode((l2->val + carry) % 10); + carry = (l2->val + carry) / 10; + l2 = l2->next; + ans->next = temp; + ans = temp; + } + if (carry > 0) + { + ListNode *temp = new ListNode(carry); + ans->next = temp; + ans = temp; + } + return ansHead; + } + ListNode *solve(ListNode *&head1, ListNode *&head2) + { + if (head1 == NULL) + { + return head2; + } + if (head2 == NULL) + { + return head1; + } + + // linked list which contains the final answer + ListNode *ansHead = NULL; + ListNode *ansTail = NULL; - ListNode* ansHead=new ListNode((l1->val+l2->val)%10); - ListNode* ans=ansHead; - int carry=(l1->val+l2->val)/10; - l1=l1->next; - l2=l2->next; - while(l1!=NULL && l2!=NULL) + int carry = 0; + while (head1 != NULL && head2 != NULL) { - ListNode* temp= new ListNode((l1->val + l2->val + carry)%10); - carry = (l1->val + l2->val + carry)/10; - l1=l1->next; - l2=l2->next; - ans->next=temp; - ans=temp; + int sum = head1->val + head2->val + carry; + int digit = sum % 10; + carry = sum / 10; + + ListNode *newNode = new ListNode(digit); + if (ansHead == NULL) + { + ansHead = newNode; + ansTail = newNode; + } + else + { + ansTail->next = newNode; + ansTail = newNode; + } + head1 = head1->next; + head2 = head2->next; } - while(l1!=NULL) + + // head1 linked list pending to be solved + while (head1 != NULL) { - ListNode* temp= new ListNode((l1->val + carry)%10); - carry = (l1->val + carry)/10; - l1=l1->next; - ans->next=temp; - ans=temp; + int sum = carry + head1->val; + int digit = sum % 10; + carry = sum / 10; + + ListNode *newNode = new ListNode(digit); + if (ansHead == NULL) + { + ansHead = newNode; + ansTail = newNode; + } + else + { + ansTail->next = newNode; + ansTail = newNode; + } + head1 = head1->next; } - while(l2!=NULL) + + // head2 linked list pending to be solved + while (head2 != NULL) { - ListNode* temp= new ListNode((l2->val + carry)%10); - carry = (l2->val + carry)/10; - l2=l2->next; - ans->next=temp; - ans=temp; + int sum = carry + head2->val; + int digit = sum % 10; + carry = sum / 10; + + ListNode *newNode = new ListNode(digit); + if (ansHead == NULL) + { + ansHead = newNode; + ansTail = newNode; + } + else + { + ansTail->next = newNode; + ansTail = newNode; + } + head2 = head2->next; } - if (carry>0) + + while (carry != 0) { - ListNode* temp= new ListNode(carry); - ans->next=temp; - ans=temp; + int sum = carry; + int digit = sum % 10; + carry = sum / 10; + + ListNode *newNode = new ListNode(digit); + if (ansHead == NULL) + { + ansHead = newNode; + ansTail = newNode; + } + else + { + ansTail->next = newNode; + ansTail = newNode; + } } return ansHead; } From 7d05318fb01aecb5e7f7b359b1d329f96668bbb0 Mon Sep 17 00:00:00 2001 From: Sagar Date: Wed, 3 May 2023 23:00:34 +0530 Subject: [PATCH 0924/1894] Added Reverse Linked list code --- Linked List/addTwoNumbers.cpp | 2 +- Linked List/reverse_linked_list.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 Linked List/reverse_linked_list.cpp diff --git a/Linked List/addTwoNumbers.cpp b/Linked List/addTwoNumbers.cpp index 03e5ff33..a378b5b8 100644 --- a/Linked List/addTwoNumbers.cpp +++ b/Linked List/addTwoNumbers.cpp @@ -6,7 +6,7 @@ * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; + * }; */ class Solution { diff --git a/Linked List/reverse_linked_list.cpp b/Linked List/reverse_linked_list.cpp new file mode 100644 index 00000000..e78e50e7 --- /dev/null +++ b/Linked List/reverse_linked_list.cpp @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev=null; + ListNode curr=head; + while(curr!=null){ + ListNode right=curr.next; + curr.next=prev; + prev=curr; + curr=right; + } + head=prev; + return head; + } +} \ No newline at end of file From f4cd969675484d9446295ee4d1f078b7b29f6b92 Mon Sep 17 00:00:00 2001 From: Sagar Date: Wed, 3 May 2023 23:05:46 +0530 Subject: [PATCH 0925/1894] Added reverse linked list code in java --- Linked List/{reverse_linked_list.cpp => reverse_linked_list.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Linked List/{reverse_linked_list.cpp => reverse_linked_list.java} (100%) diff --git a/Linked List/reverse_linked_list.cpp b/Linked List/reverse_linked_list.java similarity index 100% rename from Linked List/reverse_linked_list.cpp rename to Linked List/reverse_linked_list.java From c576abbe79065018d63f8c9986394c0046e1a543 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Thu, 4 May 2023 00:20:15 +0530 Subject: [PATCH 0926/1894] Sorting: Implement Bucket sort in C++ #580 --- sorting/bucket_sort_implementation.cpp | 78 ++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 sorting/bucket_sort_implementation.cpp diff --git a/sorting/bucket_sort_implementation.cpp b/sorting/bucket_sort_implementation.cpp new file mode 100644 index 00000000..725e7554 --- /dev/null +++ b/sorting/bucket_sort_implementation.cpp @@ -0,0 +1,78 @@ +/* + Bucket-Sort can be used to sort a set of uniformly distributed floating point numbers. + Input: [0.872, 0.435, 0.516, 0.1004, 0.1065, 0.3464] + Output: [0.1004, 0.1065, 0.3464, 0.435, 0.516, 0.872] + + Input: [9.81, 9.6, 1.1, 1.9, 5.07,5.04, 3.0, 11.11, 0.18, 6.78] + Output: [0.18, 1.1, 1.9, 3, 5.04, 5.07, 6.78, 9.6, 9.81, 11.11 ] + + + APPROACH + 1. Create N buckets. + 2. Calculate the range of floating points using the formula: + RANGE = (MAX_ELEMENT - MIN_ELEMENT)/ N + 3. Calculate bucket index for current element using the following formula: + BUCKET_INDX = (CURR_ELEMENT - MIN_ELEMENT)/RANGE + 4. If BUCKET_INDX is an integer i.e its floating part==0.00 and its is not equal to MIN_ELEMENT, update BUCKET_INDX as follows: + BUCKET_INDX = BUCKET_INDX - 1 + 5. Insert CURR_ELEMENT the bucket as per BUCKET_INDX + 6. Sort each bucket individually. + 7. Concatenate all sorted buckets and return concatenated list as answer. + + TIME COMPLEXITY: O(N) + SPACE COMPLEXITY: O(N) +*/ +#include +using namespace std; + +void bucketSort(vector& nums) +{ + // Intialize variables we will be needing later + int N=nums.size(); + double max_ele = *max_element(nums.begin(), nums.end()); + double min_ele = *min_element(nums.begin(), nums.end()); + double range = (max_ele - min_ele)/N; + vector buckets[N]; + + // Insert elements into their correct buckets by calculating bucket indexes + for(int i=0;i nums1={0.872, 0.435, 0.516, 0.1004, 0.1065, 0.3464}; +bucketSort(nums1); +for(auto i:nums1) cout< nums2={ 9.81, 9.6, 1.1, 1.9, 5.07,5.04, 3.0, 11.11, 0.18, 6.78}; +bucketSort(nums2); +cout<<"\n"; +for(auto i:nums2) cout< Date: Thu, 4 May 2023 00:33:35 +0530 Subject: [PATCH 0927/1894] Array: Find first duplicate value in C++ #1081 --- Arrays/find_first_duplicate_value.cpp | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Arrays/find_first_duplicate_value.cpp diff --git a/Arrays/find_first_duplicate_value.cpp b/Arrays/find_first_duplicate_value.cpp new file mode 100644 index 00000000..3d1f894e --- /dev/null +++ b/Arrays/find_first_duplicate_value.cpp @@ -0,0 +1,43 @@ +/* + Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function + that returns the first integer that appears more than once (when the array is read from left to right). + + Sample Input = [2, 1, 5, 2, 3, 3, 4] + Output : 2 + + Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution +*/ + +#include +using namespace std; + +class Solution{ +public: + // O(N) time complexity and O(N) Space Complexity Solution + int findDuplicate1(vector& nums) + { + int N=nums.size(); + + // Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity + vector trk(N,false); + + for(int i=0;i& nums) + { + int N=nums.size(); + for(int i=0;i Date: Thu, 4 May 2023 00:39:25 +0530 Subject: [PATCH 0928/1894] Deleted file from Linked List Folder as it was added by mistake ISSUE: Array: Find first duplicate value in C++ #1081 --- Linked List/find_first_duplicate_value.cpp | 43 ---------------------- 1 file changed, 43 deletions(-) delete mode 100644 Linked List/find_first_duplicate_value.cpp diff --git a/Linked List/find_first_duplicate_value.cpp b/Linked List/find_first_duplicate_value.cpp deleted file mode 100644 index 3d1f894e..00000000 --- a/Linked List/find_first_duplicate_value.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function - that returns the first integer that appears more than once (when the array is read from left to right). - - Sample Input = [2, 1, 5, 2, 3, 3, 4] - Output : 2 - - Please provide O(n) time and O(1) space solution along with O(n) time and O(n) space solution -*/ - -#include -using namespace std; - -class Solution{ -public: - // O(N) time complexity and O(N) Space Complexity Solution - int findDuplicate1(vector& nums) - { - int N=nums.size(); - - // Use Vector Instead of Unordered Set or Map for O(1) extraction time complexity - vector trk(N,false); - - for(int i=0;i& nums) - { - int N=nums.size(); - for(int i=0;i Date: Thu, 4 May 2023 01:13:44 +0530 Subject: [PATCH 0929/1894] Fast Slow Pointers:Middle of LL JAVA code --- .../linked_list_compute_midpoint.java | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 Fast and Slow Pointers/linked_list_compute_midpoint.java diff --git a/Fast and Slow Pointers/linked_list_compute_midpoint.java b/Fast and Slow Pointers/linked_list_compute_midpoint.java new file mode 100644 index 00000000..1cc2e363 --- /dev/null +++ b/Fast and Slow Pointers/linked_list_compute_midpoint.java @@ -0,0 +1,113 @@ +/* + * LEETCODE 876 +Given the head of a singly linked list, return the middle node of the linked list. +If there are two middle nodes, return the second middle node. +*Example 1: +Input: head = [1,2,3,4,5] +Output: [3,4,5] +Explanation: The middle node of the list is node 3. + +*Example 2: +Input: head = [1,2,3,4,5,6] +Output: [4,5,6] +Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. + +*CODE EXPLAINATION WITH DRY RUN: +This Java code finds the midpoint node of a singly-linked list. If the linked list has an even number +of nodes, it returns the second middle node. + +First, the Node class is defined with a constructor that takes in an integer value and initializes +the next reference to null. The insertAtTail() method takes in a head node and an integer value, +and inserts a new node with the given value at the end of the linked list. The printLinkedList() method +takes in a head node and prints out all the values in the linked list. + +The makeLinkedList() method prompts the user to enter integers until -1 is inputted. Each integer is +inserted into a new node at the tail of the linked list. The computeMidpoint() method takes in a head +node and returns the middle node(s) of the linked list. If the linked list has no nodes or only one node, +it just returns the head node. Otherwise, it initializes a slow pointer and a fast pointer to the head +node. The while loop advances the fast pointer by two nodes and the slow pointer by one node at each +iteration until the fast pointer reaches the end of the linked list. At that point, the slow pointer +will be pointing to the midpoint node(s) of the linked list. + +Finally, in the main() method, a new linked list is created by calling makeLinkedList(). The linked +list is printed using printLinkedList(). The midpoint of the linked list is computed using +computeMidpoint(), and its value is printed out. + +*Example Dry Run: +Suppose we have the following input: +1 2 3 4 5 -1 +This creates a linked list with the following structure: +1 -> 2 -> 3 -> 4 -> 5 -> null +Initially, the slow pointer and fast pointer both point to the head node, which is 1. In the first iteration of the while loop, the fast pointer moves two nodes ahead to node 3, while the slow pointer moves one node ahead to node 2. In the second iteration, the fast pointer moves another two nodes ahead to null, while the slow pointer moves one more node ahead to node 3. At this point, the slow pointer is pointing to the midpoint node(s) of the linked list. +Therefore, computeMidpoint() returns node 3, which is printed out as output. + +*/ +import java.util.Scanner; + +public class linked_list_compute_midpoint { + + static class Node { + + int data; + Node next; + + public Node(int data) { + this.data = data; + next = null; + } + } + + static Node insertAtTail(Node head, int data) { + if (head == null) { + head = new Node(data); + return head; + } + Node n = new Node(data); + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = n; + return head; + } + + static void printLinkedList(Node head) { + while (head != null) { + System.out.print(head.data + "->"); + head = head.next; + } + } + + static Node makeLinkedList() { + Scanner scanner = new Scanner(System.in); + int data = scanner.nextInt(); + Node head = null; + while (data != -1) { + head = insertAtTail(head, data); + data = scanner.nextInt(); + } + scanner.close(); + return head; + } + + static Node computeMidpoint(Node head) { + if (head == null || head.next == null) { + return head; + } + Node slow = head; + Node fast = head.next; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + return slow; + } + + public static void main(String[] args) { + Node head = makeLinkedList(); + printLinkedList(head); + System.out.println(); + Node midpoint = computeMidpoint(head); + System.out.println(midpoint.data); + } +} From ef3fc20b93ed9605db83c8191bc34c9ac74329c7 Mon Sep 17 00:00:00 2001 From: vandit98 Date: Thu, 4 May 2023 10:16:33 +0530 Subject: [PATCH 0930/1894] adding longest_peak in python --- Arrays/longest_peak.py | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Arrays/longest_peak.py diff --git a/Arrays/longest_peak.py b/Arrays/longest_peak.py new file mode 100644 index 00000000..e390b51b --- /dev/null +++ b/Arrays/longest_peak.py @@ -0,0 +1,43 @@ +""" +Write a function that takes in an array of integers and returns the length of the longest peak +in the array.A peak is defined as adjacent integers in the array that are strictly increasing +until they reach a tip (the highest value in the peak), at which point they become strictly +decreasing. At least three integers are required to form a peak. +""" + + + +#approach +""" +1. iterate through the array from index 1 to len(arr) - 1 +2. check if the current element is a peak +3. if it is a peak, then find the length of the peak +4. go to the uphill start +5. go to the downhill end +6. update the ans +""" + +arr=[1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3] + + +def longestPeak(arr: list) -> int: + ans = 0 + # iterate through the array from index 1 to len(arr) - 1 + for indx in range(1, len(arr) - 1): + # check if the current element is a peak + if arr[indx - 1] < arr[indx] > arr[indx + 1]: + # if it is a peak, then find the length of the peak + uphill_start = downhill_ends = indx + # go to the uphill start + while uphill_start > 0 and arr[uphill_start] > arr[uphill_start - 1]: + uphill_start -= 1 + # go to the downhill end + while downhill_ends + 1 < len(arr) and arr[downhill_ends] > arr[downhill_ends + 1]: + downhill_ends += 1 + # update the ans + ans = max(ans, (downhill_ends - uphill_start + 1)) + return ans + + +print(longestPeak(arr)) +# output: 6 \ No newline at end of file From c3285034faead713d67c8b9340d94db691d348ff Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 10:45:43 +0530 Subject: [PATCH 0931/1894] Create Good_pairs.cpp --- Arrays/Good_pairs.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Arrays/Good_pairs.cpp diff --git a/Arrays/Good_pairs.cpp b/Arrays/Good_pairs.cpp new file mode 100644 index 00000000..e2cc5e05 --- /dev/null +++ b/Arrays/Good_pairs.cpp @@ -0,0 +1,56 @@ +/* Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : Algorithms +Problem : Find Number of Good Pairs in Go +Issue Number : #529 +Problem statement : Given an array of integers nums, return the number of good pairs. + +A pair (i, j) is called good if nums[i] == nums[j] and i < j. + +Example 1: + +Input: nums = [1,2,3,1,1,3] +Output: 4 +Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. +Example 2: + +Input: nums = [1,1,1,1] +Output: 6 +Explanation: Each pair in the array are good. +Example 3: + +Input: nums = [1,2,3] +Output: 0 + +Constraints: + +1 <= nums.length <= 100 +1 <= nums[i] <= 100 +*/ + +-------------------------------------------------------------------------//C++ code begins here--------------------------------------------------------------------------------- +//Array: Find Number of Good Pairs in Go + +#include +using namespace std; + +int main() { + int n; + cin>>n; + vector v; + map m; + for(int i=0;i>x; + v.push_back(x); + m[x]++; + } + int count = 0; + for(auto it:m) + { + count = count + (it.second-1)*(it.second)/2; + } + cout< Date: Thu, 4 May 2023 10:52:40 +0530 Subject: [PATCH 0932/1894] Added Explanation to reversing a linked list --- Linked List/reverse_linked_list.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Linked List/reverse_linked_list.java b/Linked List/reverse_linked_list.java index e78e50e7..05606bbd 100644 --- a/Linked List/reverse_linked_list.java +++ b/Linked List/reverse_linked_list.java @@ -8,6 +8,31 @@ * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ + +/*Explaination of the code which reverses the linked list +* --> Initially we are given the head of the linked list. The approach used here is that +* for reversing the linked list we can take the user of three pointers +* +* --> These pointers are named as prev, curr, and right. Initially prev points to NULL, curr +* points to the current node (node of which the pointer has to be reversed) and the right node +* which always points to the node next to the current +* +* --> Idea here is that at each pass we will be reversing the pointer of the current node and +* move all the pointers forward by one step +* +* --> So initially, the current node points to head node, it's pointer is reversed and is made to +* point to he NULL, since now this first node becomes the last node. +* +* --> To move forward, prev is now at the location of current node, current node moves by +* one step, by making it point to the location where right is pointing now. (Using right pointer +* since the track of the next node is lost as we have reveresed the pointer). +* +* --> Loop stops when the current node becomes null. At the itereation, last node is being pointed +* by prev, which is now the first node logically, so assign head to prev. +* +* --> Example input: 1->2->3->4->5 +* Output : 5->4->3->2->1 +* */ class Solution { public ListNode reverseList(ListNode head) { ListNode prev=null; From 7966d3a99a3721e83149549e09af176c36ca766f Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 11:08:24 +0530 Subject: [PATCH 0933/1894] Update Good_pairs.cpp --- Arrays/Good_pairs.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Arrays/Good_pairs.cpp b/Arrays/Good_pairs.cpp index e2cc5e05..3d45ebf4 100644 --- a/Arrays/Good_pairs.cpp +++ b/Arrays/Good_pairs.cpp @@ -28,6 +28,21 @@ Output: 0 1 <= nums[i] <= 100 */ +Explanation of the below cpp code: + +This C++ program takes an integer n as input and then reads n integers from the standard input. +It then creates a vector v to store the input integers and a map m to count the frequency of each input integer. +Finally, the program computes the number of pairs of input integers that are equal and outputs this count to the standard output. + +The algorithm used to compute the count of pairs is based on the following observation: +for each integer x that appears k times in the input vector, there are k*(k-1)/2 pairs of integers that are equal to x. +This can be seen by choosing any two of the k occurrences of x, which can be done in k*(k-1)/2 ways. + +The program uses the map data structure to count the frequency of each integer in the input vector. +It then iterates over the pairs (x,k) in the map and adds k*(k-1)/2 to a variable count. Finally, it outputs the value of count. + +Overall, this program has a time complexity of O(n log n) due to the use of the map data structure, which has a logarithmic time complexity for insertion and lookup operations. +However, since the input size is limited to 10^5 integers, the program should run efficiently for typical input sizes. -------------------------------------------------------------------------//C++ code begins here--------------------------------------------------------------------------------- //Array: Find Number of Good Pairs in Go From a1cdd56b2ef5fcbb50c3add63658c0d0e9640547 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 11:09:04 +0530 Subject: [PATCH 0934/1894] Update Good_pairs.cpp --- Arrays/Good_pairs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/Good_pairs.cpp b/Arrays/Good_pairs.cpp index 3d45ebf4..05685736 100644 --- a/Arrays/Good_pairs.cpp +++ b/Arrays/Good_pairs.cpp @@ -26,7 +26,6 @@ Output: 0 1 <= nums.length <= 100 1 <= nums[i] <= 100 -*/ Explanation of the below cpp code: @@ -43,6 +42,7 @@ It then iterates over the pairs (x,k) in the map and adds k*(k-1)/2 to a variabl Overall, this program has a time complexity of O(n log n) due to the use of the map data structure, which has a logarithmic time complexity for insertion and lookup operations. However, since the input size is limited to 10^5 integers, the program should run efficiently for typical input sizes. +*/ -------------------------------------------------------------------------//C++ code begins here--------------------------------------------------------------------------------- //Array: Find Number of Good Pairs in Go From 6f8027eb9deeb94443e6c63b3d1f9e56f8b5e6bc Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 11:11:03 +0530 Subject: [PATCH 0935/1894] Update Good_pairs.cpp --- Arrays/Good_pairs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/Good_pairs.cpp b/Arrays/Good_pairs.cpp index 05685736..21baeccc 100644 --- a/Arrays/Good_pairs.cpp +++ b/Arrays/Good_pairs.cpp @@ -1,6 +1,6 @@ /* Name : Abhinav kumar Github username : Abhinavcode13 -Repository name : Algorithms +Repository name : data-structures-and-algorithms Problem : Find Number of Good Pairs in Go Issue Number : #529 Problem statement : Given an array of integers nums, return the number of good pairs. From 793e570d4e895dff265df55d5afb71dc0c423bbd Mon Sep 17 00:00:00 2001 From: Mohamed Ashraf Hassan Date: Thu, 4 May 2023 08:26:55 +0300 Subject: [PATCH 0936/1894] Solved Squares of a Sorted Array (#629) --- Arrays/squares_of_a_sorted_array.java | 91 +++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Arrays/squares_of_a_sorted_array.java diff --git a/Arrays/squares_of_a_sorted_array.java b/Arrays/squares_of_a_sorted_array.java new file mode 100644 index 00000000..c252997f --- /dev/null +++ b/Arrays/squares_of_a_sorted_array.java @@ -0,0 +1,91 @@ +/** + + Time Complexity: O(n), Space Complexity O(n). + + Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. + + Input: nums = [-4,-1,0,3,10] + Output: [0,1,9,16,100] + + Input: nums = [-7,-3,2,3,11] + Output: [4,9,9,49,121] + + + Input: nums = [2,3,11] + Output: [4,9,121] + +**/ + +class Solution { + public int[] sortedSquares(int[] nums) { + + int hasNegative = -1; // -1 Indcating that are no negative values in the input array. + int len = nums.length; + + // Find the index of the last negative value. + for(int i = 0; i < len; ++i) + { + if(nums[i] < 0) + { + nums[i] = Math.abs(nums[i]); // If there is a negative value make it positive. + hasNegative = i; + } + } + + + int []ans = new int[nums.length]; + + if(hasNegative != -1) // check if the array have negative values + { + + /** + If there are negative values, + that's divide the input array into two halfs. + both halfs are sorted in increasing order if: + + -first half start from a and end at index 0, Where a is the index of the last negative value. + -second half start from (b) and end at (size of the array - 1 (n - 1)) [b, n-1] iclusive, Where b is the index a + 1. + + At every step we choose the minimun value between the vlaues at index a and b then, + square the value and store it in array []ans. + **/ + int a = hasNegative, b = hasNegative + 1; + int k = 0; + + while(a >= 0 && b < len) + { + if(nums[a] <= nums[b]) // Value at index a is the minimum value so we choosed. + { + ans[k] = nums[a] * nums[a]; + a--; + } + else + { + ans[k] = nums[b] * nums[b]; + b++; + } + k++; + } + + while(a >= 0) + { + ans[k++] = nums[a] * nums[a]; + a--; + } + + while(b < len) + { + ans[k++] = nums[b] * nums[b]; + b++; + } + } + else //If there are no negative values, the sloution is straight forward. + { + + for(int i = 0; i < len; ++i) + ans[i] = nums[i] * nums[i]; + } + return ans; + } + +} \ No newline at end of file From 50af8cf2d3c4919226b10257f32c0e5bc8b1e212 Mon Sep 17 00:00:00 2001 From: vandit98 Date: Thu, 4 May 2023 11:57:15 +0530 Subject: [PATCH 0937/1894] added time complxity --- Arrays/longest_peak.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Arrays/longest_peak.py b/Arrays/longest_peak.py index e390b51b..07a32281 100644 --- a/Arrays/longest_peak.py +++ b/Arrays/longest_peak.py @@ -16,6 +16,10 @@ 5. go to the downhill end 6. update the ans """ +# Time Complexity: O(n) +# Space Complexity: O(1) + + arr=[1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3] From df04935cd26e521499e7a9c710909ccc7c571301 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 12:25:59 +0530 Subject: [PATCH 0938/1894] Create 3Sum.cpp --- Arrays/3Sum.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Arrays/3Sum.cpp diff --git a/Arrays/3Sum.cpp b/Arrays/3Sum.cpp new file mode 100644 index 00000000..70c6dcb3 --- /dev/null +++ b/Arrays/3Sum.cpp @@ -0,0 +1,60 @@ +/* Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Add Three number sum in C++ +Issue Number : #242 +Problem statement : 3Sum + +Explanation of the below cpp code : + +The code first sorts the input array in ascending order. Then, it iterates through the array and uses the two-pointer technique to find the remaining two elements that add up to the negative of the current element. + +We use two pointers, one at the beginning and one at the end of the remaining array after fixing the current element. If the sum of the three elements is less than zero, we increase the left pointer to increase the sum. If the sum is greater than zero, we decrease the right pointer to decrease the sum. If the sum is zero, we add the triplet to the result vector, and skip duplicate elements by increasing the left pointer and decreasing the right pointer until they point to different elements. + +The time complexity of the code is O(n^2), where n is the length of the input array. The sorting step takes O(n log n) time, and the nested loop takes O(n^2) time in the worst case. However, we skip many iterations of the loop using the two-pointer technique, making the actual running time faster than the worst-case time complexity. +*/ +-----------------------------------------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------------------------------------------------------------------------------------------ + +#include +using namespace std; + +vector> threeSum(vector& nums) { + vector> result; + int n = nums.size(); + sort(nums.begin(), nums.end()); // Sort the input array + + // Fix the first element and use two pointer technique to find the remaining two elements + for (int i = 0; i < n - 2; i++) { + if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicate elements + + int l = i + 1, r = n - 1; + while (l < r) { + int sum = nums[i] + nums[l] + nums[r]; + if (sum < 0) { + l++; // Increase left pointer to increase the sum + } else if (sum > 0) { + r--; // Decrease right pointer to decrease the sum + } else { + result.push_back({nums[i], nums[l], nums[r]}); + // Skip duplicate elements + while (l < r && nums[l] == nums[l + 1]) l++; + while (l < r && nums[r] == nums[r - 1]) r--; + l++; + r--; + } + } + } + return result; +} + +int main() { + vector nums = {-1, 0, 1, 2, -1, -4}; + vector> result = threeSum(nums); + for (vector triplet : result) { + for (int x : triplet) { + cout << x << " "; + } + cout << endl; + } + return 0; +} From a0b85180af14200be7a439f19ec2dd53bec30243 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 4 May 2023 12:40:50 +0530 Subject: [PATCH 0939/1894] Create Stacks_using_queues.py --- Stacks/Stacks_using_queues.py | 81 +++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Stacks/Stacks_using_queues.py diff --git a/Stacks/Stacks_using_queues.py b/Stacks/Stacks_using_queues.py new file mode 100644 index 00000000..83509e9e --- /dev/null +++ b/Stacks/Stacks_using_queues.py @@ -0,0 +1,81 @@ +/* Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Implement Stack using Queues in Python +Issue Number : #261 +Problem statement : + +Explanation of the below python code : + +__init__(self) initializes the two queues (q1 and q2) in the constructor. + +push(self, x: int) adds a new element x to the top of the stack. It first adds the element to q2, and then moves all the elements from q1 to q2 using a while loop. Finally, it swaps q1 and q2 so that q1 always contains the elements in the stack. + +pop(self) -> int removes and returns the element at the top of the stack, which is the first element in q1. + +top(self) -> int returns the element at the top of the stack, which is also the first element in q1. + +empty(self) -> bool returns True if the stack is empty (i.e., q1 is empty), and False otherwise. + +The deque data structure from the collections module is used to implement the two queues, since it provides efficient O(1) operations for adding and removing elements from both ends of the queue. + +Overall, this implementation is quite simple and efficient, since the push and pop operations take O(1) time complexity on average, while the top and empty operations take constant time. + +*/ +-------------------------------------------------------------------------//Python code begins here---------------------------------------------------------------------------- + +from collections import deque + +class Stack: + def __init__(self): + self.queue = deque() + + def push(self, x: int) -> None: + self.queue.append(x) + # Move all existing elements to the end of the queue + for _ in range(len(self.queue) - 1): + self.queue.append(self.queue.popleft()) + + def pop(self) -> int: + return self.queue.popleft() + + def top(self) -> int: + return self.queue[0] + + def empty(self) -> bool: + return len(self.queue) == 0 + +# Example usage +stack = Stack() +while True: + print("1. Push") + print("2. Pop") + print("3. Top") + print("4. Empty") + print("5. Quit") + choice = int(input("Enter your choice: ")) + if choice == 1: + x = int(input("Enter the element to push: ")) + stack.push(x) + print("Element pushed to stack") + elif choice == 2: + if stack.empty(): + print("Stack is empty") + else: + x = stack.pop() + print("Popped element:", x) + elif choice == 3: + if stack.empty(): + print("Stack is empty") + else: + x = stack.top() + print("Top element:", x) + elif choice == 4: + if stack.empty(): + print("Stack is empty") + else: + print("Stack is not empty") + elif choice == 5: + break + else: + print("Invalid choice") From b74df1f8aac21cba54d5ce82182755ff7fcea8f6 Mon Sep 17 00:00:00 2001 From: Yashi11 Date: Thu, 4 May 2023 12:48:23 +0530 Subject: [PATCH 0940/1894] Binary Search: Search in Rotated Sorted Array in C++ #432 --- Binary Search/searchInRotatedSortedArray.cpp | 88 ++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Binary Search/searchInRotatedSortedArray.cpp diff --git a/Binary Search/searchInRotatedSortedArray.cpp b/Binary Search/searchInRotatedSortedArray.cpp new file mode 100644 index 00000000..b1c083f0 --- /dev/null +++ b/Binary Search/searchInRotatedSortedArray.cpp @@ -0,0 +1,88 @@ +/* + Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. + You must write an algorithm with O(log n) runtime complexity. + + Input: nums = [4,5,6,7,0,1,2], target = 0 + Output: 4 + + Input: nums = [4,5,6,7,0,1,2], target = 3 + Output: -1 + + Input: nums = [1], target = 0 + Output: -1 + + Constraints: + > 1 <= nums.length <= 5000 + > -104 <= nums[i] <= 104 + > All values of nums are unique. + > nums is an ascending array that is possibly rotated. + > -104 <= target <= 104 + + APPROACH + 1. Find the index at which the array has been rotated with the help of Binary Search. + 2. Store the index of rotation as INDX and find the range where target might be found using the following comparision: + RANGE = {INDX+1, HIGH} if TARGET < NUMS[LOW] + RANGE = {LOW, INDX-1} if TARGET > NUMS{HIGH] + 3. Perform Binary Search for TARGET in the required range. + 4. If target is not found return -1. + + TIME COMPLEXITY : O(NlogN) SPACE COMPLEXITY: O(1) +*/ +class Solution { +public: + int search(vector& nums, int target) { + // Initialize Variable for later Usage + int n=nums.size(); + int low=0; + int high=n-1; + + //Find the Rotation Point in the Rotated Array + while(low<=high){ + int mid=(low+high)/2; + if(mid==0 || mid==n-1){ + low=mid; + break; + } + if(nums[mid-1]>nums[mid] && nums[mid+1]>nums[mid]){ + low=mid; + break; + } + else if(nums[mid]>nums[low] && nums[mid]>nums[high]){ + low=mid+1; + } + else{ + high=mid-1; + } + } + + // Re-initialize Variables Needed + int indx=low; + low=0, high=n-1; + if(target==nums[indx]){ + return indx; + } + else if(target>nums[high]){ + high=indx-1; + } + else if(targetnums[mid]){ + low=mid+1; + } + else{ + high=mid-1; + } + } + + // If target not found return -1 + return -1; + } +}; \ No newline at end of file From e1b1072bd188f212b77e27230af7356fda3c2e69 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Fri, 5 May 2023 02:11:16 +0530 Subject: [PATCH 0941/1894] Middle of Linked List in java --- Linked List/FindMiddleLinkedList.java | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Linked List/FindMiddleLinkedList.java diff --git a/Linked List/FindMiddleLinkedList.java b/Linked List/FindMiddleLinkedList.java new file mode 100644 index 00000000..40363256 --- /dev/null +++ b/Linked List/FindMiddleLinkedList.java @@ -0,0 +1,48 @@ +/* +In this code, the ListNode class represents a node in the linked list, with an integer value val and a reference to the next node next. The FindMiddleLinkedList class has a findMiddle method that takes a ListNode as its input and returns the middle node of the linked list using the fast and slow pointers algorithm. + +*/ +class ListNode { + int val; + ListNode next; + + ListNode(int val) { + this.val = val; + this.next = null; + } +} + +class FindMiddleLinkedList { + public ListNode findMiddle(ListNode head) { + // Create two pointers, slow and fast, both initially pointing to the head of the linked list. + ListNode slow = head; + ListNode fast = head; + + // Move the slow pointer one step at a time and the fast pointer two steps at a time, until the fast pointer reaches the end of the list. + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + + // When the fast pointer reaches the end of the list, the slow pointer will be pointing to the middle of the list. + return slow; + } + + public static void main(String[] args) { + // Create a sample linked list + ListNode head = new ListNode(1); + head.next = new ListNode(2); + head.next.next = new ListNode(3); + head.next.next.next = new ListNode(4); + head.next.next.next.next = new ListNode(5); + + // Create an instance of the FindMiddleLinkedList class + FindMiddleLinkedList f = new FindMiddleLinkedList(); + + // Call the findMiddle method to get the middle node of the linked list + ListNode middleNode = f.findMiddle(head); + + // Print the value of the middle node + System.out.println("The middle node has value: " + middleNode.val); + } +} From cb7a5083aaf40addf27769b666acaf1bd209fa67 Mon Sep 17 00:00:00 2001 From: Mohamed Ashraf Hassan Date: Thu, 4 May 2023 22:16:31 +0300 Subject: [PATCH 0942/1894] Solved Longest Substring Without Repeating Characters (#409) --- ...substring_without_repeating_characters.cpp | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Strings/longest_substring_without_repeating_characters.cpp diff --git a/Strings/longest_substring_without_repeating_characters.cpp b/Strings/longest_substring_without_repeating_characters.cpp new file mode 100644 index 00000000..6a0cad2a --- /dev/null +++ b/Strings/longest_substring_without_repeating_characters.cpp @@ -0,0 +1,68 @@ +/** + Time Complexity: O(n), Space Complexity: O(1) + + Given a string s, find the length of the longest substring without repeating characters. + + Example 1: + Input: s = "abcabcbb" + Output: 3 + Explanation: The answer is "abc", with the length of 3. + + Example 2: + Input: s = "bbbbb" + Output: 1 + Explanation: The answer is "b", with the length of 1. + + Example 3: + Input: s = "pwwkew" + Output: 3 + Explanation: The answer is "wke", with the length of 3. + Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + + Constraints: + 0 <= s.length <= 5 * 104 + s consists of English letters, digits, symbols and spaces. + +**/ + + +class Solution { +public: + + int v[128] = {0}; + + int mxDistinct() + { + int c = 0; + for (int i = 0; i < 128; ++i) { + if(v[i] > 1) + return 0; + + if(v[i] == 1) + c++; + } + return c; + } + + int lengthOfLongestSubstring(string s) { + + int a = 0, b = 0; + int sz = s.size(); + + if(!sz) + return 0; + int mx = 0; + while (a <= b && b < sz) + { + + v[s[b++] - ' ']++; + int curMax = mxDistinct(); + if(curMax) + mx = max(mx, curMax); + else + v[s[a++] - ' ']--; + } + + return mx; + } +}; From 2633f9e63a42bb63baf82501278bd7a3dc9cedef Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 09:28:09 +0530 Subject: [PATCH 0943/1894] Update Stacks_using_queues.py --- Stacks/Stacks_using_queues.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Stacks/Stacks_using_queues.py b/Stacks/Stacks_using_queues.py index 83509e9e..0de9d9a3 100644 --- a/Stacks/Stacks_using_queues.py +++ b/Stacks/Stacks_using_queues.py @@ -1,4 +1,4 @@ -/* Name : Abhinav kumar +''' Name : Abhinav kumar Github username : Abhinavcode13 Repository name : data-structures-and-algorithms Problem : Implement Stack using Queues in Python @@ -21,8 +21,8 @@ Overall, this implementation is quite simple and efficient, since the push and pop operations take O(1) time complexity on average, while the top and empty operations take constant time. -*/ -------------------------------------------------------------------------//Python code begins here---------------------------------------------------------------------------- +''' from collections import deque From 0e08140583c699942f2c585488d6e07fb16d6290 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 09:41:36 +0530 Subject: [PATCH 0944/1894] Create queues_using_stacks.py --- Queue/queues_using_stacks.py | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Queue/queues_using_stacks.py diff --git a/Queue/queues_using_stacks.py b/Queue/queues_using_stacks.py new file mode 100644 index 00000000..7184f62a --- /dev/null +++ b/Queue/queues_using_stacks.py @@ -0,0 +1,58 @@ +''' Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Implement Queue using Stacks in Python +Issue Number : #256 +Problem statement : + +Explanation of the below python code : + +In the above code, the Queue class represents a queue implemented using two stacks. The enqueue method simply adds the element to the first stack (stack1). The dequeue method pops an element from the second stack (stack2) if it's not empty. If stack2 is empty, it transfers all elements from stack1 to stack2 in reverse order and then pops an element from stack2. + +The program provides the user with a menu to select the operation they want to perform - enqueue, dequeue, or quit. The user can input the value to enqueue, and the program prints the enqueued or dequeued value accordingly. + + + +----------------------------------------------------------------------------------------------------------//Python code begins here----------------------------------------------------------------------------------------------------------------------- +''' + +class Queue: + def __init__(self): + self.stack1 = [] + self.stack2 = [] + + def enqueue(self, val): + self.stack1.append(val) + + def dequeue(self): + if not self.stack2: + while self.stack1: + self.stack2.append(self.stack1.pop()) + if not self.stack2: + return None + return self.stack2.pop() + +queue = Queue() + +while True: + print("Select operation -\n" + "1. Enqueue\n" + "2. Dequeue\n" + "3. Quit") + + choice = int(input("Enter choice: ")) + + if choice == 1: + val = int(input("Enter value to enqueue: ")) + queue.enqueue(val) + print("Enqueued value:", val) + elif choice == 2: + val = queue.dequeue() + if val: + print("Dequeued value:", val) + else: + print("Queue is empty.") + elif choice == 3: + break + else: + print("Invalid choice. Please try again.") From 4601d69e8a28788228419d252a4c8e1407af9ffc Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 09:52:12 +0530 Subject: [PATCH 0945/1894] Create stacks_using_queues.java --- Stacks/stacks_using_queues.java | 87 +++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Stacks/stacks_using_queues.java diff --git a/Stacks/stacks_using_queues.java b/Stacks/stacks_using_queues.java new file mode 100644 index 00000000..907a654a --- /dev/null +++ b/Stacks/stacks_using_queues.java @@ -0,0 +1,87 @@ +/* Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Implement Stack using Queues in Java +Issue Number : #259 +Problem statement : + +Explanation of the below Java code : + +In the above code, the main method demonstrates the usage of the stack by providing the user with a menu to select the operation they want to perform - push, pop, or quit. The user can input the value to push, and the program prints the pushed or popped value accordingly. + +The program uses the Scanner class to take user input from the console. The push method adds the element to the first queue (q1) and updates the top variable. The pop method transfers all elements except the last one from q1 to q2, removes the last element from q1 and swaps the two queues. The peek method returns the top variable, and the isEmpty method checks if q1 is empty. + +When the user selects the push operation, the program prompts the user to enter the value to push, and it calls the push method to push the value onto the stack. When the user selects the pop operation, the program checks if the stack is empty and prints an error message if it is. Otherwise, it calls the pop method to pop the value from the stack and prints it. + +The program continues to prompt the user for input until the user selects the quit operation + + +*/ +-------------------------------------------------------------------------------------------------------//Java code begins here-------------------------------------------------------------------------------------------------------------------------- + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +public class StackUsingQueues { + + private Queue q1 = new LinkedList<>(); + private Queue q2 = new LinkedList<>(); + private int top; + + public void push(int x) { + q1.add(x); + top = x; + } + + public int pop() { + while (q1.size() > 1) { + top = q1.remove(); + q2.add(top); + } + int popValue = q1.remove(); + Queue temp = q1; + q1 = q2; + q2 = temp; + return popValue; + } + + public int peek() { + return top; + } + + public boolean isEmpty() { + return q1.isEmpty(); + } + + public static void main(String[] args) { + StackUsingQueues stack = new StackUsingQueues(); + Scanner scanner = new Scanner(System.in); + while (true) { + System.out.println("Select operation -\n" + + "1. Push\n" + + "2. Pop\n" + + "3. Quit"); + + int choice = scanner.nextInt(); + + if (choice == 1) { + System.out.print("Enter value to push: "); + int val = scanner.nextInt(); + stack.push(val); + System.out.println("Pushed value: " + val); + } else if (choice == 2) { + if (stack.isEmpty()) { + System.out.println("Stack is empty."); + } else { + int val = stack.pop(); + System.out.println("Popped value: " + val); + } + } else if (choice == 3) { + break; + } else { + System.out.println("Invalid choice. Please try again."); + } + } + } +} From ab98f0902c9cabf51d9b73e9bde19bd76d7e04e3 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Fri, 5 May 2023 11:14:07 +0530 Subject: [PATCH 0946/1894] readme updated --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3097c48a..eff5e6d3 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ O(2^n) : This time complexity often indicates that the algorithm iterates throug O(n!) : This time complexity often indicates that the algorithm iterates through all permutations of the input elements. For example, the permutations of {1,2,3} are (1,2,3), (1,3,2), (2,1,3 , (2,3,1), (3,1,2) and (3,2,1). An algorithm is polynomial if its time complexity is at most O(n^k) where k is a constant. All the above time complexities except O(2^n) and O(n!) are polynomial. -In practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. +In the practice, the constant k is usually small, and therefore a polynomial time complexity roughly means that the algorithm is efficient. Still, there are many important problems for which no polynomial algorithm is known, i.e., nobody knows how to solve them efficiently. NP-hard problems are an important set of problems, for which no polynomial algorithm is known. # Estimating efficiency From 7dc2671ba36efbccf83e7e35d4795ce02b045810 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Fri, 5 May 2023 11:35:36 +0530 Subject: [PATCH 0947/1894] #1113 solved --- Arrays/merge_intervals.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Arrays/merge_intervals.cpp diff --git a/Arrays/merge_intervals.cpp b/Arrays/merge_intervals.cpp new file mode 100644 index 00000000..36410206 --- /dev/null +++ b/Arrays/merge_intervals.cpp @@ -0,0 +1,30 @@ +/* Array: Merge intervals in C++ #1113 +Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. + +Example 1: + +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. +*/ + + +class Solution { +public: + vector> merge(vector>& intervals) { + vector>v; + sort(intervals.begin(), intervals.end()); + vectorv1=intervals[0]; + for(int i=1; i Date: Fri, 5 May 2023 14:56:30 +0530 Subject: [PATCH 0948/1894] Create shuffle_an_array.py --- Math/shuffle_an_array.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Math/shuffle_an_array.py diff --git a/Math/shuffle_an_array.py b/Math/shuffle_an_array.py new file mode 100644 index 00000000..573e78d3 --- /dev/null +++ b/Math/shuffle_an_array.py @@ -0,0 +1,23 @@ +class Solution: + + def __init__(self, nums: List[int]): + #the value of nums is stored as an instance variable that can be accessed and used by other methods within the class + self.nums = nums + + + def reset(self) -> List[int]: + #returning the original array after reseting it + return self.nums + + def shuffle(self) -> List[int]: + s = [x for x in self.nums] + random.shuffle(s) + return s +# Time complexity - O(N), where N is the length of the input list self.nums +#Space compelxity - O(N) + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(nums) +# param_1 = obj.reset() +# param_2 = obj.shuffle() From a0462bcecd11dbbfbe55fe49643b3ae23ef6dc9c Mon Sep 17 00:00:00 2001 From: Saishreekouda Date: Fri, 5 May 2023 15:11:31 +0530 Subject: [PATCH 0949/1894] add two numbers linked list in c++ --- Linked List/AddTwoNumbers | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Linked List/AddTwoNumbers diff --git a/Linked List/AddTwoNumbers b/Linked List/AddTwoNumbers new file mode 100644 index 00000000..e37d7b61 --- /dev/null +++ b/Linked List/AddTwoNumbers @@ -0,0 +1,31 @@ +class Solution { +public: +// Iterative approach +// ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { +// int c = 0; +// ListNode newHead(0); +// ListNode *t = &newHead; +// while(c || l1 || l2) { +// c += (l1? l1->val : 0) + (l2? l2->val : 0); +// t->next = new ListNode(c%10); +// t = t->next; +// c /= 10; +// if(l1) l1 = l1->next; +// if(l2) l2 = l2->next; +// } +// return newHead.next; +// } + +// Recursive approach +ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + if(!l1 && !l2) return NULL; + int c = (l1? l1->val:0) + (l2? l2->val:0); + ListNode *newHead = new ListNode(c%10), *next = l1? l1->next:NULL; + c /= 10; + if(next) next->val += c; + else if(c) next = new ListNode(c); + newHead->next = addTwoNumbers(l2? l2->next:NULL, next); + return newHead; +} + +}; \ No newline at end of file From b4a870ebb5c9b3570cfa4d700ef67974890aa858 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Fri, 5 May 2023 15:20:29 +0530 Subject: [PATCH 0950/1894] comments, space and time complexity added --- Arrays/merge_intervals.cpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/Arrays/merge_intervals.cpp b/Arrays/merge_intervals.cpp index 36410206..125ec096 100644 --- a/Arrays/merge_intervals.cpp +++ b/Arrays/merge_intervals.cpp @@ -12,19 +12,23 @@ Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. class Solution { public: vector> merge(vector>& intervals) { - vector>v; - sort(intervals.begin(), intervals.end()); - vectorv1=intervals[0]; - for(int i=1; i>v; // Create an empty vector of vectors to store the merged intervals + sort(intervals.begin(), intervals.end()); // Sort the intervals based on their start times + vectorv1=intervals[0]; // Initialize the first merged interval to be the first interval in the sorted list + for(int i=1; i Date: Fri, 5 May 2023 15:33:43 +0530 Subject: [PATCH 0951/1894] added comments, space and time complexity --- Arrays/merge_intervals.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Arrays/merge_intervals.cpp diff --git a/Arrays/merge_intervals.cpp b/Arrays/merge_intervals.cpp new file mode 100644 index 00000000..125ec096 --- /dev/null +++ b/Arrays/merge_intervals.cpp @@ -0,0 +1,34 @@ +/* Array: Merge intervals in C++ #1113 +Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. + +Example 1: + +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. +*/ + + +class Solution { +public: + vector> merge(vector>& intervals) { + vector>v; // Create an empty vector of vectors to store the merged intervals + sort(intervals.begin(), intervals.end()); // Sort the intervals based on their start times + vectorv1=intervals[0]; // Initialize the first merged interval to be the first interval in the sorted list + for(int i=1; i Date: Fri, 5 May 2023 15:41:01 +0530 Subject: [PATCH 0952/1894] explanation added --- Linked List/AddTwoNumbers | 52 ++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/Linked List/AddTwoNumbers b/Linked List/AddTwoNumbers index e37d7b61..d3848b20 100644 --- a/Linked List/AddTwoNumbers +++ b/Linked List/AddTwoNumbers @@ -1,20 +1,44 @@ +/* Name : Saishree Kouda +Github username : saishreekouda +Repository name : data-structures-and-algorithms +Problem : Add Two Numbers Linked List in C++ +Issue Number : #620 +Problem statement : Add Two Numbers4 + +Description: +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +Example: +Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +Output: 7 -> 0 -> 8 + +Constraints: +The number of nodes in each linked list is in the range [1, 100]. +0 <= Node.val <= 9 +It is guaranteed that the list represents a number that does not have leading zeros.*/ + +/*-----------------------------------------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------------------------------------------------------------------------------------------ */ + class Solution { public: // Iterative approach -// ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { -// int c = 0; -// ListNode newHead(0); -// ListNode *t = &newHead; -// while(c || l1 || l2) { -// c += (l1? l1->val : 0) + (l2? l2->val : 0); -// t->next = new ListNode(c%10); -// t = t->next; -// c /= 10; -// if(l1) l1 = l1->next; -// if(l2) l2 = l2->next; -// } -// return newHead.next; -// } + + /* ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + int c = 0; + ListNode newHead(0); + ListNode *t = &newHead; + while(c || l1 || l2) { + c += (l1? l1->val : 0) + (l2? l2->val : 0); + t->next = new ListNode(c%10); + t = t->next; + c /= 10; + if(l1) l1 = l1->next; + if(l2) l2 = l2->next; + } + return newHead.next; +} */ // Recursive approach ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { From c1fcb82a21c72a2973ac4c4072fb22f2588a0731 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 15:43:35 +0530 Subject: [PATCH 0953/1894] Update stacks_using_queues.java --- Stacks/stacks_using_queues.java | 111 ++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 49 deletions(-) diff --git a/Stacks/stacks_using_queues.java b/Stacks/stacks_using_queues.java index 907a654a..46c3d18d 100644 --- a/Stacks/stacks_using_queues.java +++ b/Stacks/stacks_using_queues.java @@ -24,64 +24,77 @@ The program uses the Scanner class to take user input from the console. The push import java.util.Scanner; public class StackUsingQueues { +// Create two queues as instance variables +private Queue q1 = new LinkedList<>(); +private Queue q2 = new LinkedList<>(); - private Queue q1 = new LinkedList<>(); - private Queue q2 = new LinkedList<>(); - private int top; +// Create a variable to hold the top element of the stack +private int top; - public void push(int x) { - q1.add(x); - top = x; - } - - public int pop() { - while (q1.size() > 1) { - top = q1.remove(); - q2.add(top); - } - int popValue = q1.remove(); - Queue temp = q1; - q1 = q2; - q2 = temp; - return popValue; - } - - public int peek() { - return top; - } +// Method to push an element onto the stack +public void push(int x) { + q1.add(x); // Add the element to the first queue + top = x; // Update the top variable to hold the new element +} - public boolean isEmpty() { - return q1.isEmpty(); +// Method to pop an element from the stack +public int pop() { + // Move all elements except the last one from the first queue to the second queue + while (q1.size() > 1) { + top = q1.remove(); + q2.add(top); } + // Remove the last element from the first queue, which is the element to be popped + int popValue = q1.remove(); + // Swap the queues so that the second queue becomes the first queue for the next operation + Queue temp = q1; + q1 = q2; + q2 = temp; + return popValue; // Return the popped element +} - public static void main(String[] args) { - StackUsingQueues stack = new StackUsingQueues(); - Scanner scanner = new Scanner(System.in); - while (true) { - System.out.println("Select operation -\n" - + "1. Push\n" - + "2. Pop\n" - + "3. Quit"); +// Method to peek at the top element of the stack +public int peek() { + return top; // Return the top element of the stack +} - int choice = scanner.nextInt(); +// Method to check if the stack is empty +public boolean isEmpty() { + return q1.isEmpty(); // Return whether the first queue is empty +} - if (choice == 1) { - System.out.print("Enter value to push: "); - int val = scanner.nextInt(); - stack.push(val); - System.out.println("Pushed value: " + val); - } else if (choice == 2) { - if (stack.isEmpty()) { - System.out.println("Stack is empty."); - } else { - int val = stack.pop(); - System.out.println("Popped value: " + val); - } - } else if (choice == 3) { - break; +// Main method to run the program +public static void main(String[] args) { + // Create a new instance of the StackUsingQueues class + StackUsingQueues stack = new StackUsingQueues(); + // Create a new Scanner object to read input from the user + Scanner scanner = new Scanner(System.in); + // Create a loop to continuously prompt the user for input + while (true) { + System.out.println("Select operation -\n" + + "1. Push\n" + + "2. Pop\n" + + "3. Quit"); + // Read the user's choice + int choice = scanner.nextInt(); + // Check the user's choice and perform the corresponding operation + if (choice == 1) { + System.out.print("Enter value to push: "); + int val = scanner.nextInt(); + stack.push(val); + System.out.println("Pushed value: " + val); + } else if (choice == 2) { + if (stack.isEmpty()) { + System.out.println("Stack is empty."); } else { - System.out.println("Invalid choice. Please try again."); + int val = stack.pop(); + System.out.println("Popped value: " + val); } + } else if (choice == 3) { + break; + } else { + System.out.println("Invalid choice. Please try again."); } } } +} From 6d63de6f1a846b573e9c7729df52f34cedfc3fe0 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 15:49:42 +0530 Subject: [PATCH 0954/1894] Update Stacks_using_queues.py --- Stacks/Stacks_using_queues.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Stacks/Stacks_using_queues.py b/Stacks/Stacks_using_queues.py index 0de9d9a3..ca6cfdc1 100644 --- a/Stacks/Stacks_using_queues.py +++ b/Stacks/Stacks_using_queues.py @@ -27,25 +27,25 @@ from collections import deque class Stack: - def __init__(self): + def __init__(self): #The Stack class is defined with a constructor that initializes a deque object as the Stack's underlying data structure. self.queue = deque() def push(self, x: int) -> None: self.queue.append(x) - # Move all existing elements to the end of the queue + # Move all existing elements to the end of the queue #The push method takes an integer value as input and appends it to the end of the deque. It then moves all the existing elements in the deque to the end, effectively simulating the addition of the new element to the top of the Stack. for _ in range(len(self.queue) - 1): self.queue.append(self.queue.popleft()) def pop(self) -> int: - return self.queue.popleft() + return self.queue.popleft() #The pop method removes and returns the element at the top of the Stack, which is the first element in the deque. - def top(self) -> int: + def top(self) -> int: #The top method returns the element at the top of the Stack without removing it, which is the first element in the deque. return self.queue[0] - def empty(self) -> bool: + def empty(self) -> bool: #The empty method returns True if the Stack is empty (i.e., the deque has length 0), and False otherwise. return len(self.queue) == 0 -# Example usage + stack = Stack() while True: print("1. Push") @@ -59,7 +59,7 @@ def empty(self) -> bool: stack.push(x) print("Element pushed to stack") elif choice == 2: - if stack.empty(): + if stack.empty(): '''The code above shows an example usage of the Stack class, where the user can interact with the Stack through a command-line interface.The user is prompted with a menu of options to choose from, and their choice is read in as an integer value using the input() functiom''' Depending on the user's choice, the appropriate method is called on the stack object and the results are printed to the console. print("Stack is empty") else: x = stack.pop() From 28e9cdaf4c096eec692183dbc3ad47646fb5f28e Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 15:55:59 +0530 Subject: [PATCH 0955/1894] Create Valid_palindrome.py --- Strings/Valid_palindrome.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Strings/Valid_palindrome.py diff --git a/Strings/Valid_palindrome.py b/Strings/Valid_palindrome.py new file mode 100644 index 00000000..c6b8fbcc --- /dev/null +++ b/Strings/Valid_palindrome.py @@ -0,0 +1,32 @@ +'''Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Find Number of Good Pairs in Go +Issue Number : #648 +Problem statement : Check whether a given string is a Valid Palindrome in Python + +Explanation of the below cpp code : + +The is_valid_palindrome() function is the same as the one in the previous example, which checks whether a given string is a valid palindrome or not. + +The input() function is used to take input from the user. +It displays a prompt message "Enter a string:" and waits for the user to enter a value followed by pressing the Enter key. The entered value is stored in the variable s. + +The if statement checks if the input string s is a valid palindrome or not using the is_valid_palindrome() function. +If it is, it prints the message "The string is a valid palindrome", otherwise it prints "The string is not a valid palindrome". + +The time complexity of the given code is O(n) + +''' +------------------------------------------------------------------------------------------------------//Python code begins here---------------------------------------------------------------------------------------------------------------------------------- + +def is_valid_palindrome(s): + s = ''.join(filter(str.isalnum, s)).lower() + return s == s[::-1] + +s = input("Enter a string: ") #Taking input from user + +if is_valid_palindrome(s): + print("The string is a valid palindrome") #True case +else: + print("The string is not a valid palindrome") #False case From df58ecd6486168af6287359d03f19d52e7e6a208 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 16:00:31 +0530 Subject: [PATCH 0956/1894] Update queues_using_stacks.py --- Queue/queues_using_stacks.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Queue/queues_using_stacks.py b/Queue/queues_using_stacks.py index 7184f62a..9c22b42d 100644 --- a/Queue/queues_using_stacks.py +++ b/Queue/queues_using_stacks.py @@ -18,41 +18,54 @@ class Queue: def __init__(self): + # Initialize two empty stacks self.stack1 = [] self.stack2 = [] def enqueue(self, val): + # Add an element to the end of the queue by appending it to stack1 self.stack1.append(val) def dequeue(self): + # If stack2 is empty, reverse the order of the elements by popping from stack1 and pushing onto stack2 if not self.stack2: while self.stack1: self.stack2.append(self.stack1.pop()) + # If stack2 is still empty, the queue is empty, so return None if not self.stack2: return None + # Otherwise, pop the top element from stack2 and return it return self.stack2.pop() +# Create an instance of the Queue class queue = Queue() +# Enter into an infinite loop to prompt the user for operations while True: print("Select operation -\n" "1. Enqueue\n" "2. Dequeue\n" "3. Quit") + # Prompt the user for their choice of operation choice = int(input("Enter choice: ")) if choice == 1: + # If the user selects option 1, prompt them for a value to enqueue and enqueue it val = int(input("Enter value to enqueue: ")) queue.enqueue(val) print("Enqueued value:", val) elif choice == 2: + # If the user selects option 2, dequeue a value and print it, or indicate that the queue is empty val = queue.dequeue() if val: print("Dequeued value:", val) else: print("Queue is empty.") elif choice == 3: + # If the user selects option 3, quit the loop break else: + # If the user selects an invalid option, prompt them to try again print("Invalid choice. Please try again.") + From bf6baa0423ccf01f7226eee97f31f1ceca176b96 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 5 May 2023 16:06:47 +0530 Subject: [PATCH 0957/1894] Update queues_using_stacks.py --- Queue/queues_using_stacks.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Queue/queues_using_stacks.py b/Queue/queues_using_stacks.py index 9c22b42d..87b8dccc 100644 --- a/Queue/queues_using_stacks.py +++ b/Queue/queues_using_stacks.py @@ -11,6 +11,12 @@ The program provides the user with a menu to select the operation they want to perform - enqueue, dequeue, or quit. The user can input the value to enqueue, and the program prints the enqueued or dequeued value accordingly. +Summary about the code and time complexity: + +This code implements a queue using two stacks. +The enqueue operation is simply implemented by appending an element to one of the stacks, while the dequeue operation involves reversing the order of the elements by popping from one stack and pushing onto the other, and then popping the top element from the second stack. +The time complexity of the enqueue operation is O(1), while the time complexity of the dequeue operation is O(n) in the worst case, where n is the number of elements in the queue. This is because in the worst case, all the elements will need to be moved from one stack to the other during the dequeue operation. + ----------------------------------------------------------------------------------------------------------//Python code begins here----------------------------------------------------------------------------------------------------------------------- From ef83707d606e96622c725e7eb189f3bb4ef2198f Mon Sep 17 00:00:00 2001 From: Aashi Gupta <97161658+Aashi779@users.noreply.github.com> Date: Fri, 5 May 2023 16:14:07 +0530 Subject: [PATCH 0958/1894] Update shuffle_an_array.py --- Math/shuffle_an_array.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Math/shuffle_an_array.py b/Math/shuffle_an_array.py index 573e78d3..dbc4f8ac 100644 --- a/Math/shuffle_an_array.py +++ b/Math/shuffle_an_array.py @@ -1,3 +1,7 @@ +#Problem statement - Given an integer array nums, design an algorithm to randomly shuffle the array. +# All permutations of the array should be equally likely as a result of the shuffling. +# Complete the provided functions + class Solution: def __init__(self, nums: List[int]): From 6d01168a7a1197183f3171fb48b14a18193afa6b Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Fri, 5 May 2023 16:35:52 +0530 Subject: [PATCH 0959/1894] solved #1114 --- merge_intervals.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 merge_intervals.java diff --git a/merge_intervals.java b/merge_intervals.java new file mode 100644 index 00000000..54042dba --- /dev/null +++ b/merge_intervals.java @@ -0,0 +1,34 @@ +/* Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. + +Example 1: + +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] +Output: [[1,6],[8,10],[15,18]] +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. */ + + + + + + + +int len = intervals.length; // Get the length of the input intervals array +int i = 0; // Initialize a variable to keep track of the current interval being merged +List result = new ArrayList<>(); // Create an empty ArrayList to store the merged intervals +Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); // Sort the intervals based on their start times using a lambda expression +int first = intervals[i][0]; // Initialize the start time of the first merged interval to be the start time of the first interval in the sorted list +int second = intervals[i][1]; // Initialize the end time of the first merged interval to be the end time of the first interval in the sorted list + +while (i < len) { // Iterate through the intervals until all have been merged + if (intervals[i][0] <= second) { // If the start time of the current interval is less than or equal to the end time of the current merged interval, they overlap + second = Math.max(second, intervals[i][1]); // Update the end time of the current merged interval to be the maximum of the two end times + } else { // If the current interval does not overlap with the current merged interval + result.add(new int[]{first, second}); // Add the current merged interval to the output list + first = intervals[i][0]; // Update the start time of the current merged interval to be the start time of the current interval + second = intervals[i][1]; // Update the end time of the current merged interval to be the end time of the current interval + } + i++; // Move on to the next interval +} +result.add(new int[]{first, second}); // Add the last merged interval to the output list +return result.toArray(new int[0][]); // Convert the output ArrayList to an array and return it + From 725ef031e09491b6dfda5ec99c75eddafa4954ef Mon Sep 17 00:00:00 2001 From: Harsit-Agarwalla Date: Fri, 5 May 2023 18:19:25 +0530 Subject: [PATCH 0960/1894] Update Find Max in SW --- Sliding Window/find_max.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Sliding Window/find_max.go b/Sliding Window/find_max.go index d2ba9983..7c43525c 100644 --- a/Sliding Window/find_max.go +++ b/Sliding Window/find_max.go @@ -11,6 +11,12 @@ //// Maximum of 1, 7 is 7 //// Maximum of 7, 3 is 7 +// Approach: + +//// We will travel from 0 to (N-K)th element of the given array. +//// At each index, we will find the maximum of K indexes including the current index and print. +//// Suppose we are at ith index then we will find maximum of i, i+1, i+2, .. i+k-1 elements and print it. + // Complexity: //// Time Complexity: O(N*K) From 8d9eeb2167a92f5932904673182f4b050c85d0e3 Mon Sep 17 00:00:00 2001 From: Anushka Date: Fri, 5 May 2023 18:21:33 +0530 Subject: [PATCH 0961/1894] Coin Change Problem using Dynamic programming in java --- Dynamic Programming/coin_change.java | 90 ++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Dynamic Programming/coin_change.java diff --git a/Dynamic Programming/coin_change.java b/Dynamic Programming/coin_change.java new file mode 100644 index 00000000..1a710d61 --- /dev/null +++ b/Dynamic Programming/coin_change.java @@ -0,0 +1,90 @@ +/* QCoin Change Problem +You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. + + Example 1: + +Input: coins = [1,2,5], amount = 11 +Output: 3 +Explanation: 11 = 5 + 5 + 1 + +Example 2: +Input: coins = [2], amount = 3 +Output: -1 + +Example 3: +Input: coins = [1], amount = 0 +Output: 0 + +Constraints: + +1 <= coins.length <= 12 +1 <= coins[i] <= 231 - 1 +0 <= amount <= 104 */ + +//SOLUTION +//EXPLANATION OF CODE +/*Using unbounded knapsack in Dynamic programming + * The minimal number of coins required to make up a specific sum using a certain number of coins is stored in a 2D array. + * The array's dimensions are n+1 and amount+1, where n is the length of the coins array. + * Initialisation 1 + * t[i][j] is set to Integer when i = 0.MAX_VALUE-1 indicates that the amount j cannot be calculated using 0 coins. For j = 0, + * t[i][j] is set to 0, suggesting that the amount 0 can be made up of any number of coins. + * Initialisation 2 + * If the amount j is a multiple of the first coin denomination, then the minimum number of coins required to make up the amount j is j/coins[0]. + * Otherwise, it is not possible to make up the amount j using only the first coin denomination, so the value of t[1][j] is set to + * Integer.MAX_VALUE-1. + * + * main code + * The third loop fills in the t array for all other cases. If the current coin denomination coins[i-1] is less than or equal to the current amount + * j, then we can either include or exclude the current coin denomination to make up the amount j. If we include the current coin denomination, + * then the minimum number of coins required is 1 + t[i][j-coins[i-1]]. If we exclude the current coin denomination, then the minimum number of + * coins required is t[i-1][j]. We take the minimum of these two values to get the minimum number of coins required to make up the amount j using + * the first i coin denominations. +Finally, if the value of t[n][amount] is still Integer.MAX_VALUE-1, then it is not possible to make up the amount amount using the coin +denominations in coins, so we return -1. Otherwise, we return the value of t[n][amount], which represents the minimum number of coins required to +make up the amount amount using all the coin denominations in coins. +*/ + +//Code: +class Solution { + public int coinChange(int[] coins, int amount) { + int n=coins.length; + + int t[][]= new int[n+1][amount+1]; + for(int i=0; i Date: Fri, 5 May 2023 18:56:37 +0530 Subject: [PATCH 0962/1894] Create linked_list_reverse.js --- Linked List/linked_list_reverse.js | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Linked List/linked_list_reverse.js diff --git a/Linked List/linked_list_reverse.js b/Linked List/linked_list_reverse.js new file mode 100644 index 00000000..d9fcd4c3 --- /dev/null +++ b/Linked List/linked_list_reverse.js @@ -0,0 +1,43 @@ +//Problem statement-Given the head of a singly linked list, reverse the list, and return the reversed list. + +// Iteratively +* @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function(head) { + // Handling the edge cases if head node is null or when single node is there + if (head === null || head.next === null) { + return head; + } + // Using three pointer approach + let prev = null; + let curr = head; + let fwd = null; + while (curr !== null) { + // Updatng the value of each of the pointers + fwd = curr.next; + curr.next = prev; + prev = curr; + curr = fwd; + } + // Returning the head of the reversed linked list + return prev; +}; + +// Recursively +var reverseList = function(head) { + // Base case- If the head is null or single node is there + if (head === null || head.next === null) { + return head; + } + + // Recursively reverse the remaining list starting from the next node + const reversedList = reverseList(head.next); + + // Reversing the links between the current and next node + head.next.next = head; + head.next = null; + + // Returning the head of the reversed linked list + return reversedList; +}; From 1af8f70ad0dc8480f86b43acb3afe3d0a8d6739d Mon Sep 17 00:00:00 2001 From: Aashi Gupta <97161658+Aashi779@users.noreply.github.com> Date: Fri, 5 May 2023 19:03:03 +0530 Subject: [PATCH 0963/1894] Update linked_list_reverse.js Space and time complexities added --- Linked List/linked_list_reverse.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Linked List/linked_list_reverse.js b/Linked List/linked_list_reverse.js index d9fcd4c3..ccec12d0 100644 --- a/Linked List/linked_list_reverse.js +++ b/Linked List/linked_list_reverse.js @@ -23,6 +23,8 @@ var reverseList = function(head) { // Returning the head of the reversed linked list return prev; }; +// Time complexity - O(N) +// Space complexity - O(1) // Recursively var reverseList = function(head) { @@ -41,3 +43,5 @@ var reverseList = function(head) { // Returning the head of the reversed linked list return reversedList; }; +// Time complexity - O(N) +// Space complexity - O(N) From 03e5ef2b7eda326b4ca924ff3454d3b1f5ca45e0 Mon Sep 17 00:00:00 2001 From: Anushka Date: Fri, 5 May 2023 19:18:59 +0530 Subject: [PATCH 0964/1894] K closest point to origin using max-heap --- .../K_closest_point_to origin.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Dynamic Programming/K_closest_point_to origin.java diff --git a/Dynamic Programming/K_closest_point_to origin.java b/Dynamic Programming/K_closest_point_to origin.java new file mode 100644 index 00000000..3b48a346 --- /dev/null +++ b/Dynamic Programming/K_closest_point_to origin.java @@ -0,0 +1,73 @@ +/* + K Closest Points to Origin + +Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). +The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). +You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + + + +Example 1: +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + +Example 2: +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. + +Constraints: + +1 <= k <= points.length <= 104 +-104 < xi, yi < 104 + */ + + /* + SOLUTION: + + Explanation: + Solved this question using priority Queue. + Created a priority queue with an Integer.comapre() function. + The solution uses a max-heap, implemented as a PriorityQueue, to keep track of the k closest points seen so far. + We use the Euclidean distance formula to calculate the distance between each point and the origin, + which is given by the square root of the sum of the squares of the coordinates. However, to avoid the expensive square root operation, + we square the distance formula and compare the squared distances instead. + + The PriorityQueue is initialized with a lambda function that compares the squared distances of two points, p1 and p2, + using the Integer.compare() method. This lambda function sorts the points in descending order of their squared distances so that the + largest squared distance is at the top of the queue. + + + + + */ + + //code: + class Solution { + + public int[][] kClosest(int[][] points, int k) { + + Queue q = new PriorityQueue((p1, p2) -> Integer.compare((p2[0] * p2[0] + p2[1] * p2[1]),(p1[0] * p1[0] + p1[1] * p1[1]))); // Created a priority queue (Implementing max-heap) with a comparison function. + + for(int i=0; i k){ + q.poll(); + } + + } + int[][] arr = new int[k][2]; + while(k>0){ + arr[--k] = q.poll(); /* Creating a 2D array of size K and storing points in non decreasing order of their distance (from ,least-most). */ + } + return arr; //answer + + } +} \ No newline at end of file From 76f078966bb1aa686beb24efc881635b9686bc19 Mon Sep 17 00:00:00 2001 From: Mohamed Ashraf Hassan Date: Fri, 5 May 2023 17:05:30 +0300 Subject: [PATCH 0965/1894] Solved Longest Substring Without Repeating Characters (#409) [UPDATED With Comments]. --- ...substring_without_repeating_characters.cpp | 42 +++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/Strings/longest_substring_without_repeating_characters.cpp b/Strings/longest_substring_without_repeating_characters.cpp index 6a0cad2a..29cdff8b 100644 --- a/Strings/longest_substring_without_repeating_characters.cpp +++ b/Strings/longest_substring_without_repeating_characters.cpp @@ -1,18 +1,21 @@ /** - Time Complexity: O(n), Space Complexity: O(1) - + Time Complexity: t(n) = n * 128 -> O(n). + Where n is the size of string s. + + Space Complexity: O(1) + Given a string s, find the length of the longest substring without repeating characters. - + Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. - + Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. - + Example 3: Input: s = "pwwkew" Output: 3 @@ -29,8 +32,16 @@ class Solution { public: + + + // Array to store the frequency of characters for sub-string that's starts at index a and end at index b - 1. int v[128] = {0}; + /** + Function: mxDistinct returns the maximum number of unique charachters of substring s[a, b[ + if there is at least one character that present more than one time the function returns 0, + beacause where are looking for the lonest substring withput repating characters. + **/ int mxDistinct() { int c = 0; @@ -49,17 +60,24 @@ class Solution { int a = 0, b = 0; int sz = s.size(); - if(!sz) + if(!sz) // If the string s is empty the functon returns 0. return 0; - int mx = 0; - while (a <= b && b < sz) + + int mx = 0; // Variable mx to store the result. + + while (a <= b && b < sz) { - v[s[b++] - ' ']++; - int curMax = mxDistinct(); - if(curMax) + v[s[b++] - ' ']++; // Count how many times character at index b (s[b]) appears in the string s. + + int curMax = mxDistinct(); // Variable to store the current max or the max so far. + if(curMax) /** + If we find a substring without repeating characters we take the maximum between mx and curMax. + REMEMBER: We are looking for the longest one. Actullay, the size of the longest one. + **/ + mx = max(mx, curMax); - else + else // If there is no such a substring we start looking for substring that begins at index a + 1. v[s[a++] - ' ']--; } From cf08f9d074fcdc4789a17f128494e4a693ac308b Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Fri, 5 May 2023 22:10:54 +0530 Subject: [PATCH 0966/1894] #1120 solved --- Arrays/insert_interval.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Arrays/insert_interval.java diff --git a/Arrays/insert_interval.java b/Arrays/insert_interval.java new file mode 100644 index 00000000..5a40b71a --- /dev/null +++ b/Arrays/insert_interval.java @@ -0,0 +1,35 @@ +/* You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. + +Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). + +Return intervals after the insertion. + +Example 1: + +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +Output: [[1,5],[6,9]] */ + +public int[][] insert(int[][] intervals, int[] newInterval) { // Define a method that takes in an array of intervals and a new interval to be inserted + List list = new ArrayList<>(); // Create a new ArrayList to store the merged intervals + for(int[] curr : intervals){ // Iterate through each interval in the input array + if(curr[0] > newInterval[1]){ // If the start time of the current interval is greater than the end time of the new interval, they do not overlap + list.add(newInterval); // Add the new interval to the output list + newInterval = curr; // Update the new interval to be the current interval + } + else if(curr[1] < newInterval[0]){ // If the end time of the current interval is less than the start time of the new interval, they do not overlap + list.add(curr); // Add the current interval to the output list + }else{ // If the intervals overlap + int start = Math.min(curr[0], newInterval[0]); // Merge the start times of the intervals + int end = Math.max(curr[1], newInterval[1]); // Merge the end times of the intervals + newInterval[0] = start; // Update the start time of the new interval to be the merged start time + newInterval[1] = end; // Update the end time of the new interval to be the merged end time + } + } + list.add(newInterval); // Add the last merged interval to the output list + int[][] answer = new int[list.size()][]; // Create a new 2D array to store the merged intervals + for(int i=0;i Date: Fri, 5 May 2023 22:41:18 +0530 Subject: [PATCH 0967/1894] Added python code for insert interval --- Arrays/insert_interval.py | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Arrays/insert_interval.py diff --git a/Arrays/insert_interval.py b/Arrays/insert_interval.py new file mode 100644 index 00000000..d044b759 --- /dev/null +++ b/Arrays/insert_interval.py @@ -0,0 +1,79 @@ +##57. Insert Interval +#You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. +#Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). +#Return intervals after the insertion. +#Example 1: +#Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +#Output: [[1,5],[6,9]] +#Example 2: +#Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +#Output: [[1,2],[3,10],[12,16]] +#Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. + +##CODE Explaination +# The function insert takes two arguments, intervals which is a list of non-overlapping intervals and newInterval which is another interval that needs to be inserted into intervals. +# The variable n holds newInterval. The variable j holds intervals. The variables m and m1 are initialized with the start and end points of newInterval, respectively. The variable i is used to iterate through the intervals in j. +# The while loop checks if newInterval overlaps with any interval in intervals. If there is an overlap, we update m and/or m1 to include all overlapping intervals. +# If there is an overlap, the overlapping interval is removed from j using the pop method. If an interval is removed, we decrement i by 1 so that we don't skip any intervals. +# If there is no overlap, we increment i by 1 so that we can move on to the next interval in j. +# Once all overlaps are handled, we create a new interval s1=[m,m1] which is the combination of all overlapping intervals and newInterval. We append this new combined interval to j and sort it in ascending order based on the start point of each interval. +# Finally, we return j, which is the updated list of non-overlapping intervals. + +# Now let's do a dry run of the first example: +# intervals = [[1,3], [6,9]] +# newInterval = [2,5] +# result = insert(intervals, newInterval) +# print(result) +# Initially, n = [2,5], j = [[1,3], [6,9]], i = 0, m = 2, and m1 = 5. + +# First iteration of the while loop: + +# We check if n overlaps with [1,3]. Since there is an overlap, we update m to 1 and keep m1 as 5. +# We remove [1,3] from j using the pop method and append [1,5] to j, so j becomes [[6,9], [1,5]]. +# We decrement i to -1 since we removed an element from j. +# Second iteration of the while loop: + +# We check if n overlaps with [6,9]. Since there is no overlap, we increment i to 0 to move on to the next interval in j. +# Third iteration of the while loop: + +# We check if n overlaps with [1,5]. Since there is an overlap, we update m to 1 and keep m1 as 5. +# We remove [1,5] from j using the pop method and append [1,5] to j, so j remains [[6,9], [1,5]]. +# We decrement i to 0 since we removed an element from j. +# Since we have checked all intervals in j, we exit the while loop. + +# We create a new interval s1=[1,5] which is the combination of [1,3] and [2,5]. We append s1 to j so j becomes [[6,9], [1,5]]. + +# Finally, we sort j in ascending order based on the start point of each interval. The sorted list is [[1,5], [6,9]]. +# We return j which is the updated list of non-overlapping intervals after inserting newInterval. Therefore, the output of this function for the input intervals = [[1,3], [6,9]], newInterval = [2,5] is [[1,5],[6,9]]. +from typing import List + +def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + n = newInterval + j = intervals + i = 0 + m = n[0] + m1 = n[1] + while i < len(j): + if n[0] in range(j[i][0],j[i][1]+1) or n[1] in range(j[i][0],j[i][1]+1) or (n[1]>=j[i][1] and n[0]<=j[i][0]): + if j[i][0]m1: + m1=j[i][1] + j.pop(i) + if i<=0: + i=0 + else: + i-=1 + else: + i+=1 + s1=[m,m1] + j.append(s1) + j.sort() + return j + +# Example usage +intervals = [[1,3], [6,9]] +newInterval = [2,5] +result = insert(intervals, newInterval) +print(result) +# Output: [[1,5],[6,9]] From 1153cfa15b7f1deab65a960f4f5361d4da44422b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 6 May 2023 00:08:29 +0530 Subject: [PATCH 0968/1894] update contributing guide --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e85e9f41..c502f1c4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ Contributions are always welcome! - Add Time and Space complexity - Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) -- Send a Pull Request (PR) against main branch +- Send a Pull Request (PR) against main branch and mention issue number in the request ## What if the problem you want to add is not present in the issue? From 6a4fbb0f9f0896d63bbab3c0a77358b3e37a3018 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 6 May 2023 00:14:47 +0530 Subject: [PATCH 0969/1894] update contributing.md --- CONTRIBUTING.md | 87 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c502f1c4..d0145236 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,93 @@ Contributions are always welcome! - Provide link for further reading (optional) - Send a Pull Request (PR) against main branch and mention issue number in the request +# Example program + +```go +/* + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + + Explanation : + + This code implements the Smallest Difference problem which takes two arrays of integers as input and returns a pair of integers, + one from each array, with the smallest absolute difference between them. + + The function first initializes two variables current and smallest to the maximum integer value. It then sorts both input arrays + in ascending order using the sort.Ints function from the sort package. + + The function then iterates through both arrays using two pointers, idx1 and idx2, initialized to 0. Inside the loop, it compares + the elements at the current indices of the two arrays, first and second, and calculates the absolute difference between + them in the current variable. + + If current is smaller than the smallest variable, it updates smallest to current and assigns the current pair of integers + to the result variable. + + The function returns the result variable, which contains the pair of integers with the smallest absolute difference. + + If there are identical integers in the two input arrays, the function will return them immediately, without any further comparisons. + + O(nlog(n) + mlog(m)) time | O(1) space - where n is the length of the first input array and m is the length of the second input array +*/ + +package main + +import ( + "math" + "sort" +) + +// SmallestDifference takes two integer slices as input and returns a slice with two integers. +// The two integers in the returned slice have the smallest absolute difference among all pairs +// of integers from the two input slices. +func SmallestDifference(array1, array2 []int) []int { + // Initialize variables for the smallest difference and the current difference being calculated + current, smallest := math.MaxInt32, math.MaxInt32 + // Sort the input slices + sort.Ints(array1) + sort.Ints(array2) + // Initialize variables for the indices for the two slices + idx1, idx2 := 0, 0 + // Initialize an empty slice for the result + result := []int{} + // Loop through the two slices until we reach the end of one of the slices + for idx1 < len(array1) && idx2 < len(array2) { + // Get the values at the current indices for the two slices + first, second := array1[idx1], array2[idx2] + // Calculate the current difference between the two values + if first < second { + current = second - first + idx1++ + } else if second < first { + current = first - second + idx2++ + } else { + // If the two values are equal, we can return the pair + return []int{first, second} + } + // Update the smallest difference and result slice if the current difference is smaller + if smallest > current { + smallest = current + result = []int{first, second} + } + } + // Return the pair with the smallest absolute difference + return result +} + +``` + ## What if the problem you want to add is not present in the issue? - You can suggest an idea for this project under issues tab (add list of questions you think it is important, it will be assigned to you) From 3c4e7cddf69e00e0350d2f5324909a4b0af8a800 Mon Sep 17 00:00:00 2001 From: Sagar Date: Sat, 6 May 2023 00:22:14 +0530 Subject: [PATCH 0970/1894] Added roman to integer in java --- Hash Table/roman_to_integer.java | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Hash Table/roman_to_integer.java diff --git a/Hash Table/roman_to_integer.java b/Hash Table/roman_to_integer.java new file mode 100644 index 00000000..06986785 --- /dev/null +++ b/Hash Table/roman_to_integer.java @@ -0,0 +1,42 @@ +// AUTHOR : Sagar Wadhwa +class Solution { + public int romanToInt(String s) { + // Hashmap in java which stores key value pairs. Each key is unique and no key is repeated + HashMap map = new HashMap<>(); + + // Defining the basic rules of mapping from roman numeral to integer numbers. + map.put('I',1); + map.put('V',5); + map.put('X',10); + map.put('L',50); + map.put('C',100); + map.put('D',500); + map.put('M',1000); + + //extract the last character of the string, and find it in the map, store this keys value in the + // variable named "res" + int res = map.get(s.charAt(s.length()-1)); + + //iterate over the string from the second last character till the first character. Idea to solve + // this problem is that in the loop, for every character we check whether the value of the roman + // numeral at the i+1 th index is greater than or less than the value of the roman numeral at i th + // index. If the value of the roman numeral at the i th index is less than the value of the + // roman numeral at i+1 th index, then obviously that means we have to subtract the value of the + // roman numeral at the i th index from the result calculated so far. Else we have to add the value + // of the roman numeral at the i th index to the result calculated so far. Example: V means five, + // but if it is IV, then here the value of the roman numeral I is less than the value of the roman + // numeral V, so that means subtract I from V (4). If the string is VI, means 6, then here the value of + // V is greater than the value of I, so add I in V, that is 6. + // Doing so in an iterative fashion and storing the result and then adding or subtracting values + // from it accordingly will give us our final result. + for(int i=s.length()-2;i>=0;i--){ + + if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){ + res -= map.get(s.charAt(i)); + }else{ + res += map.get(s.charAt(i)); + } + } + return res; + } +} \ No newline at end of file From 1bcbf3dd5397f32be76e88f60818c90bc34cd1ca Mon Sep 17 00:00:00 2001 From: Thriver <97860789+SuyashSingh01@users.noreply.github.com> Date: Sat, 6 May 2023 10:44:32 +0530 Subject: [PATCH 0971/1894] rename it --- kclosest_sol.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 kclosest_sol.cpp diff --git a/kclosest_sol.cpp b/kclosest_sol.cpp new file mode 100644 index 00000000..1780625e --- /dev/null +++ b/kclosest_sol.cpp @@ -0,0 +1,44 @@ +// Author : SUYASH SINGH +/* +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] + +Explanation: + +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. +*/ +#include +#include + +using namespace std; + +class Solution { +public: + vector> kClosest(vector>& points, int k) { + vector>> v; + for(auto x: points) { + double dis = sqrt(x[0] * x[0] + x[1] * x[1]); + v.push_back({dis, {x[0], x[1]}}); + } + sort(v.begin(), v.end()); + vector> ans; + for(int i=0; i> points {{3, 4}, {1, 2}, {-1, -1}, {0, 0}, {2, 3}, {-2, 2}}; + int k = 3; + Solution s; + vector> closest_points = s.kClosest(points, k); + cout << "The " << k << " closest points to the origin are:\n"; + for(auto point: closest_points) { + cout << "(" << point[0] << ", " << point[1] << ")\n"; + } + return 0; +} From 100d6aaf54dd22c20952ef3d4c9d0d0e04b483ae Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sat, 6 May 2023 11:18:30 +0530 Subject: [PATCH 0972/1894] ##1118 solved --- Arrays/insert_intervals.cpp | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Arrays/insert_intervals.cpp diff --git a/Arrays/insert_intervals.cpp b/Arrays/insert_intervals.cpp new file mode 100644 index 00000000..0c199085 --- /dev/null +++ b/Arrays/insert_intervals.cpp @@ -0,0 +1,47 @@ +/* You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. + +Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). + +Return intervals after the insertion. + +Example 1: + +Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +Output: [[1,5],[6,9]] +*/ + + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + // get the number of intervals and initialize an index variable + int n = intervals.size(), i = 0; + // initialize a vector to store the result + vector> res; + + // loop through the intervals until the end or until the end of the first interval that comes after the new interval + while(i < n && intervals[i][1] < newInterval[0]){ + // add the current interval to the result + res.push_back(intervals[i]); + i++; + } + // loop through the intervals that overlap with the new interval + while(i < n && newInterval[1] >= intervals[i][0]){ + // update the start and end of the new interval to include the current interval + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + i++; + } + // add the new interval to the result + res.push_back(newInterval); + + // add the remaining intervals to the result + while(i < n){ + res.push_back(intervals[i]); + i++; + } + // return the result + return res; + } +}; + From c2073cb85533e83c6356a949edbeeb57ecc7f947 Mon Sep 17 00:00:00 2001 From: Faizan Siddiqui Date: Sat, 6 May 2023 11:21:42 +0530 Subject: [PATCH 0973/1894] Increased readibilty of the code --- Arrays/insert_interval.py | 65 +++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/Arrays/insert_interval.py b/Arrays/insert_interval.py index d044b759..66155352 100644 --- a/Arrays/insert_interval.py +++ b/Arrays/insert_interval.py @@ -1,16 +1,16 @@ -##57. Insert Interval -#You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. -#Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). -#Return intervals after the insertion. -#Example 1: -#Input: intervals = [[1,3],[6,9]], newInterval = [2,5] -#Output: [[1,5],[6,9]] -#Example 2: -#Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] -#Output: [[1,2],[3,10],[12,16]] -#Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. +# 57. Insert Interval +# You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. +# Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). +# Return intervals after the insertion. +# Example 1: +# Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +# Output: [[1,5],[6,9]] +# Example 2: +# Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +# Output: [[1,2],[3,10],[12,16]] +# Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. -##CODE Explaination +# CODE Explaination # The function insert takes two arguments, intervals which is a list of non-overlapping intervals and newInterval which is another interval that needs to be inserted into intervals. # The variable n holds newInterval. The variable j holds intervals. The variables m and m1 are initialized with the start and end points of newInterval, respectively. The variable i is used to iterate through the intervals in j. # The while loop checks if newInterval overlaps with any interval in intervals. If there is an overlap, we update m and/or m1 to include all overlapping intervals. @@ -45,35 +45,46 @@ # Finally, we sort j in ascending order based on the start point of each interval. The sorted list is [[1,5], [6,9]]. # We return j which is the updated list of non-overlapping intervals after inserting newInterval. Therefore, the output of this function for the input intervals = [[1,3], [6,9]], newInterval = [2,5] is [[1,5],[6,9]]. +# Code from typing import List + def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + # Assign variables for easier readability n = newInterval j = intervals i = 0 - m = n[0] - m1 = n[1] + m = n[0] # Initialize starting point of the interval to be inserted + m1 = n[1] # Initialize ending point of the interval to be inserted + + # Iterate over all existing intervals while i < len(j): - if n[0] in range(j[i][0],j[i][1]+1) or n[1] in range(j[i][0],j[i][1]+1) or (n[1]>=j[i][1] and n[0]<=j[i][0]): - if j[i][0]m1: - m1=j[i][1] + # If any part of the new interval overlaps with the current interval + if n[0] in range(j[i][0], j[i][1]+1) or n[1] in range(j[i][0], j[i][1]+1) or (n[1] >= j[i][1] and n[0] <= j[i][0]): + # Expand the new interval to include the current interval + if j[i][0] < m: + m = j[i][0] + if j[i][1] > m1: + m1 = j[i][1] + # Remove the current interval from the list and adjust the index accordingly j.pop(i) - if i<=0: - i=0 + if i <= 0: + i = 0 else: - i-=1 + i -= 1 else: - i+=1 - s1=[m,m1] + i += 1 # Move to the next interval if there is no overlap + + # Create the final interval by combining all intervals that overlap with the new interval + s1 = [m, m1] j.append(s1) - j.sort() + j.sort() # Sort the final list of intervals by their starting points return j + # Example usage -intervals = [[1,3], [6,9]] -newInterval = [2,5] +intervals = [[1, 3], [6, 9]] +newInterval = [2, 5] result = insert(intervals, newInterval) print(result) # Output: [[1,5],[6,9]] From 77a9c2515596c9f029ee44b9cf08218ef4aed889 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 6 May 2023 13:26:40 +0530 Subject: [PATCH 0974/1894] Create Add_two_numbers.py --- Linked List/Add_two_numbers.py | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Linked List/Add_two_numbers.py diff --git a/Linked List/Add_two_numbers.py b/Linked List/Add_two_numbers.py new file mode 100644 index 00000000..60f7dd47 --- /dev/null +++ b/Linked List/Add_two_numbers.py @@ -0,0 +1,46 @@ +'''Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem :Linked List: Add Two Numbers in Python +Issue Number : #621 +Problem statement : + +Explanation of the below python code : + +This code implements a solution for the "Add Two Numbers" problem on LeetCode, where the inputs are two non-empty linked lists representing two non-negative integers. The goal is to return the sum of the two integers as a linked list. + +The function takes in two linked lists, l1 and l2, and creates a new linked list represented by the variable 'dummy' which will store the sum. The current node of the new linked list is represented by the variable 'curr'. The variable 'carry' stores the carry-over value from the previous sum. + +The function then loops through both input linked lists, l1 and l2, as well as any carry-over value from the previous sum. It adds the values of the corresponding nodes in l1 and l2 (if they exist) and any carry-over value from the previous sum. It then calculates the carry-over value and the new value for the current node by dividing the sum by 10 and taking the remainder. The carry-over value is then updated for the next iteration of the loop. + +The new node with the calculated value is added to the end of the new linked list using the 'curr' variable. 'curr' is then updated to point to the new node. Once the loop is completed, the new linked list is returned, but without the initial 'dummy' node, as the first node in the list is actually the second node in the sequence. + +Overall, the function creates a new linked list representing the sum of the input linked lists, using a carry-over value to handle any values greater than 10. It runs in linear time in the length of the input linked lists, making it an efficient solution. + + +''' + +-------------------------------------------------------------------------//python code begins here---------------------------------------------------------------------------------------------------------------------------------------------------------- + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + curr = dummy + carry = 0 + while l1 or l2 or carry: + val = carry + if l1: + val += l1.val + l1 = l1.next + if l2: + val += l2.val + l2 = l2.next + carry, val = divmod(val, 10) + curr.next = ListNode(val) + curr = curr.next + return dummy.next From babb9b9da10a15cc0acd222ceefb457316f15c21 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 6 May 2023 13:33:57 +0530 Subject: [PATCH 0975/1894] Create valid_palindrome.js --- Strings/valid_palindrome.js | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Strings/valid_palindrome.js diff --git a/Strings/valid_palindrome.js b/Strings/valid_palindrome.js new file mode 100644 index 00000000..ab39678d --- /dev/null +++ b/Strings/valid_palindrome.js @@ -0,0 +1,54 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem :Two Pointers: Check whether a given string is a Valid Palindrome in Javascript +Issue Number : #649 +Problem statement : + +Explanation of the below Java code : + +we first define the isPalindrome() function, which converts the input string to lowercase and removes all non-alphanumeric characters using a regular expression, and then uses two pointers to loop through the string and check whether it is a valid palindrome. + +We then use the prompt() function to display a popup dialog box and prompt the user to enter a string input. The input value is then stored in the str variable. + +We then call the isPalindrome() function with the input string as an argument to check whether it is a palindrome. If it is, we use the console.log() function to display a message saying that the input string is a palindrome. If it is not, we display a message saying that the input string is not a palindrome. + + + +*/ + +-------------------------------------------------------------------------------------------------------//Java code begins here------------------------------------------------------------------------------------------------------------------------------- + +function isPalindrome(str) { + // Convert the input string to lowercase and remove non-alphanumeric characters + str = str.toLowerCase().replace(/[^a-z0-9]/g, ''); + + // Initialize two pointers, one starting from the beginning of the string, and the other from the end + let left = 0; + let right = str.length - 1; + + // Loop through the string while the pointers haven't crossed each other + while (left < right) { + // If the characters at the left and right pointers don't match, the string is not a palindrome + if (str[left] !== str[right]) { + return false; + } + + // Move the pointers towards each other + left++; + right--; + } + + // If the loop finishes, the string is a palindrome + return true; +} + +// Prompt the user for a string input +let str = prompt("Enter a string:"); + +// Check whether the input string is a palindrome +if (isPalindrome(str)) { + console.log(`${str} is a palindrome!`); +} else { + console.log(`${str} is not a palindrome.`); +} From de1440b12862a742e8234f1f22d2c56a9b47e2f1 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 6 May 2023 17:36:34 +0530 Subject: [PATCH 0976/1894] Create Substrings_with_1.py --- Math/Substrings_with_1.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Math/Substrings_with_1.py diff --git a/Math/Substrings_with_1.py b/Math/Substrings_with_1.py new file mode 100644 index 00000000..dd5ce9d3 --- /dev/null +++ b/Math/Substrings_with_1.py @@ -0,0 +1,29 @@ +'''Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Number of Substrings With Only 1s in Python +Issue Number : #518 +Problem statement : + +Explanation of the below Python code : + +The implementation is quite similar to the C++ implementation. We iterate over the string s using a for loop and keep track of the count of consecutive 1's using the variable count. Whenever we encounter a '0', we calculate the number of substrings that can be formed using the formula n*(n+1)/2, add it to the final answer ans, and reset the value of count to 0. Finally, we calculate the number of substrings for the last substring of consecutive 1's, add it to the final answer ans, and return the result modulo 10^9 + 7. Note that we have used the integer division operator // to perform the division in Python. + + + +''' + +----------------------------------------------------------------------------------------------//Python code begins here-------------------------------------------------------------------------------------------------------------------------------------- + +class Solution: + def numSub(self, s: str) -> int: + count = 0 + ans = 0 + for i in range(len(s)): + if s[i] == '1': + count += 1 + else: + ans = (ans + (count*(count+1))//2) % (10**9 + 7) + count = 0 + ans = (ans + (count*(count+1))//2) % (10**9 + 7) + return ans From 6c1c3fbd02747b96ee8e279e7ec6a46fb689f67a Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 6 May 2023 17:43:22 +0530 Subject: [PATCH 0977/1894] Create Uniquedigits.cpp --- Math/Uniquedigits.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/Uniquedigits.cpp diff --git a/Math/Uniquedigits.cpp b/Math/Uniquedigits.cpp new file mode 100644 index 00000000..cb97efbc --- /dev/null +++ b/Math/Uniquedigits.cpp @@ -0,0 +1,37 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Count Numbers with Unique Digits in C++ +Issue Number : #500 +Problem statement : + +Explanation of the below C++ code : + +In this implementation, we first handle the base case of n = 0 by returning 1. Then, we initialize the answer ans to 10 since there are 10 unique digits between 0 and 9. We also initialize the variables unique_digits and available_digits to 9 since we can't use 0 as the first digit. + +Next, we enter a loop that runs n-1 times (since we have already considered the case of i = 1). In each iteration of the loop, we compute unique_digits as the product of the current value of unique_digits and available_digits. We then add unique_digits to the answer ans and decrement available_digits. This is because we can't use the digits that have already been used for the previous digits. + +Finally, we return the value of ans. + +*/ + +-------------------------------------------------------------------------//C++ code begins here---------------------------------------------------------------------------- + + +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + int ans = 10; + int unique_digits = 9; + int available_digits = 9; + while (n-- > 1 && available_digits > 0) { + unique_digits *= available_digits; + ans += unique_digits; + available_digits--; + } + return ans; + } +}; From f084a8ed0025c21a54819945705e258c38629b68 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 6 May 2023 17:47:08 +0530 Subject: [PATCH 0978/1894] Create Uniquedigits.java --- Math/Uniquedigits.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/Uniquedigits.java diff --git a/Math/Uniquedigits.java b/Math/Uniquedigits.java new file mode 100644 index 00000000..019d4d26 --- /dev/null +++ b/Math/Uniquedigits.java @@ -0,0 +1,37 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Count Numbers with Unique Digits in Java +Issue Number : #501 +Problem statement : + +Explanation of the below Java code : + +We handle the base case of n = 0 by returning 1. We initialize the answer ans to 10 since there are 10 unique digits between 0 and 9. We also initialize the variables unique_digits and available_digits to 9 since we can't use 0 as the first digit. + +We then enter a loop that runs n-1 times (since we have already considered the case of i = 1). In each iteration of the loop, we compute unique_digits as the product of the current value of unique_digits and available_digits. We then add unique_digits to the answer ans and decrement available_digits. This is because we can't use the digits that have already been used for the previous digits. + +Finally, we return the value of ans. + + +*/ + +--------------------------------------------------------------------------------------------------------//Java code begins here--------------------------------------------------------------------------------------------------------------------------------- + + +class Solution { + public int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + int ans = 10; + int unique_digits = 9; + int available_digits = 9; + while (n-- > 1 && available_digits > 0) { + unique_digits *= available_digits; + ans += unique_digits; + available_digits--; + } + return ans; + } +} From 765f363a3918ac3a0af4f4d1db7593d7da82d4f1 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Sat, 6 May 2023 18:50:41 +0530 Subject: [PATCH 0979/1894] Created Stack with max API --- Stacks/Stack_with_max_API.cpp | 44 +++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Stacks/Stack_with_max_API.cpp diff --git a/Stacks/Stack_with_max_API.cpp b/Stacks/Stack_with_max_API.cpp new file mode 100644 index 00000000..f12761c8 --- /dev/null +++ b/Stacks/Stack_with_max_API.cpp @@ -0,0 +1,44 @@ +/* +Time Complexity of all Operations is O(1) +Space Complexity is O(n) +In this implementation, we use two stacks: s is the main stack that holds the elements of the stack, and max_s is a secondary stack that holds the maximum values in s. When a new value is pushed onto the stack, we compare it with the current maximum value in max_s and add it to max_s if it's greater than or equal to the current maximum. +*/ +#include +using namespace std; + +class MaxStack { +private: + stack s; // Main stack that holds the elements of the stack + stack max_s; // Secondary stack that holds the maximum values in s + +public: + void push(int val) { + s.push(val); // Push the value onto the main stack + if (max_s.empty() || val >= max_s.top()) { + // If max_s is empty or the new value is greater than or equal to the current maximum, + // push the value onto max_s + max_s.push(val); + } + } + + void pop() { + if (s.top() == max_s.top()) { + // If the top value of s is equal to the top value of max_s, it means that the top value + // of s is the current maximum, so we need to pop it from max_s as well + max_s.pop(); + } + s.pop(); // Pop the value from the main stack + } + + int top() { + return s.top(); // Return the top value of the main stack + } + + int max() { + return max_s.top(); // Return the top value of max_s, which is the maximum value in the stack + } + + bool empty() { + return s.empty(); // Check if the main stack is empty + } +}; From f37e145cb6d738baa81c42edc87d1dd575f20ceb Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sat, 6 May 2023 23:28:27 +0530 Subject: [PATCH 0980/1894] #703 solved --- Arrays/add_valid_palindrome.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Arrays/add_valid_palindrome.java diff --git a/Arrays/add_valid_palindrome.java b/Arrays/add_valid_palindrome.java new file mode 100644 index 00000000..6baec3ed --- /dev/null +++ b/Arrays/add_valid_palindrome.java @@ -0,0 +1,27 @@ +/* +Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. +Example 1: + +Input: s = "aba" +Output: true +*/ + +class Solution { + public boolean validPalindrome(String s) { + int i=0,j=s.length()-1; // initialize two pointers, i and j to the start and end of the string respectively + while(i Date: Sun, 7 May 2023 11:02:26 +0530 Subject: [PATCH 0981/1894] follow underscore naming convention --- ...ional-flag.cpp => dutch_national_flag.cpp} | 0 ...{Binary_search_arr.js => binary_search.js} | 58 +++++++++---------- ...cpp => search_in_rotated_sorted_array.cpp} | 0 ....java => kth_closest_point_to origin.java} | 0 Linked List/AddTwoNumbers | 55 ------------------ ...ist.cpp => linked_list_compute_middle.cpp} | 0 ...ist_in_Python.py => singly_linked_list.py} | 0 ...cate_value.js => first_duplicate_value.js} | 0 8 files changed, 29 insertions(+), 84 deletions(-) rename Arrays/{Dutch-national-flag.cpp => dutch_national_flag.cpp} (100%) rename Binary Search/{Binary_search_arr.js => binary_search.js} (97%) rename Binary Search/{searchInRotatedSortedArray.cpp => search_in_rotated_sorted_array.cpp} (100%) rename Dynamic Programming/{K_closest_point_to origin.java => kth_closest_point_to origin.java} (100%) delete mode 100644 Linked List/AddTwoNumbers rename Linked List/{middleOfTheLinkedList.cpp => linked_list_compute_middle.cpp} (100%) rename Linked List/{Singly_linked_list_in_Python.py => singly_linked_list.py} (100%) rename Searching/{linear_search_first_duplicate_value.js => first_duplicate_value.js} (100%) diff --git a/Arrays/Dutch-national-flag.cpp b/Arrays/dutch_national_flag.cpp similarity index 100% rename from Arrays/Dutch-national-flag.cpp rename to Arrays/dutch_national_flag.cpp diff --git a/Binary Search/Binary_search_arr.js b/Binary Search/binary_search.js similarity index 97% rename from Binary Search/Binary_search_arr.js rename to Binary Search/binary_search.js index c2d3d1a6..24a59582 100644 --- a/Binary Search/Binary_search_arr.js +++ b/Binary Search/binary_search.js @@ -1,30 +1,30 @@ -/** - * Finds the first and last occurrence of a target value in a sorted array. - * - * @param {number[]} N - The sorted array of numbers. - * @param {number} T - The target value to search for. - * @returns {number[]} An array containing the first and last index of the target value, or [-1,-1] if not found. - */ -const searchRange = function(N, T) { - // Helper function to perform binary search on the array - const find = (target, arr, left=0, right=arr.length) => { - while (left <= right) { - // Calculate the middle index - let mid = left + right >> 1; - // If the middle element is less than the target, move the left pointer to mid + 1 - if (arr[mid] < target) left = mid + 1; - // If the middle element is greater than or equal to the target, move the right pointer to mid - 1 - else right = mid - 1; - } - // Return the left pointer, which will be the index of the target or the insertion point if not found - return left; - }; - - // Find the leftmost index of the target value - let Tleft = find(T, N); - // If the target value is not found in the array, return [-1,-1] - if (N[Tleft] !== T) return [-1,-1]; - // Find the rightmost index of the target value - return [Tleft, find(T+1, N, Tleft) - 1]; - }; +/** + * Finds the first and last occurrence of a target value in a sorted array. + * + * @param {number[]} N - The sorted array of numbers. + * @param {number} T - The target value to search for. + * @returns {number[]} An array containing the first and last index of the target value, or [-1,-1] if not found. + */ +const searchRange = function(N, T) { + // Helper function to perform binary search on the array + const find = (target, arr, left=0, right=arr.length) => { + while (left <= right) { + // Calculate the middle index + let mid = left + right >> 1; + // If the middle element is less than the target, move the left pointer to mid + 1 + if (arr[mid] < target) left = mid + 1; + // If the middle element is greater than or equal to the target, move the right pointer to mid - 1 + else right = mid - 1; + } + // Return the left pointer, which will be the index of the target or the insertion point if not found + return left; + }; + + // Find the leftmost index of the target value + let Tleft = find(T, N); + // If the target value is not found in the array, return [-1,-1] + if (N[Tleft] !== T) return [-1,-1]; + // Find the rightmost index of the target value + return [Tleft, find(T+1, N, Tleft) - 1]; + }; \ No newline at end of file diff --git a/Binary Search/searchInRotatedSortedArray.cpp b/Binary Search/search_in_rotated_sorted_array.cpp similarity index 100% rename from Binary Search/searchInRotatedSortedArray.cpp rename to Binary Search/search_in_rotated_sorted_array.cpp diff --git a/Dynamic Programming/K_closest_point_to origin.java b/Dynamic Programming/kth_closest_point_to origin.java similarity index 100% rename from Dynamic Programming/K_closest_point_to origin.java rename to Dynamic Programming/kth_closest_point_to origin.java diff --git a/Linked List/AddTwoNumbers b/Linked List/AddTwoNumbers deleted file mode 100644 index d3848b20..00000000 --- a/Linked List/AddTwoNumbers +++ /dev/null @@ -1,55 +0,0 @@ -/* Name : Saishree Kouda -Github username : saishreekouda -Repository name : data-structures-and-algorithms -Problem : Add Two Numbers Linked List in C++ -Issue Number : #620 -Problem statement : Add Two Numbers4 - -Description: -You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. - -You may assume the two numbers do not contain any leading zero, except the number 0 itself. - -Example: -Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) -Output: 7 -> 0 -> 8 - -Constraints: -The number of nodes in each linked list is in the range [1, 100]. -0 <= Node.val <= 9 -It is guaranteed that the list represents a number that does not have leading zeros.*/ - -/*-----------------------------------------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------------------------------------------------------------------------------------------ */ - -class Solution { -public: -// Iterative approach - - /* ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - int c = 0; - ListNode newHead(0); - ListNode *t = &newHead; - while(c || l1 || l2) { - c += (l1? l1->val : 0) + (l2? l2->val : 0); - t->next = new ListNode(c%10); - t = t->next; - c /= 10; - if(l1) l1 = l1->next; - if(l2) l2 = l2->next; - } - return newHead.next; -} */ - -// Recursive approach -ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - if(!l1 && !l2) return NULL; - int c = (l1? l1->val:0) + (l2? l2->val:0); - ListNode *newHead = new ListNode(c%10), *next = l1? l1->next:NULL; - c /= 10; - if(next) next->val += c; - else if(c) next = new ListNode(c); - newHead->next = addTwoNumbers(l2? l2->next:NULL, next); - return newHead; -} - -}; \ No newline at end of file diff --git a/Linked List/middleOfTheLinkedList.cpp b/Linked List/linked_list_compute_middle.cpp similarity index 100% rename from Linked List/middleOfTheLinkedList.cpp rename to Linked List/linked_list_compute_middle.cpp diff --git a/Linked List/Singly_linked_list_in_Python.py b/Linked List/singly_linked_list.py similarity index 100% rename from Linked List/Singly_linked_list_in_Python.py rename to Linked List/singly_linked_list.py diff --git a/Searching/linear_search_first_duplicate_value.js b/Searching/first_duplicate_value.js similarity index 100% rename from Searching/linear_search_first_duplicate_value.js rename to Searching/first_duplicate_value.js From dbbbe7bdd39312360e9026090f01e39729557bad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 7 May 2023 11:13:44 +0530 Subject: [PATCH 0982/1894] cleanup and add good documentation --- Arrays/array_of_products.go | 99 +++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 49 deletions(-) diff --git a/Arrays/array_of_products.go b/Arrays/array_of_products.go index 8906b66c..e51a6941 100644 --- a/Arrays/array_of_products.go +++ b/Arrays/array_of_products.go @@ -1,60 +1,61 @@ -/** - * Given an array of integers A, find and return the product array of the same size where the ith element of the product array will be equal to the product of all the elements divided by the ith element of the array. - * - * Note: It is always possible to form the product array with integer (32 bit) values. Solve it without using the division operator. - * - * - * Input Format - * - * The only argument given is the integer array A. - * Output Format - * - * Return the product array. - * Constraints - * - * 2 <= length of the array <= 1000 - * 1 <= A[i] <= 10 - * For Example - * - * Input 1: - * A = [1, 2, 3, 4, 5] - * Output 1: - * [120, 60, 40, 30, 24] - * - * Input 2: - * A = [5, 1, 10, 1] - * Output 2: - * [10, 50, 5, 50] +/* + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith + element of the array. + + Note: It is always possible to form the product array with integer (32 bit) values. + Solve it without using the division operator. + + Input: [1, 2, 3, 4, 5] + Output : [120, 60, 40, 30, 24] + + Explanation: + This code implements a function called `ArrayOfProducts`, which takes an input array of integers and returns a + new array of the same size, where each element in the new array is the product of all the elements in the input + array except for the element at that index. + + To accomplish this, the function first creates a new result array with the same length as the input array. + Then, it initializes a `leftRunningProduct` variable to 1, and loops through the input array from left to right. + For each element in the input array, the function sets the corresponding element in the result array to the + current value of `leftRunningProduct`, and then updates `leftRunningProduct` to be the product of `leftRunningProduct` + and the current element in the input array. + + Next, the function initializes a `rightRunningProduct` variable to 1, and loops through the input array from right to left. + For each element in the input array, the function multiplies the corresponding element in the result array by `rightRunningProduct`, + and then updates `rightRunningProduct` to be the product of `rightRunningProduct` and the current element in the input array. + + Finally, the function returns the result array. + + This algorithm has a time complexity of O(n), where n is the length of the input array, since it loops through the input array + three times. It has a space complexity of O(n), since it creates a new result array of size n, and two additional integer variables. */ package main -import "fmt" +func ArrayOfProducts(array []int) []int { + // create two arrays to store the products of all elements to the left and right of each element in the input array + leftProduct := make([]int, len(array)) + rightProduct := make([]int, len(array)) - - -func ArrayOfProducts(Arr[]int) { - Result := make([]int, len(Arr)) - product := 1 - // fill left prefix product in result array - for i := 0; i < len(Arr); i++ { - Result[i] = product - product = product * Arr[i] + // compute the product of all elements to the left of each element in the input array + leftRunningProduct := 1 + for i := 0; i < len(array); i++ { + leftProduct[i] = leftRunningProduct + leftRunningProduct *= array[i] } - // fill right prefix product in result array - product = 1 - for i := len(Arr) - 1; i >= 0; i-- { - Result[i] = Result[i] * product - product = product * Arr[i] + // compute the product of all elements to the right of each element in the input array + rightRunningProduct := 1 + for i := len(array) - 1; i >= 0; i-- { + rightProduct[i] = rightRunningProduct + rightRunningProduct *= array[i] } - for i := 0; i < len(Arr); i++ { - fmt.Print(Result[i]," ") + // compute the product of all elements to the left and right of each element in the input array + for i := 0; i < len(array); i++ { + rightProduct[i] = leftProduct[i] * rightProduct[i] } -} - func main() { - Arr := []int{5, 1, 10, 1} - ArrayOfProducts(Arr) - } \ No newline at end of file + // return the array of products + return rightProduct +} From b9937dc4d0c902129b895662ebb87f6fa961f18e Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 7 May 2023 12:21:31 +0530 Subject: [PATCH 0983/1894] Update Substrings_with_1.py --- Math/Substrings_with_1.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Math/Substrings_with_1.py b/Math/Substrings_with_1.py index dd5ce9d3..f7981a13 100644 --- a/Math/Substrings_with_1.py +++ b/Math/Substrings_with_1.py @@ -14,16 +14,18 @@ ''' ----------------------------------------------------------------------------------------------//Python code begins here-------------------------------------------------------------------------------------------------------------------------------------- - class Solution: def numSub(self, s: str) -> int: - count = 0 - ans = 0 + count = 0 # count the number of consecutive ones + ans = 0 # variable to store the final answer for i in range(len(s)): if s[i] == '1': count += 1 else: + # calculate the number of possible substrings that can be formed + # from the current consecutive ones and add it to the final answer ans = (ans + (count*(count+1))//2) % (10**9 + 7) count = 0 + # handle the case when the string ends with consecutive ones ans = (ans + (count*(count+1))//2) % (10**9 + 7) return ans From bcce4df5490aa073f4fb1dff9659983ddd138d52 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 7 May 2023 12:22:51 +0530 Subject: [PATCH 0984/1894] Update Uniquedigits.cpp --- Math/Uniquedigits.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Math/Uniquedigits.cpp b/Math/Uniquedigits.cpp index cb97efbc..fa858eae 100644 --- a/Math/Uniquedigits.cpp +++ b/Math/Uniquedigits.cpp @@ -17,21 +17,20 @@ Finally, we return the value of ans. -------------------------------------------------------------------------//C++ code begins here---------------------------------------------------------------------------- - class Solution { public: int countNumbersWithUniqueDigits(int n) { if (n == 0) { - return 1; + return 1; // return 1 for n = 0 } - int ans = 10; - int unique_digits = 9; - int available_digits = 9; + int ans = 10; // start with 10 unique digits, as we can have numbers 0-9 + int unique_digits = 9; // start with 9 digits, as we cannot use 0 as first digit + int available_digits = 9; // remaining available digits while (n-- > 1 && available_digits > 0) { - unique_digits *= available_digits; - ans += unique_digits; - available_digits--; + unique_digits *= available_digits; // calculate number of unique numbers that can be formed + ans += unique_digits; // add number of unique numbers to the answer + available_digits--; // reduce available digits by 1 } - return ans; + return ans; // return final answer } }; From 278de83829045b119dc0e072ff2efb5a964e67a9 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 7 May 2023 12:33:34 +0530 Subject: [PATCH 0985/1894] Update Uniquedigits.cpp --- Math/Uniquedigits.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Math/Uniquedigits.cpp b/Math/Uniquedigits.cpp index fa858eae..30a2bb5c 100644 --- a/Math/Uniquedigits.cpp +++ b/Math/Uniquedigits.cpp @@ -13,8 +13,11 @@ Next, we enter a loop that runs n-1 times (since we have already considered the Finally, we return the value of ans. -*/ +The time complexity of this algorithm is O(n), where n is the input parameter representing the number of digits. + +The space complexity of this algorithm is O(1), as we are only using a constant amount of extra memory to store the variables ans, unique_digits, and available_digits, regardless of the input size. +*/ -------------------------------------------------------------------------//C++ code begins here---------------------------------------------------------------------------- class Solution { From a3b75ccbec85ff8ab2c4aa56a2a7859b9e5da975 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 7 May 2023 12:49:26 +0530 Subject: [PATCH 0986/1894] Update Uniquedigits.java --- Math/Uniquedigits.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Math/Uniquedigits.java b/Math/Uniquedigits.java index 019d4d26..258097a5 100644 --- a/Math/Uniquedigits.java +++ b/Math/Uniquedigits.java @@ -22,16 +22,16 @@ class Solution { public int countNumbersWithUniqueDigits(int n) { if (n == 0) { - return 1; + return 1; // return 1 for n = 0 } - int ans = 10; - int unique_digits = 9; - int available_digits = 9; + int ans = 10; // start with 10 unique digits, as we can have numbers 0-9 + int unique_digits = 9; // start with 9 digits, as we cannot use 0 as first digit + int available_digits = 9; // remaining available digits while (n-- > 1 && available_digits > 0) { - unique_digits *= available_digits; - ans += unique_digits; - available_digits--; + unique_digits *= available_digits; // calculate number of unique numbers that can be formed + ans += unique_digits; // add number of unique numbers to the answer + available_digits--; // reduce available digits by 1 } - return ans; + return ans; // return final answer } } From 36168b473e214dc7304fee2e05cb54d50ea30d92 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sun, 7 May 2023 13:07:47 +0530 Subject: [PATCH 0987/1894] #324 solved --- Arrays/add_reverse_integer.cpp | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Arrays/add_reverse_integer.cpp diff --git a/Arrays/add_reverse_integer.cpp b/Arrays/add_reverse_integer.cpp new file mode 100644 index 00000000..3a0f2e3f --- /dev/null +++ b/Arrays/add_reverse_integer.cpp @@ -0,0 +1,36 @@ +/* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. + +Assume the environment does not allow you to store 64-bit integers (signed or unsigned). + + + +Example 1: + +Input: x = 123 +Output: 321 +Example 2: + +Input: x = -123 +Output: -321 +*/ + + +class Solution { + public boolean validPalindrome(String s) { + int i=0,j=s.length()-1; // initialize two pointers, i and j to the start and end of the string respectively + while(i Date: Sun, 7 May 2023 13:21:01 +0530 Subject: [PATCH 0988/1894] changes made to #324 --- Arrays/add_reverse_integer.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Arrays/add_reverse_integer.cpp b/Arrays/add_reverse_integer.cpp index 3a0f2e3f..74d62a55 100644 --- a/Arrays/add_reverse_integer.cpp +++ b/Arrays/add_reverse_integer.cpp @@ -34,3 +34,15 @@ class Solution { } } + +/* + +APPROACH: The reverse function takes an integer as input and returns the reversed integer. The function first initializes a variable to store the reversed integer and then iterates over each digit of the input integer. In each iteration, the function extracts the rightmost digit of the input integer, checks if multiplying the reversed integer by 10 and adding the rightmost digit will cause integer overflow or underflow, adds the rightmost digit to the reversed integer, and removes the rightmost digit from the input integer. Finally, the function returns the reversed integer. + +Time Complexity: +The time complexity of the reverse function is O(log(x)), where x is the input integer. This is because the function needs to iterate over each digit of the input integer, which is proportional to the logarithm of the integer. + +Space Complexity: +The space complexity of the reverse function is O(1), because it only uses a constant amount of additional space to store the reversed integer and the remainder. + +*/ From 72c3ff85b2bcb7cb18859312bd217202b9ad3be4 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 7 May 2023 15:09:50 +0530 Subject: [PATCH 0989/1894] Update Uniquedigits.java --- Math/Uniquedigits.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Math/Uniquedigits.java b/Math/Uniquedigits.java index 258097a5..aa1b7fc2 100644 --- a/Math/Uniquedigits.java +++ b/Math/Uniquedigits.java @@ -13,6 +13,12 @@ Finally, we return the value of ans. +The time complexity of the given code is O(n), where n is the input parameter, because the loop runs n-1 times. + +The space complexity is O(1), because the amount of memory used by the algorithm does not depend on the size of the input n. The algorithm only uses a few constant amount of variables for computation, such as ans, unique_digits and available_digits. + +Therefore, the time complexity of the code is linear and the space complexity is constant. + */ From 278dbd89433aadbfcea653ceed6f52b23cb4a461 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 7 May 2023 15:54:47 +0530 Subject: [PATCH 0990/1894] Search insert position added --- Binary Search/search_insert_position.js | 62 +++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Binary Search/search_insert_position.js diff --git a/Binary Search/search_insert_position.js b/Binary Search/search_insert_position.js new file mode 100644 index 00000000..0b15664f --- /dev/null +++ b/Binary Search/search_insert_position.js @@ -0,0 +1,62 @@ +// https://leetcode.com/problems/search-insert-position/description/ + +/* + +Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. + +You must write an algorithm with O(log n) runtime complexity. + +Example 1: + +Input: nums = [1,3,5,6], target = 5 +Output: 2 +Example 2: + +Input: nums = [1,3,5,6], target = 2 +Output: 1 +Example 3: + +Input: nums = [1,3,5,6], target = 7 +Output: 4 + +*/ + +function findSearchPosition(nums, target) { + let startIndex = 0; + let endIndex = nums.length - 1; + + while (startIndex <= endIndex) { + const midIndex = startIndex + Math.floor((endIndex - startIndex) / 2); + + console.log(startIndex, endIndex, midIndex); + + if (nums[midIndex] === target) { + return midIndex; + } + + if (startIndex === endIndex || startIndex + 1 === endIndex) { + // If element at start index is greater then target then target then start index will be assigned to target + if (nums[startIndex] > target) { + return startIndex; + // if target is greater then end index element then end index + 1 will be assigned to target + } else if (nums[endIndex] < target) { + return endIndex + 1; + } else { + return startIndex + 1; + } + } + + if (nums[midIndex] < target) { + startIndex = midIndex + 1; + } else { + endIndex = midIndex - 1; + } + } +} + +//driver code +var nums = [1, 3, 5, 6]; +console.log(findSearchPosition(nums, 8)); + +//Input: nums = [1,3,5,6], target = 8 +// Output: 4 From d0f8700605ff2cef0fa637ea23ac778905286ad9 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 7 May 2023 16:27:29 +0530 Subject: [PATCH 0991/1894] perfect number after square root added --- Math/sqrt(x).js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Math/sqrt(x).js diff --git a/Math/sqrt(x).js b/Math/sqrt(x).js new file mode 100644 index 00000000..f3f91e2a --- /dev/null +++ b/Math/sqrt(x).js @@ -0,0 +1,20 @@ +/* +https://leetcode.com/problems/sqrtx/description/ +Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. + +Input: x = 4 +Output: 2 +Explanation: The square root of 4 is 2, so we return 2. + +Input: x = 8 +Output: 2 +Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. + +*/ + +function sqrt(x) { + return Math.floor(Math.sqrt(x)); +} + +// Driver code +console.log(4); From 4ac2f9364ae1a2f3d0312f36ba0c7ea22eaddf90 Mon Sep 17 00:00:00 2001 From: Alaka A J Date: Sun, 7 May 2023 20:32:24 +0530 Subject: [PATCH 0992/1894] Linked List: Find Middle of the Linked List in Java #361 --- Linked List/MiddleOfLinkedList.java | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Linked List/MiddleOfLinkedList.java diff --git a/Linked List/MiddleOfLinkedList.java b/Linked List/MiddleOfLinkedList.java new file mode 100644 index 00000000..613b597e --- /dev/null +++ b/Linked List/MiddleOfLinkedList.java @@ -0,0 +1,46 @@ +/* QUESTION and SAMPLE I/O + + Given the head of a singly linked list, return the middle node of the linked list. + If there are two middle nodes, return the second middle node. + + Sample Input = [1,2,3,4,5] + Sample Output = 3 + + APPROACH and EXPLANATION + + This program is done using two pointers: slow pointer and fast pointer. + * Both pointer starts from the head node. + * Slow pointer moves one step at a time. + * Fast pointer moves two steps at a time. + * As the fast pointer reaches the end, slow pointer will be at the middle of the linked list. + * Accessing the slow pointer's value for 'val' will give you the value for the middle element of linked list. + + + Time Complexity: O(n) + Space Complexity: O(1) + + */ + + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ + +class Solution { + public ListNode middleNode(ListNode head) { + ListNode slow_pointer = head; //initialize slow pointer + ListNode fast_pointer = head; //initialize fast pointer + while(fast_pointer!=null && fast_pointer.next!=null){ + slow_pointer = slow_pointer.next; //moves to next node + fast_pointer = fast_pointer.next.next; //moves two nodes forward + } + return slow_pointer; + } +} \ No newline at end of file From 63ffdcecba6799fcd01b13edcaf351d659b209b6 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sun, 7 May 2023 21:20:04 +0530 Subject: [PATCH 0993/1894] #647 solved --- Arrays/valid_palindrome.java | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Arrays/valid_palindrome.java diff --git a/Arrays/valid_palindrome.java b/Arrays/valid_palindrome.java new file mode 100644 index 00000000..ca3e3078 --- /dev/null +++ b/Arrays/valid_palindrome.java @@ -0,0 +1,47 @@ +/* +Two Pointers: Check whether a given string is a Valid Palindrome in Java +*/ + + + + +public static boolean isPalindrome(String str) +{ + // initialize startIdx to 0 and endIdx to the last index in the string + int startIdx = 0; + int endIdx = str.length() - 1; + + // loop through the string while the start index is less than the end index + while(startIdx < endIdx) + { + // get the characters at the start and end indices + char start = str.charAt(startIdx); + char end = str.charAt(endIdx); + + // if the lowercase versions of the characters do not match, return false + if(Character.toLowerCase(start) != Character.toLowerCase(end)) + return false; + + // increment the start index and decrement the end index + startIdx += 1; + endIdx -= 1; + } + + // if the loop completes without returning false, the string is a palindrome so return true + return true; +} + + +/* EXPLAINATION: +The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. + +The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. + +Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. + +If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. + +The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. + +The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. +*/ From 198addae11030e1c6b9e211013167a409a5dc682 Mon Sep 17 00:00:00 2001 From: Shivanand Patil <70444072+shivanand-patil@users.noreply.github.com> Date: Sun, 7 May 2023 21:25:40 +0530 Subject: [PATCH 0994/1894] Delete valid_palindrome.java --- Arrays/valid_palindrome.java | 47 ------------------------------------ 1 file changed, 47 deletions(-) delete mode 100644 Arrays/valid_palindrome.java diff --git a/Arrays/valid_palindrome.java b/Arrays/valid_palindrome.java deleted file mode 100644 index ca3e3078..00000000 --- a/Arrays/valid_palindrome.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -Two Pointers: Check whether a given string is a Valid Palindrome in Java -*/ - - - - -public static boolean isPalindrome(String str) -{ - // initialize startIdx to 0 and endIdx to the last index in the string - int startIdx = 0; - int endIdx = str.length() - 1; - - // loop through the string while the start index is less than the end index - while(startIdx < endIdx) - { - // get the characters at the start and end indices - char start = str.charAt(startIdx); - char end = str.charAt(endIdx); - - // if the lowercase versions of the characters do not match, return false - if(Character.toLowerCase(start) != Character.toLowerCase(end)) - return false; - - // increment the start index and decrement the end index - startIdx += 1; - endIdx -= 1; - } - - // if the loop completes without returning false, the string is a palindrome so return true - return true; -} - - -/* EXPLAINATION: -The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. - -The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. - -Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. - -If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. - -The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. - -The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. -*/ From ece153f65a9912733073c73c7726a4d33fade5ff Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sun, 7 May 2023 21:27:39 +0530 Subject: [PATCH 0995/1894] #647 solved --- Arrays/valid_palindrome.java | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Arrays/valid_palindrome.java diff --git a/Arrays/valid_palindrome.java b/Arrays/valid_palindrome.java new file mode 100644 index 00000000..ca3e3078 --- /dev/null +++ b/Arrays/valid_palindrome.java @@ -0,0 +1,47 @@ +/* +Two Pointers: Check whether a given string is a Valid Palindrome in Java +*/ + + + + +public static boolean isPalindrome(String str) +{ + // initialize startIdx to 0 and endIdx to the last index in the string + int startIdx = 0; + int endIdx = str.length() - 1; + + // loop through the string while the start index is less than the end index + while(startIdx < endIdx) + { + // get the characters at the start and end indices + char start = str.charAt(startIdx); + char end = str.charAt(endIdx); + + // if the lowercase versions of the characters do not match, return false + if(Character.toLowerCase(start) != Character.toLowerCase(end)) + return false; + + // increment the start index and decrement the end index + startIdx += 1; + endIdx -= 1; + } + + // if the loop completes without returning false, the string is a palindrome so return true + return true; +} + + +/* EXPLAINATION: +The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. + +The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. + +Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. + +If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. + +The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. + +The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. +*/ From 39b227994a936a35e29600c36507b480fb97bb83 Mon Sep 17 00:00:00 2001 From: Faizan Siddiqui Date: Sun, 7 May 2023 22:08:12 +0530 Subject: [PATCH 0996/1894] Added python code for spiral matrix --- 2D Arrays (Matrix)/spiral_traverse.py | 90 +++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 2D Arrays (Matrix)/spiral_traverse.py diff --git a/2D Arrays (Matrix)/spiral_traverse.py b/2D Arrays (Matrix)/spiral_traverse.py new file mode 100644 index 00000000..29b02024 --- /dev/null +++ b/2D Arrays (Matrix)/spiral_traverse.py @@ -0,0 +1,90 @@ +##### LEETCODE 54. Spiral Matrix #### + +##### INPUT OUTPUT ##### + +# Given an m x n matrix, return all elements of the matrix in spiral order. +# Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +# Output: [1,2,3,6,9,8,7,4,5] +# Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] +# Output: [1,2,3,4,8,12,11,10,9,5,6,7] +# Write python code along with explanation and comments use meaningful variables + +##### EXPLAINATION ##### + +# The given problem statement is to return all elements of the matrix in spiral order. We can start by defining the four boundaries of the matrix - top, bottom, left and right. We can then traverse the matrix in a spiral order by following these four steps: + +# Traverse from left to right along the top boundary +# Traverse from top to bottom along the right boundary +# Traverse from right to left along the bottom boundary +# Traverse from bottom to top along the left boundary +# After each traversal, we need to update the corresponding boundary and change the direction of traversal. + +# We can implement this algorithm using a while loop that runs as long as the top boundary is less than or equal to the bottom boundary and the left boundary is less than or equal to the right boundary. Within the while loop, we can use an if-else ladder to check the current direction of traversal and perform the corresponding traversal along the boundary. + +# Finally, we can return the result list containing all the spiral order elements of the matrix. + + +#### DRY RUN: #### + +# Initially, we have the matrix: +# 1 2 3 +# 4 5 6 +# 7 8 9 + +# We initialize the variables top, bottom, left, and right to 0, 2, 0, and 2 respectively. We also set the direction variable to 0. +# Now, we enter the while loop since top<=bottom and left<=right. +# In the first iteration of the while loop, direction=0 means we need to traverse from left to right along the top boundary. +# We iterate the for loop from left=0 to right=2 and append the elements 1, 2, 3 to the result list. After this, we increment top by 1 to mark that the top boundary is now done. +# The result list now contains [1, 2, 3]. +# In the second iteration of the while loop, direction=1 means we need to traverse from top to bottom along the right boundary. +# We iterate the for loop from top=1 to bottom=2 and append the elements 6, 9 to the result list. After this, we decrement right by 1 to mark that the right boundary is now done. +# The result list now contains [1, 2, 3, 6, 9]. +# In the third iteration of the while loop, direction=2 means we need to traverse from right to left along the bottom boundary. +# We iterate the for loop from right=1 to left=0 and append the elements 8, 7 to the result list. After this, we decrement bottom by 1 to mark that the bottom boundary is now done. +# The result list now contains [1, 2, 3, 6, 9, 8, 7]. +# In the fourth iteration of the while loop, direction=3 means we need to traverse from bottom to top along the left boundary. +# We iterate the for loop from bottom=1 to top=1 and append the element 4 and 5 to the result list. After this, we increment left by 1 to mark that the left boundary is now done. +# The result list now contains [1, 2, 3, 6, 9, 8, 7, 4, 5]. +# Now, we have completed one full spiral traversal of the matrix. The direction variable is updated as (0+1)%4=1 which sets it to 1 for the next iteration. +# We continue with the while loop since top<=bottom and left<=right. In the second iteration, the process continues in the same way as described above until all elements of the matrix are visited. +# Finally, the function returns the result list containing all the spiral order elements of the matrix. + +def spiralOrder(matrix): + # Initialize variables to keep track of indices and boundaries + top, bottom = 0, len(matrix) - 1 + left, right = 0, len(matrix[0]) - 1 + direction = 0 # 0 = right, 1 = down, 2 = left, 3 = up + + # Initialize an empty result list to store the spiral order elements + result = [] + + while top <= bottom and left <= right: + if direction == 0: + # Traverse right + for i in range(left, right+1): + result.append(matrix[top][i]) + top += 1 + elif direction == 1: + # Traverse down + for i in range(top, bottom+1): + result.append(matrix[i][right]) + right -= 1 + elif direction == 2: + # Traverse left + for i in range(right, left-1, -1): + result.append(matrix[bottom][i]) + bottom -= 1 + else: + # Traverse up + for i in range(bottom, top-1, -1): + result.append(matrix[i][left]) + left += 1 + + # Update direction after completing one full traversal + direction = (direction + 1) % 4 + + return result + + +matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +print(spiralOrder(matrix)) From bd7c7ecacd8e0f7fc0c30b74c83db418a1d475e1 Mon Sep 17 00:00:00 2001 From: Mujtaba Hussain <67089235+Hussain15527@users.noreply.github.com> Date: Sun, 7 May 2023 23:04:40 +0530 Subject: [PATCH 0997/1894] Create Number of Substrings With Only 1s.js --- Math/Number of Substrings With Only 1s.js | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/Number of Substrings With Only 1s.js diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js new file mode 100644 index 00000000..cafc74a1 --- /dev/null +++ b/Math/Number of Substrings With Only 1s.js @@ -0,0 +1,43 @@ + +/* + PROBLEM STATEMENT: + + Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. + + EXAMPLE 1: + Input: s = "0110111" + Output: 9 + Explanation: There are 9 substring in total with only 1's characters. + "1" -> 5 times. + "11" -> 3 times. + "111" -> 1 time. + EXAMPLE 2: + Input: s = "101" + Output: 2 + Explanation: Substring "1" is shown 2 times in s. + + CONSTRAINT: + Constraints: + 1 <= s.length <= 105 + s[i] is either '0' or '1'. +*/ + + +var numSub = function(s) { + // count stores the current number of consecutive 1's + var count=0; + // answer storese the final answer to be returned + var answer=0; + // we mod the sum at each step so that they don't overflow + const mod=1000000007; + // iterate the entire string + for(let i=0;i Date: Sun, 7 May 2023 23:25:01 +0530 Subject: [PATCH 0998/1894] added comments and explanation --- Binary Search/search_insert_position.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Binary Search/search_insert_position.js b/Binary Search/search_insert_position.js index 0b15664f..da532a62 100644 --- a/Binary Search/search_insert_position.js +++ b/Binary Search/search_insert_position.js @@ -19,6 +19,12 @@ Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4 +Explanation: + In a given sorted array this code uses binary search where we divide the array into two parts and check if the number is present then we return the index of element otherwise we return what should be index of that target in the given array. + The loops iterates until the start index and end index of array is same. + We calculate the middle index on each iteration of loop as start index / end index might change on the basis of last iteration result. + If the middle index element is the target element then we return middle index otherwise we loop through the entire array until last one or two elements left. + On the basis of last one or two elements we decide what is going to be the index of target in the array. */ function findSearchPosition(nums, target) { @@ -28,12 +34,12 @@ function findSearchPosition(nums, target) { while (startIndex <= endIndex) { const midIndex = startIndex + Math.floor((endIndex - startIndex) / 2); - console.log(startIndex, endIndex, midIndex); - + // Base case if middle index element is our target then we will return the middle index if (nums[midIndex] === target) { return midIndex; } + // In case if element is not present in the given array then in the final iteration when only last one or two elements are remaining we will check what should be our target number index in the given array if (startIndex === endIndex || startIndex + 1 === endIndex) { // If element at start index is greater then target then target then start index will be assigned to target if (nums[startIndex] > target) { @@ -46,6 +52,7 @@ function findSearchPosition(nums, target) { } } + // if the target element is greater then the middle index element then we will change the start index next to middle index otherwise we will change last index to middle index - 1 if (nums[midIndex] < target) { startIndex = midIndex + 1; } else { From 48fcd385d6be56e62ebe9431f52daf0cb6200611 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Sun, 7 May 2023 23:45:53 +0530 Subject: [PATCH 0999/1894] sqrt removed --- Math/sqrt(x).js | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 Math/sqrt(x).js diff --git a/Math/sqrt(x).js b/Math/sqrt(x).js deleted file mode 100644 index f3f91e2a..00000000 --- a/Math/sqrt(x).js +++ /dev/null @@ -1,20 +0,0 @@ -/* -https://leetcode.com/problems/sqrtx/description/ -Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well. - -Input: x = 4 -Output: 2 -Explanation: The square root of 4 is 2, so we return 2. - -Input: x = 8 -Output: 2 -Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. - -*/ - -function sqrt(x) { - return Math.floor(Math.sqrt(x)); -} - -// Driver code -console.log(4); From 3b6e940572340485435cd3521c053ec470091730 Mon Sep 17 00:00:00 2001 From: Shivanand Patil <70444072+shivanand-patil@users.noreply.github.com> Date: Sun, 7 May 2023 23:48:58 +0530 Subject: [PATCH 1000/1894] Update valid_palindrome.java --- Arrays/valid_palindrome.java | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/Arrays/valid_palindrome.java b/Arrays/valid_palindrome.java index ca3e3078..0f4361b4 100644 --- a/Arrays/valid_palindrome.java +++ b/Arrays/valid_palindrome.java @@ -3,6 +3,20 @@ */ +/* EXPLAINATION: +The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. + +The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. + +Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. + +If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. + +The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. + +The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. +*/ + public static boolean isPalindrome(String str) @@ -30,18 +44,3 @@ public static boolean isPalindrome(String str) // if the loop completes without returning false, the string is a palindrome so return true return true; } - - -/* EXPLAINATION: -The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. - -The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. - -Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. - -If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. - -The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. - -The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. -*/ From e61a26f81e85cba32444f45271481a7d78beec94 Mon Sep 17 00:00:00 2001 From: Shivanand Patil <70444072+shivanand-patil@users.noreply.github.com> Date: Sun, 7 May 2023 23:50:08 +0530 Subject: [PATCH 1001/1894] Update add_reverse_integer.cpp --- Arrays/add_reverse_integer.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/Arrays/add_reverse_integer.cpp b/Arrays/add_reverse_integer.cpp index 74d62a55..a735f72d 100644 --- a/Arrays/add_reverse_integer.cpp +++ b/Arrays/add_reverse_integer.cpp @@ -14,6 +14,17 @@ Input: x = -123 Output: -321 */ +/* + +APPROACH: The reverse function takes an integer as input and returns the reversed integer. The function first initializes a variable to store the reversed integer and then iterates over each digit of the input integer. In each iteration, the function extracts the rightmost digit of the input integer, checks if multiplying the reversed integer by 10 and adding the rightmost digit will cause integer overflow or underflow, adds the rightmost digit to the reversed integer, and removes the rightmost digit from the input integer. Finally, the function returns the reversed integer. + +Time Complexity: +The time complexity of the reverse function is O(log(x)), where x is the input integer. This is because the function needs to iterate over each digit of the input integer, which is proportional to the logarithm of the integer. + +Space Complexity: +The space complexity of the reverse function is O(1), because it only uses a constant amount of additional space to store the reversed integer and the remainder. + +*/ class Solution { public boolean validPalindrome(String s) { @@ -33,16 +44,3 @@ class Solution { return true; // if the loop completes without returning false, the substring is a palindrome } } - - -/* - -APPROACH: The reverse function takes an integer as input and returns the reversed integer. The function first initializes a variable to store the reversed integer and then iterates over each digit of the input integer. In each iteration, the function extracts the rightmost digit of the input integer, checks if multiplying the reversed integer by 10 and adding the rightmost digit will cause integer overflow or underflow, adds the rightmost digit to the reversed integer, and removes the rightmost digit from the input integer. Finally, the function returns the reversed integer. - -Time Complexity: -The time complexity of the reverse function is O(log(x)), where x is the input integer. This is because the function needs to iterate over each digit of the input integer, which is proportional to the logarithm of the integer. - -Space Complexity: -The space complexity of the reverse function is O(1), because it only uses a constant amount of additional space to store the reversed integer and the remainder. - -*/ From d1333f7520e74d0423221fc15f42cee392abb430 Mon Sep 17 00:00:00 2001 From: Niraj Date: Mon, 8 May 2023 12:50:03 +0530 Subject: [PATCH 1002/1894] #1011 largest rectangle containing only 1's and return its area in Python --- .../Largest_Rectangle_In_Binary_Matrix.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py new file mode 100644 index 00000000..e030b8c3 --- /dev/null +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py @@ -0,0 +1,43 @@ +#by TheCodeVenturer[Niraj Modi] +class Solution: + def maxArea(self,matrix, rows, cols): + shiftRow = [0]*cols + sol=0 + for row in matrix: + for i,ele in enumerate(row): + if ele==1: + shiftRow[i]+=1 + else: + shiftRow[i]=0 + st = [] + for i in range(cols+1): + while(len(st)>0 and(i==cols or shiftRow[st[-1]]>=shiftRow[i])): + height = shiftRow[st[-1]] + st.pop() + width = i + if(len(st)>0): + width = i - st[-1] - 1 + sol = max(height*width,sol) + st.append(i) + return sol + +if __name__ == '__main__': + t=int(input()) + for _ in range(t): + R,C = map(int, input().strip().split()) + A = [] + for i in range(R): + line = [int(x) for x in input().strip().split()] + A.append(line) + print(Solution().maxArea(A, R, C)) +""" +Input Format +1 No.Of Test Cases +4 4 rows,columns +next rows*columns lines +0 1 1 0 +1 1 1 1 +1 1 1 1 +1 1 0 0 +""" + From fed1ce59e29fe8556097e684f65e4ac9cde96394 Mon Sep 17 00:00:00 2001 From: Niraj Date: Mon, 8 May 2023 12:55:24 +0530 Subject: [PATCH 1003/1894] largest rectangle in binary matrix Updated in python --- Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py index e030b8c3..b1c077b4 100644 --- a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py @@ -1,4 +1,5 @@ -#by TheCodeVenturer[Niraj Modi] +# Dynamic Programming: Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area in Python #1011 +#Program Author : TheCodeVenturer [Niraj Modi] class Solution: def maxArea(self,matrix, rows, cols): shiftRow = [0]*cols From 8d6d520d712c1d06b35c9ea5ee386d9f7eec1f9a Mon Sep 17 00:00:00 2001 From: Niraj Date: Mon, 8 May 2023 13:12:15 +0530 Subject: [PATCH 1004/1894] #1115 Array: Merge intervals in Python --- Arrays/Merge_Intervals.py | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Arrays/Merge_Intervals.py diff --git a/Arrays/Merge_Intervals.py b/Arrays/Merge_Intervals.py new file mode 100644 index 00000000..c4db6bf1 --- /dev/null +++ b/Arrays/Merge_Intervals.py @@ -0,0 +1,44 @@ +# Array: Merge intervals in Python #1115 +#Program Author : TheCodeVenturer [Niraj Modi] + +class Solution: + def mergeIntervals(self, Intervals): + Intervals.sort() #Sorting the intervals to make the starting time in increasing order to maintain the sequence + sol = [] + start = Intervals[0][0] + end = Intervals[0][1] + for [l, u] in Intervals: + if (l > end): + sol.append([start, end]) + start, end = l, u + else: + end = max(end, u) + sol.append([start, end]) + return sol + + +if __name__ == '__main__': + T = int(input()) + for i in range(T): + n = int(input()) + a = list(map(int, input().strip().split())) + Intervals = [] + j = 0 + for i in range(n): + x = a[j] + j += 1 + y = a[j] + j += 1 + Intervals.append([x, y]) + obj = Solution() + ans = obj.mergeIntervals(Intervals) + for i in ans: + for j in i: + print(j, end=" ") + print() + +''' +Input Format +t=1 No.of Test Cases +Intervals = 2 3 1 2 6 8 9 10 A 2-d Array [[2,3],[1,2],[6,8],[9,10]] +''' \ No newline at end of file From bcc66b7b7e981125a7a3c18f54fce81d5c90a86f Mon Sep 17 00:00:00 2001 From: Faizan Siddiqui Date: Mon, 8 May 2023 19:50:55 +0530 Subject: [PATCH 1005/1894] Go code for insert interval leetcode 57 --- Arrays/insert_interval.go | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Arrays/insert_interval.go diff --git a/Arrays/insert_interval.go b/Arrays/insert_interval.go new file mode 100644 index 00000000..bf29328d --- /dev/null +++ b/Arrays/insert_interval.go @@ -0,0 +1,90 @@ +// 57. Insert Interval +// You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. +// Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). +// Return intervals after the insertion. +// Example 1: +// Input: intervals = [[1,3],[6,9]], newInterval = [2,5] +// Output: [[1,5],[6,9]] +// Example 2: +// Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] +// Output: [[1,2],[3,10],[12,16]] +// Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. + +// CODE EXPLAINATION WITH DRY RUN: +// The insert function takes in two inputs: an array of non-overlapping intervals represented as an array of arrays of integers (intervals), and a single interval represented as an array of integers (newInterval). The function returns the updated intervals after inserting the new interval such that the intervals remain sorted by the start value and do not overlap. + +// The function first initializes some variables: + +// n: the new interval +// j: the array of existing intervals +// i: a counter variable initialized to 0 +// m: the starting point of the new interval; initially set to the starting point of n +// m1: the ending point of the new interval; initially set to the ending point of n +// The function then enters a loop that iterates through each interval in the array of existing intervals j. For each iteration, it checks if the new interval overlaps with the current interval. An overlap occurs if any of the following conditions are met: + +// The starting point of the new interval is between the starting and ending points of the current interval +// The ending point of the new interval is between the starting and ending points of the current interval +// The new interval completely engulfs the current interval +// If an overlap is detected, the function updates the starting point and ending point of the new interval (m and m1) based on the starting and ending points of the current interval (j[i][0] and j[i][1], respectively). It then removes the current interval from the array of existing intervals j using the append function with a slice operation that excludes the current element (append(j[:i], j[i+1:]...)) and decrements the counter variable i so that the loop will consider the next interval after removing the current one. + +// After iterating through all intervals in j, the function appends the new interval represented by [m, m1] to the end of the j array using the append function. Finally, the intervals in the array are sorted based on their starting points using two nested loops that swap elements if they are not in order. + +// Now, let's do a dry run of the example input and output: + +// Input: + +// intervals = [[1,3],[6,9]] +// newInterval = [2,5] +// The initial values of variables are: + +// n = [2,5] +// j = [[1,3],[6,9]] +// i = 0 +// m = 2 +// m1 = 5 +// In the first iteration of the loop, the current interval is [1,3]. Since n overlaps with this interval, m is updated to 1 and m1 is updated to 5. The current interval is removed from j, which becomes [[6,9]]. The counter variable i is decremented to account for the removal, making its value -1. In the next iteration of the loop, i is incremented to 0, so the current interval is [6,9]. Since there is no overlap between n and this interval, nothing happens. The loop exits, and the updated j array is [[1,5],[6,9]], which matches the expected output. + +// Thus, the function correctly inserts the new interval and sorts the resulting array. + +package main + +import "fmt" + +func insert(intervals [][]int, newInterval []int) [][]int { + n := newInterval + j := intervals + i := 0 + m := n[0] // Initialize starting point of the interval to be inserted + m1 := n[1] // Initialize ending point of the interval to be inserted + + for i < len(j) { + if n[0] >= j[i][0] && n[0] <= j[i][1] || n[1] >= j[i][0] && n[1] <= j[i][1] || n[0] <= j[i][0] && n[1] >= j[i][1] { + if j[i][0] < m { + m = j[i][0] + } + if j[i][1] > m1 { + m1 = j[i][1] + } + j = append(j[:i], j[i+1:]...) + i-- + } + i++ + } + s1 := []int{m, m1} + j = append(j, s1) + for i := 0; i < len(j); i++ { + for k := i + 1; k < len(j); k++ { + if j[i][0] > j[k][0] { + j[i], j[k] = j[k], j[i] + } + } + } + return j +} + +func main() { + intervals := [][]int{{1, 3}, {6, 9}} + newInterval := []int{2, 5} + result := insert(intervals, newInterval) + fmt.Println(result) +} From 13d3c19485563aa00968b01e8bcac5ac75e539ea Mon Sep 17 00:00:00 2001 From: Faizan Siddiqui Date: Mon, 8 May 2023 19:52:51 +0530 Subject: [PATCH 1006/1894] Leetcode 57 insert interval go code --- Arrays/{insert_interval.go => insert_intervals.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{insert_interval.go => insert_intervals.go} (100%) diff --git a/Arrays/insert_interval.go b/Arrays/insert_intervals.go similarity index 100% rename from Arrays/insert_interval.go rename to Arrays/insert_intervals.go From 3846b7f8bc271ce55dfee3e8ffd520f12912100f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 8 May 2023 22:51:53 +0530 Subject: [PATCH 1007/1894] add validate bst --- Trees/Binary Search Trees/validate_bst.go | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Trees/Binary Search Trees/validate_bst.go diff --git a/Trees/Binary Search Trees/validate_bst.go b/Trees/Binary Search Trees/validate_bst.go new file mode 100644 index 00000000..32513f2e --- /dev/null +++ b/Trees/Binary Search Trees/validate_bst.go @@ -0,0 +1,49 @@ +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) + and returns a boolean representing whether the BST is valid. + Sample Input : + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 + Output : True + +*/ +package main + +import "math" + +type BST struct { + Value int + + Left *BST + Right *BST +} + +// ValidateBst is a method of BST that checks if the binary search tree is valid +func (tree *BST) ValidateBst() bool { + return tree.validateBST(math.MinInt32, math.MaxInt32) +} + +// validateBST is a recursive helper function that checks if the binary search tree is valid +// min is the minimum value that a node in the subtree rooted at this node can have +// max is the maximum value that a node in the subtree rooted at this node can have +func (tree *BST) validateBST(min, max int) bool { + // if the current node's value is outside the allowed range, then the tree is invalid + if tree.Value < min || tree.Value >= max { + return false + } + // recursively check the left subtree, making sure all values are less than the current node's value + if tree.Left != nil && !tree.Left.validateBST(min, tree.Value) { + return false + } + // recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if tree.Right != nil && !tree.Right.validateBST(tree.Value, max) { + return false + } + // if we reach this point, then the tree is valid + return true +} From d697fd95cccdea1cc596cf5b8b6cee87a6eb6e40 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 8 May 2023 22:52:37 +0530 Subject: [PATCH 1008/1894] add explanation --- Trees/Binary Search Trees/validate_bst.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Trees/Binary Search Trees/validate_bst.go b/Trees/Binary Search Trees/validate_bst.go index 32513f2e..5a88cbe8 100644 --- a/Trees/Binary Search Trees/validate_bst.go +++ b/Trees/Binary Search Trees/validate_bst.go @@ -11,6 +11,26 @@ 1 14 Output : True + Explanation: + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can + point to other BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating + whether the tree is a valid BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree + is a valid BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum + and maximum values that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined + by the min and max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left + and right child nodes to check whether their values are within their valid ranges. The valid range for the + left child node is defined by the minimum value and the parent node's value, while the valid range for the + right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree + is a valid BST. + */ package main From af81e8479b5ee208e1d2476bc20f47332df6d6c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 8 May 2023 22:52:56 +0530 Subject: [PATCH 1009/1894] add time and space --- Trees/Binary Search Trees/validate_bst.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Trees/Binary Search Trees/validate_bst.go b/Trees/Binary Search Trees/validate_bst.go index 5a88cbe8..842f8acd 100644 --- a/Trees/Binary Search Trees/validate_bst.go +++ b/Trees/Binary Search Trees/validate_bst.go @@ -31,6 +31,8 @@ If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST + */ package main From 9af169ec216c99fcf79a6fa3ac47b76f8d53e57b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 8 May 2023 22:59:33 +0530 Subject: [PATCH 1010/1894] follow naming convention --- ...{FindMiddleLinkedList.java => linked_list_compute_middle.java} | 0 .../{countNumbersWithUniqueDigits.cpp => count_unique_digits.cpp} | 0 Math/{count_unique_digits,go => count_unique_digits.go} | 0 Math/{Palindrome_Number_Java.java => palindrome_number.java} | 0 Math/{Substrings_with_1.py => substrings_with_1s.py} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename Linked List/{FindMiddleLinkedList.java => linked_list_compute_middle.java} (100%) rename Math/{countNumbersWithUniqueDigits.cpp => count_unique_digits.cpp} (100%) rename Math/{count_unique_digits,go => count_unique_digits.go} (100%) rename Math/{Palindrome_Number_Java.java => palindrome_number.java} (100%) rename Math/{Substrings_with_1.py => substrings_with_1s.py} (100%) diff --git a/Linked List/FindMiddleLinkedList.java b/Linked List/linked_list_compute_middle.java similarity index 100% rename from Linked List/FindMiddleLinkedList.java rename to Linked List/linked_list_compute_middle.java diff --git a/Math/countNumbersWithUniqueDigits.cpp b/Math/count_unique_digits.cpp similarity index 100% rename from Math/countNumbersWithUniqueDigits.cpp rename to Math/count_unique_digits.cpp diff --git a/Math/count_unique_digits,go b/Math/count_unique_digits.go similarity index 100% rename from Math/count_unique_digits,go rename to Math/count_unique_digits.go diff --git a/Math/Palindrome_Number_Java.java b/Math/palindrome_number.java similarity index 100% rename from Math/Palindrome_Number_Java.java rename to Math/palindrome_number.java diff --git a/Math/Substrings_with_1.py b/Math/substrings_with_1s.py similarity index 100% rename from Math/Substrings_with_1.py rename to Math/substrings_with_1s.py From 6560f4442d62f5c3580bef4141a7d0f16f2d1754 Mon Sep 17 00:00:00 2001 From: balsa-asanovic Date: Mon, 8 May 2023 23:00:49 +0200 Subject: [PATCH 1011/1894] Added JavaScript code for insert_interval --- Merge Interval/insert_interval.js | 76 +++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Merge Interval/insert_interval.js diff --git a/Merge Interval/insert_interval.js b/Merge Interval/insert_interval.js new file mode 100644 index 00000000..bbe2848c --- /dev/null +++ b/Merge Interval/insert_interval.js @@ -0,0 +1,76 @@ +/* + Problem definition: + You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent + the start and the end of the ith interval and intervals is sorted in ascending order by starti. + You are also given an interval newInterval = [start, end] that represents the start and end of another interval. + + Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). + + Approach: + The approach used here is to first add all the intervals before the newInterval to the result array. + Then, we merge overlapping intervals by iterating through the intervals array and comparing the start and end times of the newInterval and the current interval. + After all overlapping intervals have been merged, we add the newInterval to the result array and then add all the remaining intervals after the newInterval. + The resulting array will be sorted in ascending order by start time. + + Complexity: + Time Complexity: O(n), where n is the length of intervals array. + We iterate through the intervals array only once in the worst case. + Space Complexity: O(n), where n is the length of intervals array. + We use an array to store the result, which could potentially contain all the intervals. + + Sample input/outputs: + Example 1: + Input: + intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] + newInterval = [4,8] + + Output: + [[1,2],[3,10],[12,16]] + + Example 2: + Input: + intervals = [[1,3],[6,9]] + newInterval = [2,5] + + Output: + [[1,5],[6,9]] + + Example 3: + Input: + intervals = [[1,5]] + newInterval = [2,3] + + Output: + [[1,5]] +*/ + +const insert = function(intervals, newInterval) { + const result = []; + let i = 0; + + // Add all the intervals before the newInterval + while (i < intervals.length && intervals[i][1] < newInterval[0]) { + result.push(intervals[i]); + i++; + } + + // Merge overlapping intervals + while (i < intervals.length && intervals[i][0] <= newInterval[1]) { + newInterval[0] = Math.min(intervals[i][0], newInterval[0]); + newInterval[1] = Math.max(intervals[i][1], newInterval[1]); + i++; + } + + result.push(newInterval); + + // Add all the intervals after the newInterval + while (i < intervals.length) { + result.push(intervals[i]); + i++; + } + + return result; +}; + +console.log("The resulting array of intervals is:"); +console.log(insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8])); From 93280b23140bb3e79b9355f00f8c71560649d900 Mon Sep 17 00:00:00 2001 From: balsa-asanovic Date: Mon, 8 May 2023 23:08:37 +0200 Subject: [PATCH 1012/1894] added JavaScript code for merge intervals problem --- Merge Interval/merge_interval.js | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Merge Interval/merge_interval.js diff --git a/Merge Interval/merge_interval.js b/Merge Interval/merge_interval.js new file mode 100644 index 00000000..7e76b5cc --- /dev/null +++ b/Merge Interval/merge_interval.js @@ -0,0 +1,63 @@ +/* + Problem definition: + Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, + and return an array of the non-overlapping intervals that cover all the intervals in the input. + + Approach: + The approach is to first sort the intervals by their start times. + Then we initialize a new merged intervals array and loop through all the intervals. + For each interval, if the merged array is empty or + the current interval does not overlap with the previous interval, + then we add the current interval to the merged array. + Otherwise, we merge the current interval with the previous interval + by updating the end time of the previous interval to the maximum of + its original end time and the end time of the current interval. + Finally, we return the merged array. + + Complexity: + The time complexity of this solution is O(n log n) due to the initial sorting step. + The space complexity is O(n) to store the merged intervals array. + + Sample input/outputs: + Example 1: + Input: [[1,4],[4,5]] + Output: [[1,5]] + + Example 2: + Input: [[1,3],[2,6],[8,10],[9,12]] + Output: [[1,6],[8,12]] + + Example 3: + Input: [[1,4],[0,4]] + Output: [[0,4]] +*/ + +function merge(intervals) { + // Sort the intervals by their start times + intervals.sort((a, b) => a[0] - b[0]); + + // Initialize a new merged intervals array + const merged = []; + + // Loop through all the intervals + for (let i = 0; i < intervals.length; i++) { + let interval = intervals[i]; + + // If the merged array is empty or the current interval does not overlap with the previous interval + // then add the current interval to the merged array + if (merged.length === 0 || interval[0] > merged[merged.length - 1][1]) { + merged.push(interval); + } else { + // Otherwise, merge the current interval with the previous interval + merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]); + } + } + + // Return the merged array + return merged; + } + + // Example usage: + const intervals = [[1,3],[2,6],[8,10],[15,18]]; + console.log(merge(intervals)); // [[1,6],[8,10],[15,18]] + \ No newline at end of file From 8c96946e60db75247064ae9b68fdfbc70e16e99b Mon Sep 17 00:00:00 2001 From: balsa-asanovic Date: Mon, 8 May 2023 23:09:24 +0200 Subject: [PATCH 1013/1894] moved merge_interval.java to folder Merge Interval --- merge_intervals.java => Merge Interval/merge_intervals.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename merge_intervals.java => Merge Interval/merge_intervals.java (100%) diff --git a/merge_intervals.java b/Merge Interval/merge_intervals.java similarity index 100% rename from merge_intervals.java rename to Merge Interval/merge_intervals.java From 17d8c67815f6c7f082c6db0163a52fd3cf387b40 Mon Sep 17 00:00:00 2001 From: balsa-asanovic Date: Mon, 8 May 2023 23:10:30 +0200 Subject: [PATCH 1014/1894] renamed file merge_interval.js to merge_intervals.js --- Merge Interval/{merge_interval.js => merge_intervals.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Merge Interval/{merge_interval.js => merge_intervals.js} (100%) diff --git a/Merge Interval/merge_interval.js b/Merge Interval/merge_intervals.js similarity index 100% rename from Merge Interval/merge_interval.js rename to Merge Interval/merge_intervals.js From 1037948dba476e714bfe1e36e346c91eeccc5757 Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Tue, 9 May 2023 15:57:03 +0530 Subject: [PATCH 1015/1894] added kadane's algorithm --- Famous Algorithms/kadanes_algorithm.py | 87 ++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Famous Algorithms/kadanes_algorithm.py diff --git a/Famous Algorithms/kadanes_algorithm.py b/Famous Algorithms/kadanes_algorithm.py new file mode 100644 index 00000000..6634247f --- /dev/null +++ b/Famous Algorithms/kadanes_algorithm.py @@ -0,0 +1,87 @@ +""" +What is Kadane's Algorithm? +Kadane's Algorithm is a way to find the maximum subarray sum in an array with a runtime of O(n). +It is a dynamic programming algorithm that uses the fact that the maximum subarray sum ending at index i is either the value at index i or the maximum subarray sum ending at index i-1 plus the value at index i. + +Note: The subarray must be contiguous, all the values in the subarray must be next to each other in the original array. + +How does it work? +The algorithm works by iterating through the array and keeping track of the maximum subarray sum seen so far and the maximum subarray sum ending at the current index. +The maximum subarray sum ending at the current index is either the value at the current index or the maximum subarray sum ending at the previous index plus the value at the current index. + +Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} + max_so_far = INT_MIN + max_ending_here = 0 + + for i=0, a[0] = -2 + max_ending_here = max_ending_here + (-2) + Set max_ending_here = 0 because max_ending_here < 0 + and set max_so_far = -2 + + for i=1, a[1] = -3 + max_ending_here = max_ending_here + (-3) + Since max_ending_here = -3 and max_so_far = -2, max_so_far will remain -2 + Set max_ending_here = 0 because max_ending_here < 0 + + for i=2, a[2] = 4 + max_ending_here = max_ending_here + (4) + max_ending_here = 4 + max_so_far is updated to 4 because max_ending_here greater + than max_so_far which was -2 till now + + for i=3, a[3] = -1 + max_ending_here = max_ending_here + (-1) + max_ending_here = 3 + + for i=4, a[4] = -2 + max_ending_here = max_ending_here + (-2) + max_ending_here = 1 + + for i=5, a[5] = 1 + max_ending_here = max_ending_here + (1) + max_ending_here = 2 + + for i=6, a[6] = 5 + max_ending_here = max_ending_here + (5) + max_ending_here = 7 + max_so_far is updated to 7 because max_ending_here is + greater than max_so_far + + for i=7, a[7] = -3 + max_ending_here = max_ending_here + (-3) + max_ending_here = 4 + + Time Complexity: O(n) + Space Complexity: O(1) +""" + +from sys import maxint + +# maxint is a constant that holds the maximum possible value for an integer in Python. + + +def maxSubArraySum(a, size): + # we take the max_so_far to be the smallest possible integer value + max_so_far = -maxint - 1 + + # initialize max_ending_here to 0 + max_ending_here = 0 + + for i in range(0, size): + max_ending_here = max_ending_here + a[i] + if max_so_far < max_ending_here: + max_so_far = max_ending_here + + # if max_ending_here is negative, we set it to 0 + if max_ending_here < 0: + max_ending_here = 0 + + return max_so_far + + +# Driver function to check the above function + + +a = [-2, -3, 4, -1, -2, 1, 5, -3] + +print("Maximum contiguous sum is", maxSubArraySum(a, len(a))) From 6e705bed4cebb8da2b3344f3a03062d76f66268b Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 18:07:57 +0530 Subject: [PATCH 1016/1894] kadane_algo_in_js --- Arrays/kadane's_algo.js | 87 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Arrays/kadane's_algo.js diff --git a/Arrays/kadane's_algo.js b/Arrays/kadane's_algo.js new file mode 100644 index 00000000..86a5d951 --- /dev/null +++ b/Arrays/kadane's_algo.js @@ -0,0 +1,87 @@ +/* Name : Aneesh +Github username : 007aneesh +Repository name : data-structures-and-algorithms +Problem : Kadane's algorithm in Javascript +Issue Number : #1182 +Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum. + +Sample testcases: + +Testcase 1 --> + +Input: number of elements in array = 9 +nums = [-2,1,-3,4,-1,2,1,-5,4] +Output: 6 + +Testcase 2 --> +Input: number of elements in array +nums = [5,4,-1,7,8] +Output: 23 + +Time Complexity = O(n) +Space Complexity = O(n) + + +Explanation: +This code asks the user to enter the number of elements in an array, +and then prompts them to enter each element of the array one at a time. +Once the array is complete, the code applies the Kadane's algorithm to +find the maximum sum of any subarray within the array, and then prints +the result to the console. + +Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array, +and it does so by keeping track of the maximum sum seen so far as it iterates through the array. +At each step, it adds the current element to a running sum, and if that sum becomes negative, +it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far, +it updates the maximum. Finally, it returns the maximum sum. +*/ + +// ----------------------------------------------------------------------------- code begins now! +const readline = require("readline"); + +function kadaneAlgorithm(arr) { + if (!arr) return 0; + let sum = 0; + let max = 0; + + for (let i = 0; i < arr.length; i++) { + max += arr[i]; + + if (max < 0) { + max = 0; + } + + if (sum < max) { + sum = max; + } + } + + return sum; +} + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let arr = []; + +rl.question("Enter number of elements in the array: ", function (n) { + let count = 0; + + function getArrayInput() { + if (count < n) { + rl.question("Enter element in array: ", function (input) { + arr.push(Number(input)); + count++; + getArrayInput(); + }); + } else { + let ans = kadaneAlgorithm(arr); + console.log(ans); + rl.close(); + } + } + + getArrayInput(); +}); From 55e6fdc4348466519dbc2ecb7bb2a532a709a331 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 18:42:33 +0530 Subject: [PATCH 1017/1894] kadane's_algo_js --- {Arrays => Famous Algorithms}/kadane's_algo.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Arrays => Famous Algorithms}/kadane's_algo.js (100%) diff --git a/Arrays/kadane's_algo.js b/Famous Algorithms/kadane's_algo.js similarity index 100% rename from Arrays/kadane's_algo.js rename to Famous Algorithms/kadane's_algo.js From 97ad248b861237d369aa1d4612ddbc24c12d11c5 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 19:02:56 +0530 Subject: [PATCH 1018/1894] kadane_algo_java --- Famous Algorithms/kadane.java | 80 +++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Famous Algorithms/kadane.java diff --git a/Famous Algorithms/kadane.java b/Famous Algorithms/kadane.java new file mode 100644 index 00000000..9f505f62 --- /dev/null +++ b/Famous Algorithms/kadane.java @@ -0,0 +1,80 @@ +/* Name : Aneesh +Github username : 007aneesh +Repository name : data-structures-and-algorithms +Problem : Kadane's algorithm in Java +Issue Number : #1180 +Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum. + +Sample testcases: + +Testcase 1 --> + +Input: number of elements in array = 9 +nums = [-2,1,-3,4,-1,2,1,-5,4] +Output: 6 + +Testcase 2 --> +Input: number of elements in array +nums = [5,4,-1,7,8] +Output: 23 + +Time Complexity = O(n) +Space Complexity = O(1) + + +Explanation: +This code asks the user to enter the number of elements in an array, +and then prompts them to enter each element of the array one at a time. +Once the array is complete, the code applies the Kadane's algorithm to +find the maximum sum of any subarray within the array, and then prints +the result to the console. + +Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array, +and it does so by keeping track of the maximum sum seen so far as it iterates through the array. +At each step, it adds the current element to a running sum, and if that sum becomes negative, +it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far, +it updates the maximum. Finally, it returns the maximum sum. +*/ + +// ----------------------------------------------------------------------------- code begins now! +import java.util.Scanner; + +public class kadane { + public static int maxSubArraySum(int[] arr) { + if (arr == null || arr.length == 0) { + return 0; + } + + int max = 0; + int sum = Integer.MIN_VALUE; + + for (int i = 0; i < arr.length; i++) { + max += arr[i]; + + if (max < arr[i]) { + max = arr[i]; + } + + if (sum < max) { + sum = max; + } + } + + return sum; + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter the number of elements in the array: "); + int n = sc.nextInt(); + int[] arr = new int[n]; + System.out.println("Enter the elements of the array:"); + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + + int maxSum = maxSubArraySum(arr); + System.out.println("The maximum subarray sum is " + maxSum); + } + +} From 050d308b8477cabb12f3bc502d103b45bac09cd8 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 19:09:55 +0530 Subject: [PATCH 1019/1894] kadane_algo_java --- Famous Algorithms/{kadane.java => kadane_algo.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Famous Algorithms/{kadane.java => kadane_algo.java} (98%) diff --git a/Famous Algorithms/kadane.java b/Famous Algorithms/kadane_algo.java similarity index 98% rename from Famous Algorithms/kadane.java rename to Famous Algorithms/kadane_algo.java index 9f505f62..b14b8895 100644 --- a/Famous Algorithms/kadane.java +++ b/Famous Algorithms/kadane_algo.java @@ -39,7 +39,7 @@ // ----------------------------------------------------------------------------- code begins now! import java.util.Scanner; -public class kadane { +public class kadane_algo { public static int maxSubArraySum(int[] arr) { if (arr == null || arr.length == 0) { return 0; From 77b8fa62656cd346e705f3c377ca5a9b924349c1 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 19:33:43 +0530 Subject: [PATCH 1020/1894] name updated --- Famous Algorithms/{kadane's_algo.js => kadanes_algo.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Famous Algorithms/{kadane's_algo.js => kadanes_algo.js} (100%) diff --git a/Famous Algorithms/kadane's_algo.js b/Famous Algorithms/kadanes_algo.js similarity index 100% rename from Famous Algorithms/kadane's_algo.js rename to Famous Algorithms/kadanes_algo.js From a1995025a533bf68e12eeda1d341091ec98fe593 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Tue, 9 May 2023 19:36:45 +0530 Subject: [PATCH 1021/1894] name updated --- Famous Algorithms/{kadane_algo.java => kadanes_algo.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Famous Algorithms/{kadane_algo.java => kadanes_algo.java} (98%) diff --git a/Famous Algorithms/kadane_algo.java b/Famous Algorithms/kadanes_algo.java similarity index 98% rename from Famous Algorithms/kadane_algo.java rename to Famous Algorithms/kadanes_algo.java index b14b8895..7de2d844 100644 --- a/Famous Algorithms/kadane_algo.java +++ b/Famous Algorithms/kadanes_algo.java @@ -39,7 +39,7 @@ // ----------------------------------------------------------------------------- code begins now! import java.util.Scanner; -public class kadane_algo { +public class kadanes_algo { public static int maxSubArraySum(int[] arr) { if (arr == null || arr.length == 0) { return 0; From 1438514f4931dfc16c9fc6c3b190c9a2a22f70eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 9 May 2023 23:21:13 +0530 Subject: [PATCH 1022/1894] follow naming convention and move into arrays --- {Merge Interval => Arrays}/insert_interval.js | 0 {Merge Interval => Arrays}/merge_intervals.java | 0 {Merge Interval => Arrays}/merge_intervals.js | 0 Famous Algorithms/{kadanes_algo.java => kadanes_algorithm.java} | 0 Famous Algorithms/{kadanes_algo.js => kadanes_algorithm.js} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename {Merge Interval => Arrays}/insert_interval.js (100%) rename {Merge Interval => Arrays}/merge_intervals.java (100%) rename {Merge Interval => Arrays}/merge_intervals.js (100%) rename Famous Algorithms/{kadanes_algo.java => kadanes_algorithm.java} (100%) rename Famous Algorithms/{kadanes_algo.js => kadanes_algorithm.js} (100%) diff --git a/Merge Interval/insert_interval.js b/Arrays/insert_interval.js similarity index 100% rename from Merge Interval/insert_interval.js rename to Arrays/insert_interval.js diff --git a/Merge Interval/merge_intervals.java b/Arrays/merge_intervals.java similarity index 100% rename from Merge Interval/merge_intervals.java rename to Arrays/merge_intervals.java diff --git a/Merge Interval/merge_intervals.js b/Arrays/merge_intervals.js similarity index 100% rename from Merge Interval/merge_intervals.js rename to Arrays/merge_intervals.js diff --git a/Famous Algorithms/kadanes_algo.java b/Famous Algorithms/kadanes_algorithm.java similarity index 100% rename from Famous Algorithms/kadanes_algo.java rename to Famous Algorithms/kadanes_algorithm.java diff --git a/Famous Algorithms/kadanes_algo.js b/Famous Algorithms/kadanes_algorithm.js similarity index 100% rename from Famous Algorithms/kadanes_algo.js rename to Famous Algorithms/kadanes_algorithm.js From 7df8093d96ce67db223c779400ef21d4511a8254 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 9 May 2023 23:22:35 +0530 Subject: [PATCH 1023/1894] remove duplicate program --- Arrays/3Sum.cpp | 60 ------------------------------------------------- 1 file changed, 60 deletions(-) delete mode 100644 Arrays/3Sum.cpp diff --git a/Arrays/3Sum.cpp b/Arrays/3Sum.cpp deleted file mode 100644 index 70c6dcb3..00000000 --- a/Arrays/3Sum.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* Name : Abhinav kumar -Github username : Abhinavcode13 -Repository name : data-structures-and-algorithms -Problem : Add Three number sum in C++ -Issue Number : #242 -Problem statement : 3Sum - -Explanation of the below cpp code : - -The code first sorts the input array in ascending order. Then, it iterates through the array and uses the two-pointer technique to find the remaining two elements that add up to the negative of the current element. - -We use two pointers, one at the beginning and one at the end of the remaining array after fixing the current element. If the sum of the three elements is less than zero, we increase the left pointer to increase the sum. If the sum is greater than zero, we decrease the right pointer to decrease the sum. If the sum is zero, we add the triplet to the result vector, and skip duplicate elements by increasing the left pointer and decreasing the right pointer until they point to different elements. - -The time complexity of the code is O(n^2), where n is the length of the input array. The sorting step takes O(n log n) time, and the nested loop takes O(n^2) time in the worst case. However, we skip many iterations of the loop using the two-pointer technique, making the actual running time faster than the worst-case time complexity. -*/ ------------------------------------------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------------------------------------------------------------------------------------------ - -#include -using namespace std; - -vector> threeSum(vector& nums) { - vector> result; - int n = nums.size(); - sort(nums.begin(), nums.end()); // Sort the input array - - // Fix the first element and use two pointer technique to find the remaining two elements - for (int i = 0; i < n - 2; i++) { - if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicate elements - - int l = i + 1, r = n - 1; - while (l < r) { - int sum = nums[i] + nums[l] + nums[r]; - if (sum < 0) { - l++; // Increase left pointer to increase the sum - } else if (sum > 0) { - r--; // Decrease right pointer to decrease the sum - } else { - result.push_back({nums[i], nums[l], nums[r]}); - // Skip duplicate elements - while (l < r && nums[l] == nums[l + 1]) l++; - while (l < r && nums[r] == nums[r - 1]) r--; - l++; - r--; - } - } - } - return result; -} - -int main() { - vector nums = {-1, 0, 1, 2, -1, -4}; - vector> result = threeSum(nums); - for (vector triplet : result) { - for (int x : triplet) { - cout << x << " "; - } - cout << endl; - } - return 0; -} From 0f3dd28f405e9ebf72d0505ca60f4f1e236257bd Mon Sep 17 00:00:00 2001 From: Niraj Date: Tue, 9 May 2023 23:56:52 +0530 Subject: [PATCH 1024/1894] Added Problem Definition in Merge Intervals with Python --- Arrays/Merge_Intervals.py | 37 ++++++++----------------------------- 1 file changed, 8 insertions(+), 29 deletions(-) diff --git a/Arrays/Merge_Intervals.py b/Arrays/Merge_Intervals.py index c4db6bf1..f6fe8e09 100644 --- a/Arrays/Merge_Intervals.py +++ b/Arrays/Merge_Intervals.py @@ -1,9 +1,15 @@ -# Array: Merge intervals in Python #1115 #Program Author : TheCodeVenturer [Niraj Modi] +''' + Problem definition: + Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, + and return an array of the non-overlapping intervals that cover all the intervals in the input. + + +''' class Solution: def mergeIntervals(self, Intervals): - Intervals.sort() #Sorting the intervals to make the starting time in increasing order to maintain the sequence + Intervals.sort() sol = [] start = Intervals[0][0] end = Intervals[0][1] @@ -15,30 +21,3 @@ def mergeIntervals(self, Intervals): end = max(end, u) sol.append([start, end]) return sol - - -if __name__ == '__main__': - T = int(input()) - for i in range(T): - n = int(input()) - a = list(map(int, input().strip().split())) - Intervals = [] - j = 0 - for i in range(n): - x = a[j] - j += 1 - y = a[j] - j += 1 - Intervals.append([x, y]) - obj = Solution() - ans = obj.mergeIntervals(Intervals) - for i in ans: - for j in i: - print(j, end=" ") - print() - -''' -Input Format -t=1 No.of Test Cases -Intervals = 2 3 1 2 6 8 9 10 A 2-d Array [[2,3],[1,2],[6,8],[9,10]] -''' \ No newline at end of file From 2948722b40f2eaa1e9dd14e8d300ff7af8d7fe3b Mon Sep 17 00:00:00 2001 From: Niraj Date: Wed, 10 May 2023 00:09:00 +0530 Subject: [PATCH 1025/1894] Merge Intervals in Python Completed --- Arrays/Merge_Intervals.py | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/Arrays/Merge_Intervals.py b/Arrays/Merge_Intervals.py index f6fe8e09..cb2450ca 100644 --- a/Arrays/Merge_Intervals.py +++ b/Arrays/Merge_Intervals.py @@ -4,20 +4,47 @@ Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. - + Approach: + The Approach to this problem is that it will be more easier if we start merging the time linear increasing fashion + To Make It in Linear Increasing Fashion We will Sort the Array + Then will initialise a new mergeIntervals Array. Here, sol + then will pick the first starting and ending point and will iterate through the array .Here, start,end + and insert it if the new start time is Greater then previous one(end) or will merge it with previous Start Time,end Time(start,end). + and at finally when the loop is over again will insert the start and end for the final Interval + then Will the mergedIntervals Array + Sample input/outputs: + Example 1: + Input: [[1,9],[4,5]] + Output: [[1,9]] + + Example 2: + Input: [[1,3],[2,6],[8,10],[9,12]] + Output: [[1,6],[8,12]] + + Example 3: + Input: [[1,4],[0,2]] + Output: [[0,4]] ''' -class Solution: +class Solution(object): def mergeIntervals(self, Intervals): - Intervals.sort() - sol = [] - start = Intervals[0][0] + Intervals.sort() # Sorting the Intervals to make the Array in Linear Increasing Fashion + sol = [] # MergedIntervals Array Initialisation + start = Intervals[0][0] end = Intervals[0][1] + #setting up the first start and end Point for [l, u] in Intervals: + # if l (current start) is Greater then previous end then will add it to mergedIntervals Array + # else will update the end with the greater end that is max(end,u) if (l > end): sol.append([start, end]) start, end = l, u else: end = max(end, u) + #finally adding the final start and end point to sol sol.append([start, end]) return sol +if __name__ == "__main__": + Intervals = [[1,3],[2,6],[8,10],[9,12]] + sol = Solution() + print(sol.mergeIntervals(Intervals)) From c411327b7a8aa7700cb71f57759add493686ec62 Mon Sep 17 00:00:00 2001 From: Niraj Date: Wed, 10 May 2023 00:33:36 +0530 Subject: [PATCH 1026/1894] #1011 Updated Largest Rectangle In Binary Matrix with python --- .../Largest_Rectangle_In_Binary_Matrix.py | 73 ++++++++++++------- 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py index b1c077b4..6172127f 100644 --- a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py @@ -1,11 +1,48 @@ -# Dynamic Programming: Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area in Python #1011 #Program Author : TheCodeVenturer [Niraj Modi] +''' + Problem Definition: + Dynamic Programming: Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area in Python + Approach: + This Problem can be termed as updated version of Largest Rectangle in Histogram + If you are given a binary matrix then you can use no.of rows together with one as height + Like + 0 1 1 0 + 1 1 1 1 + 1 1 1 1 + 1 1 0 0 + If you can Visualise then it will be clear that for + first row the histogram row is like [0,1,1,0] + second row the histogram row is like [1,2,2,1] + third row the histogram row is like [2,3,3,2] + fourth row the histogram row is like [3,4,0,0] + then by using a monotonic stack for each row we can get The Largest Rectangle in the Binary Matrix + + we are taking here a row list which keeps track of current height of a particular column . Here, ShiftRow + we are also using a solution variable to keep track of largest rectangle + then first we will iterate through each row + and inside each iteration we will go and look for the particular element of that row matrix[i][j] + if it is 1 then will increase size of jth entry in the shiftRow else will convert it to zero + next will initialize an empty Stack [Monotonic] + next we will iterate through the shiftRow and will first check for the list is not empty and (it's top element is greater than or equal to current element or value of current column is equal to row size) + then will store it's height from the current row array and will update width of the rectangle with stack's top element and will finally update the sol + and will insert the element to the stack + Sample input/outputs: + Example 1: + Input: [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] + Output: 8 + + Example 2: + Input: [[0,1,1],[1,1,1],[0,1,1]] + Output: 6 +''' class Solution: def maxArea(self,matrix, rows, cols): - shiftRow = [0]*cols + shiftRow = [0]*cols #initialising the row which update after each iteration sol=0 for row in matrix: - for i,ele in enumerate(row): + for i,ele in enumerate(row): #used enumerate as it will give index as well as element + # Updating the shiftRow if value of ele is 1 => ShiftRow[i] <- shiftRow[i]+1 + # else shiftRow[i]=0 if ele==1: shiftRow[i]+=1 else: @@ -13,32 +50,16 @@ def maxArea(self,matrix, rows, cols): st = [] for i in range(cols+1): while(len(st)>0 and(i==cols or shiftRow[st[-1]]>=shiftRow[i])): - height = shiftRow[st[-1]] + height = shiftRow[st[-1]] #for getting height of Current index st.pop() - width = i + width = i # setting width to i as it is only smallest from beginning if(len(st)>0): - width = i - st[-1] - 1 - sol = max(height*width,sol) - st.append(i) + width = i - st[-1] - 1 # updating width is stack is not empty as it is not the smallest element + sol = max(height*width,sol) # Updating the sol + st.append(i) # Pushing the Element's index to the stack return sol if __name__ == '__main__': - t=int(input()) - for _ in range(t): - R,C = map(int, input().strip().split()) - A = [] - for i in range(R): - line = [int(x) for x in input().strip().split()] - A.append(line) - print(Solution().maxArea(A, R, C)) -""" -Input Format -1 No.Of Test Cases -4 4 rows,columns -next rows*columns lines -0 1 1 0 -1 1 1 1 -1 1 1 1 -1 1 0 0 -""" + matrix = [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] + print(Solution().maxArea(matrix, 4, 4)) From d28480b8a393274e9fce3beec3e445888ba2abd3 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Wed, 10 May 2023 02:05:37 +0530 Subject: [PATCH 1027/1894] Kadenes algorithim code simplified --- Famous Algorithms/kadanes_algorithm.js | 87 ---------------------- Famous Algorithms/kadenes_algorithim.js | 98 +++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 87 deletions(-) delete mode 100644 Famous Algorithms/kadanes_algorithm.js create mode 100644 Famous Algorithms/kadenes_algorithim.js diff --git a/Famous Algorithms/kadanes_algorithm.js b/Famous Algorithms/kadanes_algorithm.js deleted file mode 100644 index 86a5d951..00000000 --- a/Famous Algorithms/kadanes_algorithm.js +++ /dev/null @@ -1,87 +0,0 @@ -/* Name : Aneesh -Github username : 007aneesh -Repository name : data-structures-and-algorithms -Problem : Kadane's algorithm in Javascript -Issue Number : #1182 -Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum. - -Sample testcases: - -Testcase 1 --> - -Input: number of elements in array = 9 -nums = [-2,1,-3,4,-1,2,1,-5,4] -Output: 6 - -Testcase 2 --> -Input: number of elements in array -nums = [5,4,-1,7,8] -Output: 23 - -Time Complexity = O(n) -Space Complexity = O(n) - - -Explanation: -This code asks the user to enter the number of elements in an array, -and then prompts them to enter each element of the array one at a time. -Once the array is complete, the code applies the Kadane's algorithm to -find the maximum sum of any subarray within the array, and then prints -the result to the console. - -Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array, -and it does so by keeping track of the maximum sum seen so far as it iterates through the array. -At each step, it adds the current element to a running sum, and if that sum becomes negative, -it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far, -it updates the maximum. Finally, it returns the maximum sum. -*/ - -// ----------------------------------------------------------------------------- code begins now! -const readline = require("readline"); - -function kadaneAlgorithm(arr) { - if (!arr) return 0; - let sum = 0; - let max = 0; - - for (let i = 0; i < arr.length; i++) { - max += arr[i]; - - if (max < 0) { - max = 0; - } - - if (sum < max) { - sum = max; - } - } - - return sum; -} - -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); - -let arr = []; - -rl.question("Enter number of elements in the array: ", function (n) { - let count = 0; - - function getArrayInput() { - if (count < n) { - rl.question("Enter element in array: ", function (input) { - arr.push(Number(input)); - count++; - getArrayInput(); - }); - } else { - let ans = kadaneAlgorithm(arr); - console.log(ans); - rl.close(); - } - } - - getArrayInput(); -}); diff --git a/Famous Algorithms/kadenes_algorithim.js b/Famous Algorithms/kadenes_algorithim.js new file mode 100644 index 00000000..0a22dc31 --- /dev/null +++ b/Famous Algorithms/kadenes_algorithim.js @@ -0,0 +1,98 @@ +/* What is Kadane's Algorithm? +Kadane's Algorithm is a way to find the maximum subarray sum in an array with a runtime of O(n). +It is a dynamic programming algorithm that uses the fact that the maximum subarray sum ending at index i is either the value at index i or the maximum subarray sum ending at index i-1 plus the value at index i. + +Note: The subarray must be contiguous, all the values in the subarray must be next to each other in the original array. + +How does it work? +In this algorithim we maintain two variables, one will hold the maximum sum of contagious subarray and the other variable will hold sum of next element + current sum from previous iteration. +If at any point the current sum + next element sum is less then 0 then we will reset the current sum to 0 and current sum + next element sum will start again from the next element. +If the current sum + next element sum is greater then 0 and it is also greater then the maximum sum of contagious subarray then the variable of maximum sum of contagious subarray will be updated with current sum + next element sum + + +Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} + In this example maxLargestSumTillNow holds the maximum sum of contagious subarray and newLargestSum hold the value of current sum + next element + On initalizing max so far will be the max -ve number + maxLargestSumTillNow = INT_MIN + newLargestSum = 0 + + for i=0, a[0] = -2 + newLargestSum = newLargestSum + (-2) + Set newLargestSum = 0 because newLargestSum < 0 + and set maxLargestSumTillNow = -2 + + for i=1, a[1] = -3 + newLargestSum = newLargestSum + (-3) + Since newLargestSum = -3 and maxLargestSumTillNow = -2, maxLargestSumTillNow will remain -2 + Set newLargestSum = 0 because newLargestSum < 0 + + for i=2, a[2] = 4 + newLargestSum = newLargestSum + (4) + newLargestSum = 4 + maxLargestSumTillNow is updated to 4 because newLargestSum greater + than maxLargestSumTillNow which was -2 till now + + for i=3, a[3] = -1 + newLargestSum = newLargestSum + (-1) + newLargestSum = 3 + + for i=4, a[4] = -2 + newLargestSum = newLargestSum + (-2) + newLargestSum = 1 + + for i=5, a[5] = 1 + newLargestSum = newLargestSum + (1) + newLargestSum = 2 + + for i=6, a[6] = 5 + newLargestSum = newLargestSum + (5) + newLargestSum = 7 + maxLargestSumTillNow is updated to 7 because newLargestSum is + greater than maxLargestSumTillNow + + for i=7, a[7] = -3 + newLargestSum = newLargestSum + (-3) + newLargestSum = 4 + + Time Complexity: O(n) + Space Complexity: O(1) +*/ + +function largestSumOfSubArray(arr) { + if (arr.lenth == 1) { + return arr[0]; + } + + // Variable for maintaining Maximum sum of the subarray + var maxint = Math.pow(2, 53); + var maxLargestSumTillNow = -maxint - 1; + + // Variable to calclate the sum of subarray after each iteration + var newLargestSum = 0; + + // Looping through the entire array + for (i = 0; i < arr.length - 1; i++) { + // Calculating the largest sum on each iteration + newLargestSum += arr[i]; + + // If the largest sum value is greater then the maximum largest subarray value we have maintained then we will assign new value to maintained maximum largest subarray + if (maxLargestSumTillNow < newLargestSum) { + maxLargestSumTillNow = newLargestSum; + } + + // If the largest sum is negative then we will reset the value of largest sum to 0 and start the calculation again of largest sum from next element + if (newLargestSum < 0) { + newLargestSum = 0; + } + } + + // After the completion of iteration we will return the max largest sub array value + return maxLargestSumTillNow; +} + +// Driver code +var arr = [-2, -3, 4, -1, -2, 1, 5, -3]; +console.log(largestSumOfSubArray(arr)); + +// Input: arr = [-2, -3, 4, -1, -2, 1, 5, -3]; +//Output: 7 From da5706c672c0efec9c06162371cf1a943564f463 Mon Sep 17 00:00:00 2001 From: Arpit Sharma Date: Wed, 10 May 2023 02:06:19 +0530 Subject: [PATCH 1028/1894] file name corrected --- Famous Algorithms/{kadenes_algorithim.js => kadenes_algorithm.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Famous Algorithms/{kadenes_algorithim.js => kadenes_algorithm.js} (100%) diff --git a/Famous Algorithms/kadenes_algorithim.js b/Famous Algorithms/kadenes_algorithm.js similarity index 100% rename from Famous Algorithms/kadenes_algorithim.js rename to Famous Algorithms/kadenes_algorithm.js From 5893b8732fb7e5ed79f1db4920417066ff0c0297 Mon Sep 17 00:00:00 2001 From: Ashley Didriksen Date: Tue, 9 May 2023 18:30:13 -0400 Subject: [PATCH 1029/1894] added python,javascript and java implementations of Euclid's Algorithms --- Famous Algorithms/euclidean_algorithm.java | 27 ++++++++++++++++++++++ Famous Algorithms/euclidean_algorithm.js | 22 ++++++++++++++++++ Famous Algorithms/euclidean_algorithm.py | 21 +++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 Famous Algorithms/euclidean_algorithm.java create mode 100644 Famous Algorithms/euclidean_algorithm.js create mode 100644 Famous Algorithms/euclidean_algorithm.py diff --git a/Famous Algorithms/euclidean_algorithm.java b/Famous Algorithms/euclidean_algorithm.java new file mode 100644 index 00000000..cc31a2e1 --- /dev/null +++ b/Famous Algorithms/euclidean_algorithm.java @@ -0,0 +1,27 @@ +//extended version of Euclid's algorithm to find GCD of 2 numbers +//runs in O(log N) time/space complexity for GCD of numbers a and b +//in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) + +public class euclidean_algorithm { + public static int euclid(int a, int b, int c, int d){ + if(a == 0){ + c = 0; + d = 0; + return b; + } + int c1 = 1,d1 = 1; + int result = euclid(b%a, a, c1, d1); + //update with recursive call + c = d1 - (b / a) * c1; + d = c1; + return result; + } + //driver + public static void main(String[] args) { + int c =1, d = 1; + int a = 45; + int b = 10; + int gcd = euclid(a, b, c, d); + System.out.print("gcd of "+ a+"," +b +" is equal to: " + gcd); + } +} diff --git a/Famous Algorithms/euclidean_algorithm.js b/Famous Algorithms/euclidean_algorithm.js new file mode 100644 index 00000000..0aaca194 --- /dev/null +++ b/Famous Algorithms/euclidean_algorithm.js @@ -0,0 +1,22 @@ +//extended version of Euclid's algorithm to find GCD of 2 numbers +//runs in O(log N) time/space complexity for GCD of numbers a and b +//in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) + + +function euclid(a,b,c,d){ + if(a == 0){ + c = 0; + d = 1; + return b; + } + let result = euclid(b%a,a,c,d); + //update with recursive values + c = d- (b / a) * c; + d = c; + return result; +} +//modify a and b to find gcd of any 2 numbers +let a = 450; +let b = 100; +let gcd = euclid(a,b,0,0); +console.log(`GCD of ${a}, ${b} is equal to ${gcd}`); diff --git a/Famous Algorithms/euclidean_algorithm.py b/Famous Algorithms/euclidean_algorithm.py new file mode 100644 index 00000000..081079bc --- /dev/null +++ b/Famous Algorithms/euclidean_algorithm.py @@ -0,0 +1,21 @@ +#extended version of Euclid's algorithm to find GCD of 2 numbers +#runs in O(log N) time/space complexity for GCD of numbers a and b +#in comparison, the standard Euclidean algorithm runs in O (log (min (a,b))) + +def euclidExtended(a,b): + if a==0: + return b,0, 1 + result, a1, b1 = euclidExtended(b%a,a) + + a2 = b1- (b//a) *a1 + b2 = a1 + return result, a2, b2 #used as input to recursive call, + +#example driver, change a and b as desired + +a,b = 45,10 +g,x,y = euclidExtended(a,b) +print("gcd of", a,"," ,b ,"is equal to: " , g) + + + From 7d34ac485b0f2c96113dfbb00eff05b314a78ebf Mon Sep 17 00:00:00 2001 From: Mujtaba Hussain <67089235+Hussain15527@users.noreply.github.com> Date: Wed, 10 May 2023 04:31:13 +0530 Subject: [PATCH 1030/1894] Update Number of Substrings With Only 1s.js --- Math/Number of Substrings With Only 1s.js | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js index cafc74a1..59e2314b 100644 --- a/Math/Number of Substrings With Only 1s.js +++ b/Math/Number of Substrings With Only 1s.js @@ -22,6 +22,44 @@ s[i] is either '0' or '1'. */ +/* + +/* + PROBLEM STATEMENT: + + Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. + + EXAMPLE 1: + Input: s = "0110111" + Output: 9 + Explanation: There are 9 substring in total with only 1's characters. + "1" -> 5 times. + "11" -> 3 times. + "111" -> 1 time. + EXAMPLE 2: + Input: s = "101" + Output: 2 + Explanation: Substring "1" is shown 2 times in s. + + CONSTRAINT: + Constraints: + 1 <= s.length <= 105 + s[i] is either '0' or '1'. +*/ + +/* + The function begins by initializing two variables - "count" and "answer" - to 0. "count" will be used to keep track of the current number of consecutive 1's in the string, while "answer" will eventually store the final answer. + +The constant "mod" is defined to be 10^9+7, which will be used to take modulo of the answer at each step, in order to prevent overflow. + +The function then iterates through the input string using a for loop. For each character in the string, it checks if it is a 1 or a 0. If it is a 1, the "count" variable is incremented by 1. If it is a 0, the "count" variable is reset to 0. + +At each step of the loop, the value of "count" is added to "answer" and then taken modulo "mod". This is done to count the number of substrings with all 1's and prevent overflow of the result. + +After the loop has finished, the final value of "answer" is returned as the solution to the problem. + + +*/ var numSub = function(s) { // count stores the current number of consecutive 1's @@ -41,3 +79,42 @@ var numSub = function(s) { // return the final answer. return answer; }; + + + +*/ + +var numSub = function(s) { + // count stores the current number of consecutive 1's + var count=0; + // answer storese the final answer to be returned + var answer=0; + // we mod the sum at each step so that they don't overflow + const mod=1000000007; + // iterate the entire string + for(let i=0;i Date: Wed, 10 May 2023 04:32:28 +0530 Subject: [PATCH 1031/1894] Update Number of Substrings With Only 1s.js --- Math/Number of Substrings With Only 1s.js | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js index 59e2314b..b9d122da 100644 --- a/Math/Number of Substrings With Only 1s.js +++ b/Math/Number of Substrings With Only 1s.js @@ -48,13 +48,19 @@ */ /* - The function begins by initializing two variables - "count" and "answer" - to 0. "count" will be used to keep track of the current number of consecutive 1's in the string, while "answer" will eventually store the final answer. + The function begins by initializing two variables - "count" and "answer" - to 0. + "count" will be used to keep track of the current number of consecutive 1's in the string, + while "answer" will eventually store the final answer. -The constant "mod" is defined to be 10^9+7, which will be used to take modulo of the answer at each step, in order to prevent overflow. +The constant "mod" is defined to be 10^9+7, which will be used to take modulo of the answer +at each step, in order to prevent overflow. -The function then iterates through the input string using a for loop. For each character in the string, it checks if it is a 1 or a 0. If it is a 1, the "count" variable is incremented by 1. If it is a 0, the "count" variable is reset to 0. +The function then iterates through the input string using a for loop. +For each character in the string, it checks if it is a 1 or a 0. If it is a 1, +the "count" variable is incremented by 1. If it is a 0, the "count" variable is reset to 0. -At each step of the loop, the value of "count" is added to "answer" and then taken modulo "mod". This is done to count the number of substrings with all 1's and prevent overflow of the result. +At each step of the loop, the value of "count" is added to "answer" and then taken modulo "mod". +This is done to count the number of substrings with all 1's and prevent overflow of the result. After the loop has finished, the final value of "answer" is returned as the solution to the problem. @@ -106,9 +112,13 @@ var numSub = function(s) { /* Time and Space complexity -The time complexity of this code is O(n), where n is the length of the input string s. This is because we iterate through the entire string once, and each operation inside the loop takes O(1) time. +The time complexity of this code is O(n), +where n is the length of the input string s. This is because we iterate through the entire string once, +and each operation inside the loop takes O(1) time. -The space complexity of this code is O(1), because we only use a fixed amount of extra space to store the variables count, answer, mod, and i. We do not use any additional space that depends on the length of the input string. +The space complexity of this code is O(1), +because we only use a fixed amount of extra space to store the variables count, answer, mod, and i. +We do not use any additional space that depends on the length of the input string. From 9b43c1ab6f7df60b2cfe66af3dcf2b03e9239da6 Mon Sep 17 00:00:00 2001 From: Mujtaba Hussain <67089235+Hussain15527@users.noreply.github.com> Date: Wed, 10 May 2023 04:32:55 +0530 Subject: [PATCH 1032/1894] Update Number of Substrings With Only 1s.js --- Math/Number of Substrings With Only 1s.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js index b9d122da..02d4d330 100644 --- a/Math/Number of Substrings With Only 1s.js +++ b/Math/Number of Substrings With Only 1s.js @@ -47,7 +47,8 @@ s[i] is either '0' or '1'. */ -/* +/* Explaination + The function begins by initializing two variables - "count" and "answer" - to 0. "count" will be used to keep track of the current number of consecutive 1's in the string, while "answer" will eventually store the final answer. From 2ff8230430f55e7f380dfa5dcb975a826dca2d9d Mon Sep 17 00:00:00 2001 From: Mujtaba Hussain <67089235+Hussain15527@users.noreply.github.com> Date: Wed, 10 May 2023 04:34:10 +0530 Subject: [PATCH 1033/1894] Update Number of Substrings With Only 1s.js --- Math/Number of Substrings With Only 1s.js | 48 ----------------------- 1 file changed, 48 deletions(-) diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js index 02d4d330..f5624013 100644 --- a/Math/Number of Substrings With Only 1s.js +++ b/Math/Number of Substrings With Only 1s.js @@ -1,29 +1,3 @@ - -/* - PROBLEM STATEMENT: - - Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. - - EXAMPLE 1: - Input: s = "0110111" - Output: 9 - Explanation: There are 9 substring in total with only 1's characters. - "1" -> 5 times. - "11" -> 3 times. - "111" -> 1 time. - EXAMPLE 2: - Input: s = "101" - Output: 2 - Explanation: Substring "1" is shown 2 times in s. - - CONSTRAINT: - Constraints: - 1 <= s.length <= 105 - s[i] is either '0' or '1'. -*/ - -/* - /* PROBLEM STATEMENT: @@ -68,28 +42,6 @@ After the loop has finished, the final value of "answer" is returned as the solu */ -var numSub = function(s) { - // count stores the current number of consecutive 1's - var count=0; - // answer storese the final answer to be returned - var answer=0; - // we mod the sum at each step so that they don't overflow - const mod=1000000007; - // iterate the entire string - for(let i=0;i Date: Wed, 10 May 2023 07:50:33 +0530 Subject: [PATCH 1034/1894] Added Complexities to The Problem --- Arrays/Merge_Intervals.py | 5 +++++ Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/Arrays/Merge_Intervals.py b/Arrays/Merge_Intervals.py index cb2450ca..b55cf533 100644 --- a/Arrays/Merge_Intervals.py +++ b/Arrays/Merge_Intervals.py @@ -12,6 +12,11 @@ and insert it if the new start time is Greater then previous one(end) or will merge it with previous Start Time,end Time(start,end). and at finally when the loop is over again will insert the start and end for the final Interval then Will the mergedIntervals Array + Complexity: + Time Complexity: O(n logn) for sorting the array and additional O(n) for the complete iteration + All Over It will be O(n logn) + Space Complexity: O(1) as we are not using any extra Spaces + Space to Store Solution is not counted in Space complexity Sample input/outputs: Example 1: Input: [[1,9],[4,5]] diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py index 6172127f..37355c00 100644 --- a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py @@ -26,6 +26,10 @@ next we will iterate through the shiftRow and will first check for the list is not empty and (it's top element is greater than or equal to current element or value of current column is equal to row size) then will store it's height from the current row array and will update width of the rectangle with stack's top element and will finally update the sol and will insert the element to the stack + Complexity: + Time Complexity: O(rows * col) for for traversing through each elements of the array + Here in each iteration we are doint three times O(n) => O(3n) ~ O(n) + Space Complexity: O(n) for the shiftRow and O(n) for the stack we are using => O(2n) ~ O(n) Sample input/outputs: Example 1: Input: [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] From 02e87f97319680447086c6094df44774138a6916 Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Wed, 10 May 2023 11:43:26 +0530 Subject: [PATCH 1035/1894] Beautified the code with Arrays import. --- sorting/bubble_sort.class | Bin 0 -> 745 bytes sorting/bubble_sort.java | 9 ++++----- 2 files changed, 4 insertions(+), 5 deletions(-) create mode 100644 sorting/bubble_sort.class diff --git a/sorting/bubble_sort.class b/sorting/bubble_sort.class new file mode 100644 index 0000000000000000000000000000000000000000..62afe78afe1491062a825eab65325eee7a35e256 GIT binary patch literal 745 zcmZuu%Wl&^6g?B$apJgiNJ&aaOlexE<3hYEAVPUmLP81{$taQw5;%!fxg>VwI7r?1 zAJ`)#*02DCP?s#&^D~Io9R~!6YDV`lbMHB4=6?GA{t&=5oYRnlq(auAAkV;e{inV? z@}nKw>F)-Elp)^eEw|Ye! z!@LTv<2cIyz`OgCG#C?VJf+r3HzN*X`(6@8shcK&Kfa>j1S%@3Iu>#AclR_6NA`^* z@%JYTg*2wxFxp|L3c?vorhj%$7^hHI(a>SwG{eFXJPhidU>!vy#QYzk)nkyi;$grr z-wmVS?sVJ_lKVcroMFyQ{lSwv{@$-#9{VBTkeZ``G&i0mgWy&un)zS<*A~jKOdp)1 z(Et*dm$_(<1ykfltdqn}m8M5LUsG%t4L9r-(Mr{iDE$gr&U2W9m;d5M;HjR2? zC_>XR+Lj?dZoj}Hg&VSEWT_);MRpD(_VUN)gB;n9f+&{}Sh&FMoX3Ee01nY8@ At^fc4 literal 0 HcmV?d00001 diff --git a/sorting/bubble_sort.java b/sorting/bubble_sort.java index 1a7a7803..56ffc099 100644 --- a/sorting/bubble_sort.java +++ b/sorting/bubble_sort.java @@ -20,7 +20,9 @@ Bubble sort is O(n) on a list that is already sorted i.e. Best case Output : [0 1 2 3 4 5 9] */ -public class BubbleSort { +import java.util.Arrays; + +public class bubble_sort { public static void bubbleSort(int[] arr) { int n = arr.length; // Traverse through all array elements @@ -40,9 +42,6 @@ public static void bubbleSort(int[] arr) { public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr); - System.out.println("Sorted array: "); - for (int i = 0; i < arr.length; i++) { - System.out.print(arr[i] + " "); - } + System.out.println(Arrays.toString(arr)); } } From 713fade3953e3282ca684570833fdb9ff44f1c0b Mon Sep 17 00:00:00 2001 From: Arpitshivam Pandey <98251986+Arpit0324@users.noreply.github.com> Date: Wed, 10 May 2023 16:47:11 +0530 Subject: [PATCH 1036/1894] Create Heap Sort .cpp I have uploaded Complete heap sort in C++ along with Time complexity --- sorting/Heap Sort .cpp | 59 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 sorting/Heap Sort .cpp diff --git a/sorting/Heap Sort .cpp b/sorting/Heap Sort .cpp new file mode 100644 index 00000000..c57b03fc --- /dev/null +++ b/sorting/Heap Sort .cpp @@ -0,0 +1,59 @@ +#include +using namespace std; +void heapify(int arr[], int n, int i){ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + //If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + //If right child largest + if (r < n && arr[r] > arr[largest]) + largest = r; + //If root is nor largest + if (largest != i){ + swap(arr[i], arr[largest]); + //Recursively heapifying the sub-tree + heapify(arr, n, largest); + } +} + +void heapSort(int arr[], int n){ + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + //One by one extract an element from heap + for (int i=n-1; i>=0; i--){ + //Moving current root to end + swap(arr[0], arr[i]); + //Calling max heapify on the reduced heap + heapify(arr, i, 0); + } +} + //Function to print array +void display(int arr[], int n){ + for (int i = 0; i < n; i++){ + cout << arr[i] << "\t"; + } + cout << "\n"; +} +int main(){ + int arr[] = {1, 14, 3, 7, 0}; + int n = sizeof(arr)/sizeof(arr[0]); + cout << "Unsorted array \n"; + display(arr, n); + heapSort(arr, n); + cout << "Sorted array \n"; + display(arr, n); +} + +/*Time Complexcity +Best +O(nlog n) + +Average +O(nlog n) + +Worst +O(nlog n) +*/ From eecaaba307232a01691c189bd91120e5d9970d80 Mon Sep 17 00:00:00 2001 From: Arpitshivam Pandey <98251986+Arpit0324@users.noreply.github.com> Date: Wed, 10 May 2023 19:29:51 +0530 Subject: [PATCH 1037/1894] Update Heap Sort .cpp updated the document --- sorting/Heap Sort .cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/sorting/Heap Sort .cpp b/sorting/Heap Sort .cpp index c57b03fc..0070532e 100644 --- a/sorting/Heap Sort .cpp +++ b/sorting/Heap Sort .cpp @@ -1,3 +1,23 @@ +/* +Heap sort is a sorting technique based on comparison based on binary heap data. +Similar to sorting, it finds the largest number first and then puts the largest number last. + + +This sorting algorithm uses a tree structure called the stack, where the stack is a kind of binary tree. +A binary decision tree in which the value of the root of a tree is less than or equal to the value of one of its roots is called a min-heap. +A decision binary tree is called maximum heap when the value of the root of a tree is greater than or equal to the value of one of its trees. +In this post, we'll learn more about C++ Stack Sorting. + +Working of heap sort in C++ +To sort any list into a logical order following steps are followed:- + +Convert the list into a heap. +Now convert this heap into a max heap. +As the heap is converted to max heap largest element in the list is stored in the root of the heap, replace it with the last item of the heap. +Now delete this node and reduce the size of the heap by 1. +Follow these steps until the list is sorted. +*/ + #include using namespace std; void heapify(int arr[], int n, int i){ From 3eb5fe6347d2e3db1ab8cf805ce9bc066bb66dbb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 10 May 2023 22:54:56 +0530 Subject: [PATCH 1038/1894] rename file --- sorting/{Heap Sort .cpp => heap_sort.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sorting/{Heap Sort .cpp => heap_sort.cpp} (100%) diff --git a/sorting/Heap Sort .cpp b/sorting/heap_sort.cpp similarity index 100% rename from sorting/Heap Sort .cpp rename to sorting/heap_sort.cpp From 78da776551e6267efadfb0f3ad641ff657c3853e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 10 May 2023 22:55:11 +0530 Subject: [PATCH 1039/1894] rename file --- ...allindromic_permutations.cpp => pallindromic_permutations.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{arrays_strings_pallindromic_permutations.cpp => pallindromic_permutations.cpp} (100%) diff --git a/Arrays/arrays_strings_pallindromic_permutations.cpp b/Arrays/pallindromic_permutations.cpp similarity index 100% rename from Arrays/arrays_strings_pallindromic_permutations.cpp rename to Arrays/pallindromic_permutations.cpp From f3e7d6c185eabaa628740bc3b26fc8c6ac867177 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 10 May 2023 23:01:22 +0530 Subject: [PATCH 1040/1894] improve documentation --- Arrays/Good_pairs.cpp | 73 +++++++++++++++++++------------------------ 1 file changed, 33 insertions(+), 40 deletions(-) diff --git a/Arrays/Good_pairs.cpp b/Arrays/Good_pairs.cpp index 21baeccc..aab8d29a 100644 --- a/Arrays/Good_pairs.cpp +++ b/Arrays/Good_pairs.cpp @@ -1,50 +1,44 @@ -/* Name : Abhinav kumar -Github username : Abhinavcode13 -Repository name : data-structures-and-algorithms -Problem : Find Number of Good Pairs in Go -Issue Number : #529 -Problem statement : Given an array of integers nums, return the number of good pairs. +/* + Problem statement : Given an array of integers nums, return the number of good pairs. -A pair (i, j) is called good if nums[i] == nums[j] and i < j. + A pair (i, j) is called good if nums[i] == nums[j] and i < j. -Example 1: + Example 1: -Input: nums = [1,2,3,1,1,3] -Output: 4 -Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. -Example 2: + Input: nums = [1,2,3,1,1,3] + Output: 4 + Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. + Example 2: -Input: nums = [1,1,1,1] -Output: 6 -Explanation: Each pair in the array are good. -Example 3: + Input: nums = [1,1,1,1] + Output: 6 + Explanation: Each pair in the array are good. + Example 3: -Input: nums = [1,2,3] -Output: 0 + Input: nums = [1,2,3] + Output: 0 -Constraints: + Constraints: -1 <= nums.length <= 100 -1 <= nums[i] <= 100 + 1 <= nums.length <= 100 + 1 <= nums[i] <= 100 -Explanation of the below cpp code: + Explanation of the below cpp code: -This C++ program takes an integer n as input and then reads n integers from the standard input. -It then creates a vector v to store the input integers and a map m to count the frequency of each input integer. -Finally, the program computes the number of pairs of input integers that are equal and outputs this count to the standard output. + This C++ program takes an integer n as input and then reads n integers from the standard input. + It then creates a vector v to store the input integers and a map m to count the frequency of each input integer. + Finally, the program computes the number of pairs of input integers that are equal and outputs this count to the standard output. -The algorithm used to compute the count of pairs is based on the following observation: -for each integer x that appears k times in the input vector, there are k*(k-1)/2 pairs of integers that are equal to x. -This can be seen by choosing any two of the k occurrences of x, which can be done in k*(k-1)/2 ways. + The algorithm used to compute the count of pairs is based on the following observation: + for each integer x that appears k times in the input vector, there are k*(k-1)/2 pairs of integers that are equal to x. + This can be seen by choosing any two of the k occurrences of x, which can be done in k*(k-1)/2 ways. -The program uses the map data structure to count the frequency of each integer in the input vector. -It then iterates over the pairs (x,k) in the map and adds k*(k-1)/2 to a variable count. Finally, it outputs the value of count. + The program uses the map data structure to count the frequency of each integer in the input vector. + It then iterates over the pairs (x,k) in the map and adds k*(k-1)/2 to a variable count. Finally, it outputs the value of count. -Overall, this program has a time complexity of O(n log n) due to the use of the map data structure, which has a logarithmic time complexity for insertion and lookup operations. -However, since the input size is limited to 10^5 integers, the program should run efficiently for typical input sizes. + Overall, this program has a time complexity of O(n log n) due to the use of the map data structure, which has a logarithmic time complexity for insertion and lookup operations. + However, since the input size is limited to 10^5 integers, the program should run efficiently for typical input sizes. */ --------------------------------------------------------------------------//C++ code begins here--------------------------------------------------------------------------------- -//Array: Find Number of Good Pairs in Go #include using namespace std; @@ -54,18 +48,17 @@ int main() { cin>>n; vector v; map m; - for(int i=0;i>x; + cin >> x; v.push_back(x); m[x]++; } int count = 0; - for(auto it:m) + for(auto it: m) { - count = count + (it.second-1)*(it.second)/2; + count = count + (it.second - 1) * (it.second) / 2; } - cout< Date: Thu, 11 May 2023 00:03:40 +0530 Subject: [PATCH 1041/1894] #1201 solved --- Arrays/heap_sort.java | 82 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Arrays/heap_sort.java diff --git a/Arrays/heap_sort.java b/Arrays/heap_sort.java new file mode 100644 index 00000000..6bc66f94 --- /dev/null +++ b/Arrays/heap_sort.java @@ -0,0 +1,82 @@ +/* +Sorting: Implement Heap Sort in Java +*/ + +/* +APPROACH: Build Max Heap: The first step is to build a max heap from the given array. This is done by starting from the middle element of the array and heapifying each subtree in a bottom-up manner. Heapify operation ensures that the largest element is at the root of the subtree. + +Extract Elements: After building the max heap, the largest element (root) is at the top of the heap. We swap it with the last element of the heap and reduce the heap size by 1. Then, we heapify the root to maintain the heap property. We repeat this process until all the elements are extracted and the heap is empty. +*/ + +public class HeapSort { + + public void heapSort(int[] array) { + int length = array.length; + + // Build max heap + for (int i = length / 2 - 1; i >= 0; i--) + heapify(array, length, i); + + // Extract elements from the heap in sorted order + for (int i = length - 1; i > 0; i--) { + // Move current root to end + int temp = array[0]; + array[0] = array[i]; + array[i] = temp; + + // Heapify the reduced heap + heapify(array, i, 0); + } + } + + // Heapify a subtree rooted at index i + void heapify(int[] array, int length, int i) { + int largest = i; // Initialize largest as root + int leftChild = 2 * i + 1; // Left child index + int rightChild = 2 * i + 2; // Right child index + + // If left child is larger than root + if (leftChild < length && array[leftChild] > array[largest]) + largest = leftChild; + + // If right child is larger than largest so far + if (rightChild < length && array[rightChild] > array[largest]) + largest = rightChild; + + // If largest is not the root + if (largest != i) { + // Swap the root with the largest element + int swap = array[i]; + array[i] = array[largest]; + array[largest] = swap; + + // Recursively heapify the affected subtree + heapify(array, length, largest); + } + } + + // Utility function to print an array + void printArray(int[] array) { + int length = array.length; + for (int i = 0; i < length; ++i) + System.out.print(array[i] + " "); + System.out.println(); + } + + public static void main(String[] args) { + int[] array = { 12, 11, 13, 5, 6, 7 }; + int length = array.length; + + HeapSort heapSort = new HeapSort(); + heapSort.heapSort(array); + + System.out.println("Sorted array: "); + heapSort.printArray(array); + } +} +/* +Time Complexity: The time complexity of Heap Sort is O(n log n), where n is the number of elements in the array. The initial heap construction takes O(n) time, and the repeated heapify operation during extraction takes O(log n) time. As we perform heapify for each element, the overall time complexity is O(n log n). + +Space Complexity: The space complexity of Heap Sort is O(1) since the sorting is performed in-place, without requiring any additional space proportional to the input size. +*/ + From 2619686159759f1ac9f7387c981b902b2a613265 Mon Sep 17 00:00:00 2001 From: Mohamed Ashraf Hassan Date: Wed, 10 May 2023 21:49:28 +0300 Subject: [PATCH 1042/1894] Solved Well-Formed Parentheses (#428) --- Strings/well_formed_parentheses.java | 117 +++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Strings/well_formed_parentheses.java diff --git a/Strings/well_formed_parentheses.java b/Strings/well_formed_parentheses.java new file mode 100644 index 00000000..4bfe3d7a --- /dev/null +++ b/Strings/well_formed_parentheses.java @@ -0,0 +1,117 @@ +/** + + Time Complexity: O(2^n * n), Space Complexity: O(n). + + Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + + Example 1: + Input: n = 3 + Output: ["((()))","(()())","(())()","()(())","()()()"] + + + Example 2: + Input: n = 1 + Output: ["()"] + + + Constraints: + + 1 <= n <= 8 + + +**/ + + +class Solution { + + + public List generateParenthesis(int n) { + + ArrayList validParenthesis = new ArrayList(); + /** + We need to generate every n pair valid parenthses. + + What we are going to do is try every possible combination + if we have a 2 pair parenthes p: ???? + each question mark could be '(' or ')'. + ex: ()() or (()) or ((() + so we have a total of (2 ^ (2 * n)) combination. + + if we say that an open bracket '(' can be expressed as 0 + and a closed bracket ')' can be expressed 1. + + 0000 -> (((( + 0001 -> ((() + 0010 -> (()( + 0011 -> (()) + 0100 -> ()(( + 0101 -> ()() + . + . + . + . + . + 1111 -> )))) + + **/ + for (int i = 0; i < (1 << (2 * n)); ++i) + { + String aParenthesis = ""; + for(int j = 0; j < 2 * n; ++j) + { + if(((i >> j) & 1) == 1) + { + aParenthesis += '('; + } + else + aParenthesis += ')'; + } + if(isValid(aParenthesis)) + validParenthesis.add(aParenthesis); + } + + return validParenthesis; + } + + + /** + Function: isValid check if parenthesis is balanced or not. + + + For each open bracket we find we pushed it to the stack. + + If We find a closed bracket we check the top of the stack + if it is an open bracket that's mean we find a corrsponding closing bracket so, we removed it. + + else the top of the stack is a closed bracket that means there is no open bracket that matches that closed bracket, + that's means the parenthesis is NOT valid or balanced so, we return false. + + + At the end if we find that the stack is empty that's mean that each open breack has a corrsponding closed bracket, + so, we return true otherwise we return false. + **/ + + public boolean isValid(String s) { + + int n = s.length(); + Stack st = new Stack(); + + for(int i = 0; i < n; ++i) + { + char ch = s.charAt(i); + if( ch == '(') + { + st.push(ch); + } + else + { + if(!st.empty() && st.peek() == '(') + st.pop(); + else + return false; + } + } + + return st.empty(); + } +} From 8edba322be623773a4eb9fe757fa42f1597bd32a Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Thu, 11 May 2023 01:39:28 +0530 Subject: [PATCH 1043/1894] Create Heap_Sort.py Heap Sort program in Python issue resolved as was assigned to me --- sorting/Heap_Sort.py | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sorting/Heap_Sort.py diff --git a/sorting/Heap_Sort.py b/sorting/Heap_Sort.py new file mode 100644 index 00000000..abb171a0 --- /dev/null +++ b/sorting/Heap_Sort.py @@ -0,0 +1,48 @@ + +Heap sort is a sorting algorithm that works by transforming an unsorted list into a heap data structure, +which is a binary tree where each parent node is greater than or equal to its children if any. +then it repeatedly extracts the maximum element from the heap and puts it into its correct sorted position until the whole list is sorted. + +def heap_sort(arr): + # Build the initial heap + n = len(arr) + for i in range(n // 2 - 1, -1, -1): + heapify(arr, n, i) + + # Extract the maximum element repeatedly + for i in range(n - 1, 0, -1): + arr[0], arr[i] = arr[i], arr[0] # Swap + heapify(arr, i, 0) + + return arr + +def heapify(arr, n, i): + largest = i + left = 2 * i + 1 + right = 2 * i + 2 + + # Check if left child is larger than root + if left < n and arr[left] > arr[largest]: + largest = left + + # Check if right child is larger than root + if right < n and arr[right] > arr[largest]: + largest = right + + # Swap if necessary and heapify the affected subtree + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + heapify(arr, n, largest) +ere's how the algorithm works: + +The heap_sort function takes an unsorted list arr as input. +It starts by building the initial heap by calling the heapify function on each parent node in the tree. +It does this by iterating over the parent nodes in reverse order (starting from the last parent node), +and calling heapify on each of them. This builds a heap where each parent node is greater than or equal to its children. +It then repeatedly extracts the maximum element from the heap and puts it into its correct sorted position. +It does this by swapping the maximum element (which is always at the root of the heap) with the last element in the heap, +and then calling heapify on the root node to restore the heap property. +Finally, it returns the sorted list. + +Sample_input : [5,16,8,14,20,1,26] +Sample_output : [1,5,8,14,16,20,26] From ea9d37aacf42ad061dd663ba6af21ea77983fd05 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Thu, 11 May 2023 01:45:33 +0530 Subject: [PATCH 1044/1894] Update Heap_Sort.py --- sorting/Heap_Sort.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sorting/Heap_Sort.py b/sorting/Heap_Sort.py index abb171a0..75ef3f1b 100644 --- a/sorting/Heap_Sort.py +++ b/sorting/Heap_Sort.py @@ -3,6 +3,9 @@ which is a binary tree where each parent node is greater than or equal to its children if any. then it repeatedly extracts the maximum element from the heap and puts it into its correct sorted position until the whole list is sorted. +Sample_input : [5,16,8,14,20,1,26] +Sample_output : [1,5,8,14,16,20,26] + def heap_sort(arr): # Build the initial heap n = len(arr) @@ -37,12 +40,11 @@ def heapify(arr, n, i): The heap_sort function takes an unsorted list arr as input. It starts by building the initial heap by calling the heapify function on each parent node in the tree. -It does this by iterating over the parent nodes in reverse order (starting from the last parent node), +It does this by iterating over the parent nodes in reverse order starting from the last parent node, and calling heapify on each of them. This builds a heap where each parent node is greater than or equal to its children. It then repeatedly extracts the maximum element from the heap and puts it into its correct sorted position. -It does this by swapping the maximum element (which is always at the root of the heap) with the last element in the heap, +It does this by swapping the maximum element which is always at the root of the heap with the last element in the heap, and then calling heapify on the root node to restore the heap property. Finally, it returns the sorted list. -Sample_input : [5,16,8,14,20,1,26] -Sample_output : [1,5,8,14,16,20,26] + From 64805586a98d809c6850b3237b334e55ddd3825e Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Thu, 11 May 2023 16:13:38 +0530 Subject: [PATCH 1045/1894] added heapsort code with best time complexity --- sorting/heap_sort.class | Bin 0 -> 1521 bytes sorting/heap_sort.java | 74 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 sorting/heap_sort.class create mode 100644 sorting/heap_sort.java diff --git a/sorting/heap_sort.class b/sorting/heap_sort.class new file mode 100644 index 0000000000000000000000000000000000000000..3767d31617b28770499aa1267ae7cddbc2738c0d GIT binary patch literal 1521 zcmaJ=T~8ZF6g}hpvbRex1Op*na8gKYZ)zIaI!Vn(2ofq1)Ri1jSyXBk*un<0Yk8MQ zyyri(QXeWsmGa!GB2`-P1Nt-in8!X=P3Re~8;C%CnYnZ4-gD2nGxv`-FOLB%;DL!0 z6a%US4Z1+~vHQfGZn?qEbba%&w-pQMvwq;m^8!k-v~D7ei~-Zad$0sDyPn(rItn|C zGoAT`VC|)3}Emb?8adfd;5e8515%-?N;@}=`T8d5I5qE=kC`A zNpQ$Q4#NT?`|h5%6b4&v{G}i7(u!g?h$H3}S4v5Gmo#(zV5eqc6juz4S-6V4z~u|@ z1+=!TCLzuPNTs6~w=f~QVss;0fmE-^<+_FUF)5%X(lrV$t*3EApufRpc-sZH({T?A zek5Uv5+*P6$`%}%XLbP>Weh=H;^ zf#KrDMTCjk2oE}2-m))~FTH)5id4_`KM2D(iaTz5&5L)#?WkYJCnl=6W8kjr^F4vd z)93etC*htqoisFQ{j$3ihaEEh?rg_;feGkmZm`|*qRG`T+&gI3&htFuc_;DVVcWYP z{H)UCL)OkdcMoF8ZM7PH?A6k!38X|pz*-3cud~#0qsWU4@cT}k({>SM1NQ~S|38#7 zk?6xUzG;g86r3J@DCk^o@nmxs(p!E3@e>V!54g%}K;g>Y!&QcU3zdn$edl;CueH?e zdHZ{0%TC@tg7H*2d4BR&K5-TtrBYQL#jz`O$IhwsvSTa%1^p?jq`FlqoK0CvK?Z#= zF~oh0qj(+txQQ%d1~5bKJ^B_fj0&R%puR>%h`*8j2MV_WogDEV$zMn^P0v?$Rn_cW z^-)#hrah|aIW7MTgHBGXI61ZQBaEC@Rdagc)ZaRFI#v4z*d$*y99st0x#SG0$mdkb zI2BMOZIH6U={1ojxp9)8zzz2M4y_udu*lOg<*cEI2FloAGo=s{${Wt15JMAW%wg*( zaEYeyeyV&ttIXxEKEue*=qu+dFL4<-!pPHDj|!rCq82-jGCaOwy*onKKp{Wb}SyHx)vN>pFL9LIK^r-d#t`S3F&1u7OKCU`T; MlSyliF^jnJFII9tl>h($ literal 0 HcmV?d00001 diff --git a/sorting/heap_sort.java b/sorting/heap_sort.java new file mode 100644 index 00000000..bf90fc4b --- /dev/null +++ b/sorting/heap_sort.java @@ -0,0 +1,74 @@ +/*Since the tree satisfies Max-Heap property, then the largest item is stored at the root node. + +Swap: Remove the root element and put at the end of the array (nth position) Put the last item of the tree (heap) at the vacant place. + +Remove: Reduce the size of the heap by 1. + +Heapify: Heapify the root element again so that we have the highest element at root. + +The process is repeated until all the items of the list are sorted.*/ + +// Heap Sort in Java + +public class heap_sort { + + public void sort(int arr[]) { + int n = arr.length; + + // Build max heap + for (int i = n / 2 - 1; i >= 0; i--) { + heapify(arr, n, i); + } + + // Heap sort + for (int i = n - 1; i >= 0; i--) { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Heapify root element + heapify(arr, i, 0); + } + } + + void heapify(int arr[], int n, int i) { + // Find largest among root, left child and right child + int largest = i; + int l = 2 * i + 1; + int r = 2 * i + 2; + + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + // Swap and continue heapifying if root is not largest + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + heapify(arr, n, largest); + } + } + + // Function to print an array + static void printArray(int arr[]) { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver code + public static void main(String args[]) { + int arr[] = { 1, 12, 9, 5, 6, 10 }; + + heap_sort hs = new heap_sort(); + hs.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } + } From d96a44068250ca29722787bdf8e620e8f01628ca Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Thu, 11 May 2023 16:42:53 +0530 Subject: [PATCH 1046/1894] added maximum rectangle problem solution --- .../Maximum_rectangle_problem.class | Bin 0 -> 1138 bytes .../Maximum_rectangle_problem.java | 32 ++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 Dynamic Programming/Maximum_rectangle_problem.class create mode 100644 Dynamic Programming/Maximum_rectangle_problem.java diff --git a/Dynamic Programming/Maximum_rectangle_problem.class b/Dynamic Programming/Maximum_rectangle_problem.class new file mode 100644 index 0000000000000000000000000000000000000000..93986dbec61063bca8add9cffe21a61ff94ba8b5 GIT binary patch literal 1138 zcmZ`&OHUI~6#j1Kaob_AUErgpMl%U_p^Ct%>_RZnFbw=Xkw7_mbJ*x9F7eCxn)0x!O(CLPUReH&MIhVMyrlC z1R1<`&KWl|MayMQiB!9eGYHY1DoLrZZNSqzo?2(sBI5cFuZG%uZW{M4r-73avu)W%O0L z_rPA0!w@Gc(tt!ZfgZ9{>ZvD~j|zOz$_BKk)LYqvBJD&g!u_Zn(E$%D!+^i8xGT!h3b@Bz)cXoLr^i)eVpD! z$Kx{Yh~)X>WYQaQ8N6{9zX7j7I-3kto~@yno!`f$fs$G+sibhtRXY{hp%!`Ec8$Xz zU!j-55rmhz?W2}y=tmvK$e*CtB>XTDz#9J^emPeuYB+Bgl+M8aaH- k7$TkyR$mn|YY-wQ*cfs7|CNy_eF%Q&GSW~a-Sgl02_SFa!T 0 ? m[i - 1][j] + 1 : 1; + } + } + + int maxArea = 0; + for (int i = 0; i < m.length; i++) { + Stack s = new Stack(); + for (int j = 0; j <= m[0].length; j++) { + int h = j == m[0].length ? 0 : m[i][j]; + if (s.isEmpty() || h >= m[i][s.peek()]) { + s.push(j); + } else { + int tp = s.pop(); + maxArea = Math.max(maxArea, m[i][tp] * (s.isEmpty() ? j : j - 1 - s.peek())); + j--; + } + } + } + return maxArea; + } + +} From f5888abff7c50e7cb67af4eeedf9b3288bd4d859 Mon Sep 17 00:00:00 2001 From: jayesh-RN <100137975+jayesh-RN@users.noreply.github.com> Date: Thu, 11 May 2023 19:45:56 +0530 Subject: [PATCH 1047/1894] Validate BST --- Trees/Binary Search Trees/Validate_BST.cpp | 81 ++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Trees/Binary Search Trees/Validate_BST.cpp diff --git a/Trees/Binary Search Trees/Validate_BST.cpp b/Trees/Binary Search Trees/Validate_BST.cpp new file mode 100644 index 00000000..0a183188 --- /dev/null +++ b/Trees/Binary Search Trees/Validate_BST.cpp @@ -0,0 +1,81 @@ +// VALIDATE BINARY SEARCH TREE --->> LEETCODE + + + +// Given the root of a binary tree, determine if it is a valid binary search tree (BST). + +// A valid BST is defined as follows: + +// The left +// subtree +// of a node contains only nodes with keys less than the node's key. +// The right subtree of a node contains only nodes with keys greater than the node's key. +// Both the left and right subtrees must also be binary search trees. + +// ALGORITHM--> +// Follow these steps while the current node is not null: +// Process the current node and go to its right child if it doesn't have a left child. +// Find the inorder predecessor of the current node—that is, the rightmost node in the left subtree—if the present node has a left child, and see if its value is smaller than the value of the current node. + +// If the predecessor's right child is null, go to the current node's left child and change the predecessor's right child to point to it. +// In order to restore the binary tree's original structure, reset the predecessor's right child to null, process the current node, and then move to its right child if it is already referring to the current node. + + + + + +#include +using namespace std; + +struct Node { + int data; + struct Node *left, *right; + + Node(int data) + { + this->data = data; + left = right = NULL; + } +}; + + +bool validate(Node* root,long long int min , long long int max){ + if(!root) + return true; + bool ans = false; + if(root->datadata>min) + ans = true; + else + return ans; + return ans && validate(root->left,min,root->data) && + validate(root->right,root->data,max); +} + + + bool isValidBST(Node* root) { + if(!root) + return true; + return validate(root ,-9223372036854775807,9223372036854775807 ); + } + +int main() +{ + struct Node* root = new Node(3); + root->left = new Node(2); + root->right = new Node(5); + root->left->left = new Node(1); + root->left->right = new Node(4); + + if (isValidBST(root)) + cout << "Is BST"; + else + cout << "Not a BST"; + + return 0; +} + + + + +// T.C. O(N) +// S.C. O(N) ---> for Auxillary stack \ No newline at end of file From 753fe4dadf18d681a084fa94960cb3c4dd1854f3 Mon Sep 17 00:00:00 2001 From: Mohit Verma <112820522+mohitvdx@users.noreply.github.com> Date: Thu, 11 May 2023 20:43:33 +0530 Subject: [PATCH 1048/1894] added tim_sort in java --- sorting/.DS_Store | Bin 0 -> 10244 bytes sorting/Tim sort java/tim_sort.class | Bin 0 -> 2184 bytes sorting/Tim sort java/tim_sort.java | 106 +++++++++++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 sorting/.DS_Store create mode 100644 sorting/Tim sort java/tim_sort.class create mode 100644 sorting/Tim sort java/tim_sort.java diff --git a/sorting/.DS_Store b/sorting/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d9dfc2dc03d63c313806fd98ca8f3791cafbcd60 GIT binary patch literal 10244 zcmeI1F>ezw6vv-Kg(4+snsx@=gb)%H{RW{519RC+a*fiox!gfhB)04K7tX$Jb{^LxGD5v*cYk439gn$qb0zyCtYy$y&XLD(`jFqbp5CTHr9|3+pB&clr zrCl1UUmdvUBLM6U9_xa8oCCBbDQ&;BOJlVZKF#Stl~Pq6F_e+x^Msqj_Dj1o*2qa2 zIjOQ|Ri03k?j5>BHz(CMR<1%o2>1l}?B1ghU89bi^ZSAhDaDf^&huBVXL&lBqv{Feu2wy&X!oMp3yk~&4J-Oj6@9$#i|VY^?~Szu zeRTV6OoG~!E|D==(DO29!p!}CdCXre+Gflv?JD2GT8|eoYg=o0g|uN_%-hyK*1UcF zDNQM(LPt=BIn6PvA?g&lpt+7DKMpvGY~LL^hjIun_MB4uU5OyQ61K7(REAf<*6m|_ zbFd#HU$q)*P2U{*>Y23~y&50EHE}!~)Od)ljN_$l9KpD{lLwC{uY==Z7csyrC%D#d za;#sE6BFJ@>2m^MN4c-}CTEq?P4}k)YsW{g#)rp^i8~$+ zYCHt_F@48N-8g)XyaG4Y3e|qAsHZGvXZm0(arje@Ddru=-x3oK22S z(mX5hHeZ!Bt+RYEDF2ga{`x$=`SS25=1FT6XLnQ-=iZ3gI)1X+-Nw=5665a$R~ICv zqsCUY0zG;wq@%=Etq6)00zyCt2mv8*Uj!Z)$4LwJRs8q=`|4i&3IQRo1q9U2;AC)& zfvCt}IM<$_zD4E2?Uu%B2`)Mv53AGh_=D5&oLl6!FW7RyeZRCzWAOy#zyBCupNi%D XA3V=+p36DE%K1N*g$VN7_VfQ=q>4}u literal 0 HcmV?d00001 diff --git a/sorting/Tim sort java/tim_sort.class b/sorting/Tim sort java/tim_sort.class new file mode 100644 index 0000000000000000000000000000000000000000..6bb5f363bec860e7ce0227224ecf615681a71003 GIT binary patch literal 2184 zcmaJ?T~8ck6nN#}GwKhN7Yx z>NDn3%N5ru(aKq(lRn`GDma;Q<$~=_xn;{N4JfEZoeWLI9@IbaUUCb?%t*OxE>{Gi zu0z{`JtxrAeR;em2;=7y$Or0~ccTg&O#;m&bHN&Q>>1O&P;lqTRb10{8RtOv^Pal| zQ_zA|8Eq=!Fa#QQNm@W&^hzk&tZKKY(+b+rA)`~p3)t(GP$*rgIAx+Blb!Op2#Xo- znXZRGqk{c7Amc?9-RKdh-G+S9bmxg+sldI$-Ek^er#ZSNMKMR2;?2j8wA9a~2cx?dc#OjXJZG)J+s@>+DkLs#QL3UM*50 zl}vAQV!sQ1bgY?j&6$NsbJ4e#F(^=Vd7QBaXNp^6qD(nULNI)U=**(IOTP9OrUEUkb-@~S+Fue>w`v*nKQ0aUKaRtXEU}8 zgP^BPd$wp*x+WZFVQF#T`AT+3o^d?CylCxWz7vb!R1EB#rL7R7X0bR`aIJwTP7CZg zX9TnK8nDV(2xHg45s><(4ns+bI1{ns^X+sB}ZYGq$KK7>zr+B}d z<@y5U?^4rG>t;kYP$kx3Y#<~yc-61t;5yqI^X`_dNB_-Wc`XhRn zR1Wn;^{6i0LSt)0k0#@KG|%LsOy}=F6~2Y0R+%b8%5N+GqB7JMi}xvk_c1-D)AEoP zBu(>J`Zns5y5g_>c&PK1o+i5z6Dx{WaNw)&wDT2@f@r?t8IMQX5ZV0pfQL&a2r33p zk3oKwh6vNE1Z@aMFhV+tGkl+8b8{HO98SZf50J%&)O?J$@CnZ2CZ_QPoBt&) z;wxOjcX%83@eY3EFg!rshq@QaCb#96d_Z_VzC9LLM{_VIt&b6=left && arr[j]>temp) + { + arr[j+1]=arr[j]; + j--; + } + arr[j+1]=temp; + } + } + public static void merge(int[] arr,int left,int mid,int right) + { + int len1=mid-left+1; + int len2=right-mid; + int[] leftArr=new int[len1]; + int[] rightArr=new int[len2]; + for(int i=0;i Date: Thu, 11 May 2023 20:45:49 +0530 Subject: [PATCH 1049/1894] added tim sort in java --- sorting/.DS_Store | Bin 10244 -> 10244 bytes sorting/Tim sort java/tim_sort.class | Bin 2184 -> 0 bytes sorting/{Tim sort java => }/tim_sort.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 sorting/Tim sort java/tim_sort.class rename sorting/{Tim sort java => }/tim_sort.java (100%) diff --git a/sorting/.DS_Store b/sorting/.DS_Store index d9dfc2dc03d63c313806fd98ca8f3791cafbcd60..bb12766ea00fbf5af08e31ade7d4818a460a69ed 100644 GIT binary patch delta 49 zcmZn(XbG6$I9U^hRb(qTAb>?3Ll#3KLm5M2PP$=ma(-?BSRI7GqdGU=#U&{xKMAOid7wup-x5(`V*I&TNn#`0W_E>7?A%Ch1pth# BMjHSC diff --git a/sorting/Tim sort java/tim_sort.class b/sorting/Tim sort java/tim_sort.class deleted file mode 100644 index 6bb5f363bec860e7ce0227224ecf615681a71003..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2184 zcmaJ?T~8ck6nN#}GwKhN7Yx z>NDn3%N5ru(aKq(lRn`GDma;Q<$~=_xn;{N4JfEZoeWLI9@IbaUUCb?%t*OxE>{Gi zu0z{`JtxrAeR;em2;=7y$Or0~ccTg&O#;m&bHN&Q>>1O&P;lqTRb10{8RtOv^Pal| zQ_zA|8Eq=!Fa#QQNm@W&^hzk&tZKKY(+b+rA)`~p3)t(GP$*rgIAx+Blb!Op2#Xo- znXZRGqk{c7Amc?9-RKdh-G+S9bmxg+sldI$-Ek^er#ZSNMKMR2;?2j8wA9a~2cx?dc#OjXJZG)J+s@>+DkLs#QL3UM*50 zl}vAQV!sQ1bgY?j&6$NsbJ4e#F(^=Vd7QBaXNp^6qD(nULNI)U=**(IOTP9OrUEUkb-@~S+Fue>w`v*nKQ0aUKaRtXEU}8 zgP^BPd$wp*x+WZFVQF#T`AT+3o^d?CylCxWz7vb!R1EB#rL7R7X0bR`aIJwTP7CZg zX9TnK8nDV(2xHg45s><(4ns+bI1{ns^X+sB}ZYGq$KK7>zr+B}d z<@y5U?^4rG>t;kYP$kx3Y#<~yc-61t;5yqI^X`_dNB_-Wc`XhRn zR1Wn;^{6i0LSt)0k0#@KG|%LsOy}=F6~2Y0R+%b8%5N+GqB7JMi}xvk_c1-D)AEoP zBu(>J`Zns5y5g_>c&PK1o+i5z6Dx{WaNw)&wDT2@f@r?t8IMQX5ZV0pfQL&a2r33p zk3oKwh6vNE1Z@aMFhV+tGkl+8b8{HO98SZf50J%&)O?J$@CnZ2CZ_QPoBt&) z;wxOjcX%83@eY3EFg!rshq@QaCb#96d_Z_VzC9LLM{_VIt&b6 Date: Thu, 11 May 2023 21:05:42 +0530 Subject: [PATCH 1050/1894] added tim sort in go Lang --- sorting/tim_sort.go | 118 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 sorting/tim_sort.go diff --git a/sorting/tim_sort.go b/sorting/tim_sort.go new file mode 100644 index 00000000..7c30ead6 --- /dev/null +++ b/sorting/tim_sort.go @@ -0,0 +1,118 @@ +// File: tim_sort.go +//Implementation of Tim Sort +//Tim Sort makes use of insertionSort and Merge function of MergeSort +//The basic idea is to divide the input array into blocks called as runs +//The size of runs varies from 32 to 64, and perform insertion sort on the runs +//Then, The runs(blocks) are merged to form the final sorted array +// +//Time Complexity of this algorithm in Best case is O(n),Average case is O(n*log(n)) +//Time Complexity in Worst case is O(n*log(n)). +//This is a stable sorting algorithm +//This algorithm uses Space of O(n) +//This algorithm is used in languages like Java and Python for sorting. + +package main + +import ( + "fmt" + "math" +) + +func main() { + + arr := []int{43, 56, 2, 99, 1, 64, 23, 78, 34, 11, 90, 45, 32, 67, 88, 12, 9, 10, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} + n := len(arr) + fmt.Printf("Before Sorting\n") + printArray(arr, n) + timSort(arr, n) + fmt.Printf("Sorted Array is\n") + printArray(arr, n) +} + +func timSort(arr []int, n int) { + + run := 32 + // you can take any value between 32 to 64, it actually is some empirical result from insertion s + for i := 0; i < n; i += run { + insertionSort(arr, i, int(math.Min(float64(i + 31), float64(n - 1)))) + } + + for size := run; size < n; size = 2 * size { + for left := 0; left < n; left += 2 * size { + mid := left + size - 1 + right := int(math.Min(float64(left + 2 * size - 1), float64(n - 1))) + merge(arr, left, mid, right) + } + } +} + +func insertionSort(arr []int, left int, right int) { + for i := left + 1; i <= right; i++ { + j := i + for j > left && arr[j] < arr[j - 1] { + arr[j], arr[j - 1] = arr[j - 1], arr[j] + j-- + } + } +} + +func merge(arr []int, left int, mid int, right int) { + + // function to merge the two sorted arrays + len1 := mid - left + 1 + len2 := right - mid + leftArr := make([]int, len1) + rightArr := make([]int, len2) + + for i := 0; i < len1; i++ { + leftArr[i] = arr[left + i] + } + for j := 0; j < len2; j++ { + rightArr[j] = arr[mid + 1 + j] + } + + i := 0 + j := 0 + k := left + + for i < len1 && j < len2 { + if leftArr[i] <= rightArr[j] { + arr[k] = leftArr[i] + i++ + } else { + arr[k] = rightArr[j] + j++ + } + k++ + } + + for i < len1 { + arr[k] = leftArr[i] + i++ + k++ + } + + for j < len2 { + arr[k] = rightArr[j] + j++ + k++ + } +} + + +// Function to print the array +func printArray(arr []int, n int) { + for i := 0; i < n; i++ { + fmt.Printf("%d ", arr[i]) + } + fmt.Printf("\n") +} + +// to run in terminal +// $ go run tim_sort.go + +// Output +// Before Sorting +// 43 56 2 99 1 64 23 78 34 11 90 45 32 67 88 12 9 10 3 4 5 6 7 8 9 10 11 12 13 14 15 +// Sorted Array is +// 1 2 3 4 5 6 7 8 9 9 10 10 11 11 12 12 13 14 15 23 32 34 43 45 56 64 67 78 88 90 99 From 78a40bfda9614ef8ebac9f9cdbbc69b81968e725 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 11 May 2023 23:58:25 +0530 Subject: [PATCH 1051/1894] add min height BST --- Trees/Binary Search Trees/min_height_BST.go | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Trees/Binary Search Trees/min_height_BST.go diff --git a/Trees/Binary Search Trees/min_height_BST.go b/Trees/Binary Search Trees/min_height_BST.go new file mode 100644 index 00000000..6c3e83d0 --- /dev/null +++ b/Trees/Binary Search Trees/min_height_BST.go @@ -0,0 +1,48 @@ +package main + +func MinHeightBST(array []int) *BST { + // call helper method with start index, end index array and nil node + return constructMinHeightBST(array, nil, 0, len(array)-1) +} + +func constructMinHeightBST(array []int, bst *BST, start int, end int) *BST { + // base case + if end < start { + return nil + } + mid := (start + end) / 2 + value := array[mid] + // there are no value in bst + if bst == nil { + bst = &BST{Value: value} + } else { + bst.Insert(value) + } + constructMinHeightBST(array, bst, start, mid-1) + constructMinHeightBST(array, bst, mid+1, end) + return bst +} + +type BST struct { + Value int + + Left *BST + Right *BST +} + +func (tree *BST) Insert(value int) *BST { + if value < tree.Value { + if tree.Left == nil { + tree.Left = &BST{Value: value} + } else { + tree.Left.Insert(value) + } + } else { + if tree.Right == nil { + tree.Right = &BST{Value: value} + } else { + tree.Right.Insert(value) + } + } + return tree +} From 7bb6206985482506d0da362b7c5400ed4a23f9bd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 11 May 2023 23:58:54 +0530 Subject: [PATCH 1052/1894] add explanation --- Trees/Binary Search Trees/min_height_BST.go | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Trees/Binary Search Trees/min_height_BST.go b/Trees/Binary Search Trees/min_height_BST.go index 6c3e83d0..c1fbbede 100644 --- a/Trees/Binary Search Trees/min_height_BST.go +++ b/Trees/Binary Search Trees/min_height_BST.go @@ -1,3 +1,49 @@ +/* + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + + The function follows these steps: + + Base Case: If end < start, it means there are no elements to consider in the current range, so it returns nil indicating an empty subtree. + + Calculate the mid index as the midpoint of the current range (start and end). + + Get the value from the array at the mid index. + + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. Otherwise, insert the value into the existing bst using the Insert method. + + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. This constructs the left subtree. + + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. This constructs the right subtree. + + Finally, return the bst which represents the constructed minimum height BST. + + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and Left and Right fields to point to the left and right child nodes, respectively. + + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the array and inserting the mid-value into the BST, ensuring a balanced structure. + + Time Complexity: + + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where n is the number of elements in the array. + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), where n is the number of elements in the array. + + Space Complexity: + + The space complexity is determined by the stack space used during recursive calls and the space required to store the BST. + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of elements (n), the space complexity becomes O(n). + The space required to store the BST is also O(n) in the worst case since each element in the array is inserted into the BST. + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. + In summary, the time complexity is O(n log n) and the space complexity is O(n). + + + +*/ package main func MinHeightBST(array []int) *BST { From 64e54a43f4736682a00f2a0612d37d8c17833d2c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 00:03:25 +0530 Subject: [PATCH 1053/1894] update documentation --- Trees/Binary Search Trees/min_height_BST.go | 67 ++++++++++++++++----- 1 file changed, 52 insertions(+), 15 deletions(-) diff --git a/Trees/Binary Search Trees/min_height_BST.go b/Trees/Binary Search Trees/min_height_BST.go index c1fbbede..17a004af 100644 --- a/Trees/Binary Search Trees/min_height_BST.go +++ b/Trees/Binary Search Trees/min_height_BST.go @@ -1,9 +1,28 @@ /* - The given code is used to construct a minimum height binary search tree (BST) from a sorted array. The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. - The MinHeightBST function serves as a wrapper function that initializes the construction process by calling the constructMinHeightBST helper function. + Write a function that takes in a non-empty sorted array of distinct integers, constructs a BST from the integers, and returns the root of the BST. + The function should minimize the height of the BST. + Smple Input : [1, 2, 5, 7, 10, 13, 14, 15, 22] + Output: - The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + 10 + / \ + 2 14 + / \ / \ + 1 5 13 15 + \ \ + 7 22 + + Explanation: + + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. + The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling + the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, + a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. The function follows these steps: @@ -13,31 +32,49 @@ Get the value from the array at the mid index. - If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. Otherwise, insert the value into the existing bst using the Insert method. + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. + Otherwise, insert the value into the existing bst using the Insert method. - Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. This constructs the left subtree. + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. + This constructs the left subtree. - Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. This constructs the right subtree. + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. + This constructs the right subtree. Finally, return the bst which represents the constructed minimum height BST. - The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and Left and Right fields to point to the left and right child nodes, respectively. + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and + Left and Right fields to point to the left and right child nodes, respectively. - The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to + insert the value based on the comparison with the current node's value and updates the left or right child accordingly. - Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the array and inserting the mid-value into the BST, ensuring a balanced structure. + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the + array and inserting the mid-value into the BST, ensuring a balanced structure. Time Complexity: - The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where n is the number of elements in the array. - The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, as it involves traversing the height of the BST to find the appropriate position to insert the value. - Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), where n is the number of elements in the array. + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like + operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where + n is the number of elements in the array. + + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, + as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), + where n is the number of elements in the array. Space Complexity: - The space complexity is determined by the stack space used during recursive calls and the space required to store the BST. - The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of elements (n), the space complexity becomes O(n). - The space required to store the BST is also O(n) in the worst case since each element in the array is inserted into the BST. + The space complexity is determined by the stack space used during recursive calls and the space required + to store the BST. + + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of + the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of + elements (n), the space complexity becomes O(n). + + The space required to store the BST is also O(n) in the worst case since each element in the array is + inserted into the BST. + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. In summary, the time complexity is O(n log n) and the space complexity is O(n). From d19c49813138efdfed2a2c952bfe32709089d113 Mon Sep 17 00:00:00 2001 From: Niraj Date: Fri, 12 May 2023 07:54:59 +0530 Subject: [PATCH 1054/1894] #516 Number of Substrings with only 1's --- Math/number_of_substring_with_only_1.js | 47 +++++++++++++ sorting/heap_sort.py | 90 ++++++++++++------------- 2 files changed, 92 insertions(+), 45 deletions(-) create mode 100644 Math/number_of_substring_with_only_1.js diff --git a/Math/number_of_substring_with_only_1.js b/Math/number_of_substring_with_only_1.js new file mode 100644 index 00000000..dcf04736 --- /dev/null +++ b/Math/number_of_substring_with_only_1.js @@ -0,0 +1,47 @@ +// Program Author : TheCodeVenturer[Niraj Modi] +/* + Program Definition : Number of Substrings With Only 1s in Javascript + Description : We are required to find no.of substrings with only 1's is possible + + Approach: + BruteForce : + we can create a nested loop to find each substring from each each 1's positions. Which will require O(n^2) complexity for worst Cases. + Optimal Approach: + Using Mathematical Formula + No.of Substrings = n*(n+1)/2 n <- size of string + we are only required to find substrings which only consists of 1 + + now for this we will apply this formula for all group of ones so that total no.of substrings can be generated + [Note: for each group of use the formula and add the result to 2nd variable sol and set count to zero for next group of ones] + Sample input/outputs: + Example 1: + Input: "0110111" + Output: 9 + + Example 2: + Input: "101" + Output: 2 + + Example 3: + Input: "1111111" + Output: 28 + */ +const mod = 1e9+7 // For handling the overflow of integer +var numSub = function(s) { + var sol=0; //Solution variable which will be return finally + for(let i=0;i arr[largest]: + largest = left + + # Check if right child is larger than root + if right < n and arr[right] > arr[largest]: + largest = right + + # Swap if necessary and heapify the affected subtree + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] + heapify(arr, n, largest) +ere's how the algorithm works: -def heap_sort(arr: list[int]) -> None: - heap_size = len(arr) - build_max_heap(arr, heap_size) - source_idx = 0 - for dest_idx in range(len(arr) - 1, 0, -1): - arr[source_idx], arr[dest_idx] = arr[dest_idx], arr[source_idx] - heap_size -= 1 - max_heapify(arr, 0, heap_size) +The heap_sort function takes an unsorted list arr as input. +It starts by building the initial heap by calling the heapify function on each parent node in the tree. +It does this by iterating over the parent nodes in reverse order starting from the last parent node, +and calling heapify on each of them. This builds a heap where each parent node is greater than or equal to its children. +It then repeatedly extracts the maximum element from the heap and puts it into its correct sorted position. +It does this by swapping the maximum element which is always at the root of the heap with the last element in the heap, +and then calling heapify on the root node to restore the heap property. +Finally, it returns the sorted list. -def build_max_heap(arr: list[int], heap_size: int) -> None: - """Modifies the input array into a max heap. A tree binary tree structure in every node - satisfies the property: parent node > left node and parent node > right node""" - for idx in range((heap_size // 2) - 1, -1, -1): - max_heapify(arr, idx, heap_size) -def max_heapify(arr: list[int], idx: int, heap_size: int) -> None: - """ - A recursive function that recursively modifies sub roots - of the tree indicated by the idx into a max heap - """ - left_idx = idx + 1 - right_idx = idx + 2 - if left_idx < heap_size and arr[idx] < arr[left_idx]: - largest = left_idx - else: - largest = idx - if right_idx < heap_size and arr[largest] < arr[right_idx]: - largest = right_idx - if largest != idx: - arr[idx], arr[largest] = arr[largest], arr[idx] - return max_heapify(arr, largest, heap_size) - -if __name__ == "__main__": - main() \ No newline at end of file From f0e2be35e6418b53740e0e6b1a849205d9d4e15d Mon Sep 17 00:00:00 2001 From: Niraj Date: Fri, 12 May 2023 07:59:15 +0530 Subject: [PATCH 1055/1894] Added Comiit to #516 --- Math/number_of_substring_with_only_1.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Math/number_of_substring_with_only_1.js b/Math/number_of_substring_with_only_1.js index dcf04736..1edd5872 100644 --- a/Math/number_of_substring_with_only_1.js +++ b/Math/number_of_substring_with_only_1.js @@ -13,6 +13,9 @@ now for this we will apply this formula for all group of ones so that total no.of substrings can be generated [Note: for each group of use the formula and add the result to 2nd variable sol and set count to zero for next group of ones] + Complexity: + The time complexity of this solution is O(n) because i will parent and nested folder will together run for n times only. + The space complexity is O(1),we are not using any Auxiliary Spaces. Sample input/outputs: Example 1: Input: "0110111" From 0ecbf64ba0c87a0f1231ca2caef092c6ad33b6e4 Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Fri, 12 May 2023 15:19:37 +0530 Subject: [PATCH 1056/1894] heap sort code --- .../Maximum_rectangle_problem.java | 32 ------------------- sorting/heap_sort.java | 2 +- 2 files changed, 1 insertion(+), 33 deletions(-) delete mode 100644 Dynamic Programming/Maximum_rectangle_problem.java diff --git a/Dynamic Programming/Maximum_rectangle_problem.java b/Dynamic Programming/Maximum_rectangle_problem.java deleted file mode 100644 index c67cf8de..00000000 --- a/Dynamic Programming/Maximum_rectangle_problem.java +++ /dev/null @@ -1,32 +0,0 @@ -import java.util.Stack; - -public class Maximum_rectangle_problem { - public int maximalRectangle(char[][] matrix) { - if (matrix.length == 0 || matrix[0].length == 0) return 0; - - int[][] m = new int[matrix.length][matrix[0].length]; - for (int i = 0; i < m.length; i++) { - for (int j = 0; j < m[0].length; j++) { - if (matrix[i][j] == '0') continue; - m[i][j] = i > 0 ? m[i - 1][j] + 1 : 1; - } - } - - int maxArea = 0; - for (int i = 0; i < m.length; i++) { - Stack s = new Stack(); - for (int j = 0; j <= m[0].length; j++) { - int h = j == m[0].length ? 0 : m[i][j]; - if (s.isEmpty() || h >= m[i][s.peek()]) { - s.push(j); - } else { - int tp = s.pop(); - maxArea = Math.max(maxArea, m[i][tp] * (s.isEmpty() ? j : j - 1 - s.peek())); - j--; - } - } - } - return maxArea; - } - -} diff --git a/sorting/heap_sort.java b/sorting/heap_sort.java index bf90fc4b..9495f23f 100644 --- a/sorting/heap_sort.java +++ b/sorting/heap_sort.java @@ -8,7 +8,7 @@ The process is repeated until all the items of the list are sorted.*/ -// Heap Sort in Java +// Heap Sort in Java language public class heap_sort { From 9e84c3541dbd7b85069e3d13c86730c86239a631 Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Fri, 12 May 2023 17:25:28 +0530 Subject: [PATCH 1057/1894] deleted class file --- sorting/heap_sort.class | Bin 1521 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 sorting/heap_sort.class diff --git a/sorting/heap_sort.class b/sorting/heap_sort.class deleted file mode 100644 index 3767d31617b28770499aa1267ae7cddbc2738c0d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1521 zcmaJ=T~8ZF6g}hpvbRex1Op*na8gKYZ)zIaI!Vn(2ofq1)Ri1jSyXBk*un<0Yk8MQ zyyri(QXeWsmGa!GB2`-P1Nt-in8!X=P3Re~8;C%CnYnZ4-gD2nGxv`-FOLB%;DL!0 z6a%US4Z1+~vHQfGZn?qEbba%&w-pQMvwq;m^8!k-v~D7ei~-Zad$0sDyPn(rItn|C zGoAT`VC|)3}Emb?8adfd;5e8515%-?N;@}=`T8d5I5qE=kC`A zNpQ$Q4#NT?`|h5%6b4&v{G}i7(u!g?h$H3}S4v5Gmo#(zV5eqc6juz4S-6V4z~u|@ z1+=!TCLzuPNTs6~w=f~QVss;0fmE-^<+_FUF)5%X(lrV$t*3EApufRpc-sZH({T?A zek5Uv5+*P6$`%}%XLbP>Weh=H;^ zf#KrDMTCjk2oE}2-m))~FTH)5id4_`KM2D(iaTz5&5L)#?WkYJCnl=6W8kjr^F4vd z)93etC*htqoisFQ{j$3ihaEEh?rg_;feGkmZm`|*qRG`T+&gI3&htFuc_;DVVcWYP z{H)UCL)OkdcMoF8ZM7PH?A6k!38X|pz*-3cud~#0qsWU4@cT}k({>SM1NQ~S|38#7 zk?6xUzG;g86r3J@DCk^o@nmxs(p!E3@e>V!54g%}K;g>Y!&QcU3zdn$edl;CueH?e zdHZ{0%TC@tg7H*2d4BR&K5-TtrBYQL#jz`O$IhwsvSTa%1^p?jq`FlqoK0CvK?Z#= zF~oh0qj(+txQQ%d1~5bKJ^B_fj0&R%puR>%h`*8j2MV_WogDEV$zMn^P0v?$Rn_cW z^-)#hrah|aIW7MTgHBGXI61ZQBaEC@Rdagc)ZaRFI#v4z*d$*y99st0x#SG0$mdkb zI2BMOZIH6U={1ojxp9)8zzz2M4y_udu*lOg<*cEI2FloAGo=s{${Wt15JMAW%wg*( zaEYeyeyV&ttIXxEKEue*=qu+dFL4<-!pPHDj|!rCq82-jGCaOwy*onKKp{Wb}SyHx)vN>pFL9LIK^r-d#t`S3F&1u7OKCU`T; MlSyliF^jnJFII9tl>h($ From bf6a21a6e9ae537e437db369f630d870deaf89ae Mon Sep 17 00:00:00 2001 From: harshita-2003 Date: Fri, 12 May 2023 17:27:50 +0530 Subject: [PATCH 1058/1894] deleted class file --- .../Maximum_rectangle_problem.class | Bin 1138 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Dynamic Programming/Maximum_rectangle_problem.class diff --git a/Dynamic Programming/Maximum_rectangle_problem.class b/Dynamic Programming/Maximum_rectangle_problem.class deleted file mode 100644 index 93986dbec61063bca8add9cffe21a61ff94ba8b5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1138 zcmZ`&OHUI~6#j1Kaob_AUErgpMl%U_p^Ct%>_RZnFbw=Xkw7_mbJ*x9F7eCxn)0x!O(CLPUReH&MIhVMyrlC z1R1<`&KWl|MayMQiB!9eGYHY1DoLrZZNSqzo?2(sBI5cFuZG%uZW{M4r-73avu)W%O0L z_rPA0!w@Gc(tt!ZfgZ9{>ZvD~j|zOz$_BKk)LYqvBJD&g!u_Zn(E$%D!+^i8xGT!h3b@Bz)cXoLr^i)eVpD! z$Kx{Yh~)X>WYQaQ8N6{9zX7j7I-3kto~@yno!`f$fs$G+sibhtRXY{hp%!`Ec8$Xz zU!j-55rmhz?W2}y=tmvK$e*CtB>XTDz#9J^emPeuYB+Bgl+M8aaH- k7$TkyR$mn|YY-wQ*cfs7|CNy_eF%Q&GSW~a-Sgl02_SFa!T Date: Fri, 12 May 2023 22:36:07 +0530 Subject: [PATCH 1059/1894] add bfs in go --- Trees/Binary Trees/bfs.go | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Trees/Binary Trees/bfs.go diff --git a/Trees/Binary Trees/bfs.go b/Trees/Binary Trees/bfs.go new file mode 100644 index 00000000..ac3ad118 --- /dev/null +++ b/Trees/Binary Trees/bfs.go @@ -0,0 +1,43 @@ +/* + Breadth First Search: + Sample Input: + A + / | \ + B C D + / \ / \ + E F G H + / \ \ + I J K + Output: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"] +*/ +package main + +// Define a Node struct that has a name and a slice of child nodes. +type Node struct { + Name string + Children []*Node +} + +// Define a method BreadthFirstSearch on the Node struct that takes an array of strings as an argument. +// This method performs a breadth-first search on the tree starting from the node the method is called on. +// It appends the names of all nodes visited to the input array and returns the modified array. +func (n *Node) BreadthFirstSearch(array []string) []string { + // Create a queue of nodes starting with the current node. + queue := []*Node{n} + + // While there are still nodes in the queue to be visited: + for len(queue) > 0 { + // Dequeue the first node in the queue and add its name to the array. + current := queue[0] + queue = queue[1:] + array = append(array, current.Name) + + // Add all of the node's children to the end of the queue. + for _, child := range current.Children { + queue = append(queue, child) + } + } + + // Return the modified array. + return array +} From e028c964734df66639a9c27aa6d37c1061e3dca2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 22:36:48 +0530 Subject: [PATCH 1060/1894] add explanation --- Trees/Binary Trees/bfs.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Trees/Binary Trees/bfs.go b/Trees/Binary Trees/bfs.go index ac3ad118..d3dd3bca 100644 --- a/Trees/Binary Trees/bfs.go +++ b/Trees/Binary Trees/bfs.go @@ -9,6 +9,24 @@ / \ \ I J K Output: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"] + + Explanation: + This code defines a struct `Node` with two properties: `Name`, a string representing the name of the node, + and `Children`, a slice of pointers to other `Node` objects representing the children of the node. + + The method `BreadthFirstSearch` is defined on `Node`. This method takes an empty string slice `array` as + an argument and performs a breadth-first search traversal of the tree rooted at the current node. + + It returns a slice of strings representing the names of the nodes visited in breadth-first order. + + The breadth-first search algorithm starts with a queue containing only the current node. The algorithm then proceeds as follows: + + 1. Dequeue the first node from the queue. + 2. Add the name of the dequeued node to the `array`. + 3. Enqueue all the children of the dequeued node to the end of the queue. + 4. Repeat steps 1-3 until the queue is empty. + + At the end of the algorithm, the `array` contains the names of all the nodes visited in breadth-first order. The method returns this `array`. */ package main From 66e8ba0fb482829a86914af9776f683346d02922 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 22:37:32 +0530 Subject: [PATCH 1061/1894] add time and space compl;exity --- Trees/Binary Trees/bfs.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Trees/Binary Trees/bfs.go b/Trees/Binary Trees/bfs.go index d3dd3bca..792b95d0 100644 --- a/Trees/Binary Trees/bfs.go +++ b/Trees/Binary Trees/bfs.go @@ -27,6 +27,10 @@ 4. Repeat steps 1-3 until the queue is empty. At the end of the algorithm, the `array` contains the names of all the nodes visited in breadth-first order. The method returns this `array`. + + Time complexity: O(v + e) + Space complexity: O(v) + where v is the number of vertices of the input graph and e is the number of edges of the input graph */ package main From 004caf16da091e34011ecc9d69421b40391cd004 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 22:41:20 +0530 Subject: [PATCH 1062/1894] update dfs in go --- Trees/Binary Trees/dfs.go | 57 ++++++++++++++++++++++++++++++++++----- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/Trees/Binary Trees/dfs.go b/Trees/Binary Trees/dfs.go index 8722104b..39be1179 100644 --- a/Trees/Binary Trees/dfs.go +++ b/Trees/Binary Trees/dfs.go @@ -1,15 +1,60 @@ // Implementation of Depth First Search package main +import "fmt" + +// Node represents a node in a graph. type Node struct { Value int Children []*Node } -func (n *Node) DepthFirstSearch(array []int) []int { - array = append(array, n.Value) - // call dfs on children of each node - for _, child := range n.Children { - array = child.DepthFirstSearch(array) +// DFS traverses the graph using Depth-First Search starting from the given node. +func DFS(node *Node) { + // Create a set to keep track of visited nodes. + visited := make(map[*Node]bool) + + // Call the recursive helper function to perform DFS. + dfsHelper(node, visited) +} + +// dfsHelper is a recursive function that performs Depth-First Search on the graph. +func dfsHelper(node *Node, visited map[*Node]bool) { + // Mark the current node as visited. + visited[node] = true + + // Process the current node (print its value in this case). + fmt.Println(node.Value) + + // Traverse the children of the current node. + for _, child := range node.Children { + // If the child node has not been visited, recursively call dfsHelper on it. + if !visited[child] { + dfsHelper(child, visited) + } } -} \ No newline at end of file +} + +func main() { + // Create a sample graph. + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + node1 := &Node{Value: 1} + node2 := &Node{Value: 2} + node3 := &Node{Value: 3} + node4 := &Node{Value: 4} + node5 := &Node{Value: 5} + node6 := &Node{Value: 6} + node7 := &Node{Value: 7} + + node1.Children = []*Node{node2, node3} + node2.Children = []*Node{node4, node5} + node3.Children = []*Node{node6, node7} + + // Perform DFS starting from node1. + fmt.Println("Depth-First Search:") + DFS(node1) +} From 4b2c525ad7599347ce804edc901b17512020e493 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 22:42:46 +0530 Subject: [PATCH 1063/1894] add explanation --- Trees/Binary Trees/dfs.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Trees/Binary Trees/dfs.go b/Trees/Binary Trees/dfs.go index 39be1179..6542a4c9 100644 --- a/Trees/Binary Trees/dfs.go +++ b/Trees/Binary Trees/dfs.go @@ -1,4 +1,18 @@ // Implementation of Depth First Search +/* + This code demonstrates a basic implementation of Depth-First Search (DFS) on a graph represented by nodes. + It uses a recursive approach to traverse the graph in a depth-first manner, printing the values of the visited nodes. + The algorithm maintains a set of visited nodes to avoid visiting the same node multiple times. + The DFS function serves as the entry point to start the DFS traversal, and the dfsHelper + function recursively visits each node and its children. + Sample Input : + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Output : 1 2 4 5 3 6 7 +*/ package main import "fmt" From c33f744046e8e04a7b102074914fb5645ba3ba59 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 12 May 2023 22:43:48 +0530 Subject: [PATCH 1064/1894] add time and space --- Trees/Binary Trees/dfs.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Trees/Binary Trees/dfs.go b/Trees/Binary Trees/dfs.go index 6542a4c9..8f17ab43 100644 --- a/Trees/Binary Trees/dfs.go +++ b/Trees/Binary Trees/dfs.go @@ -12,6 +12,15 @@ // / \ / \ // 4 5 6 7 Output : 1 2 4 5 3 6 7 + + The time complexity of Depth-First Search (DFS) on a graph is O(V + E), where V represents the number of vertices (nodes) + in the graph and E represents the number of edges. In the worst case, DFS may visit all vertices and edges of the graph. + + The space complexity of DFS is determined by the maximum depth of the recursion stack. In the case of a tree-like + structure, where each node has only one child, the maximum depth is equal to the height of the tree. + Therefore, the space complexity of DFS on such a tree-like structure is O(H), where H represents the height of the tree. + In the worst case, where the graph is a linear structure, the height of the tree is equal to the number of vertices, + so the space complexity becomes O(V). */ package main From 3029d4fccd3804da301317d43515511a3677d27d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 13 May 2023 00:11:27 +0530 Subject: [PATCH 1065/1894] add bf approach of kth alrgest in bst --- Trees/Binary Search Trees/kth_largest.go | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Trees/Binary Search Trees/kth_largest.go diff --git a/Trees/Binary Search Trees/kth_largest.go b/Trees/Binary Search Trees/kth_largest.go new file mode 100644 index 00000000..703749d0 --- /dev/null +++ b/Trees/Binary Search Trees/kth_largest.go @@ -0,0 +1,27 @@ +// Kth largest in BST +package main + +// Approach 1: Using Brute Force +// Since Inorder traversal of BSt always comes in sorted order, we can directly access kth from end +type BST struct { + Value int + + Left *BST + Right *BST +} + +func FindKthLargestValueInBst(tree *BST, k int) int { + sortedValues := make([]int, 0) + inOrderTraverse(tree, &sortedValues) + return sortedValues[len(sortedValues) - k] +} + +func inOrderTraverse(tree *BST, sortedValues *[]int) { + if tree.Left != nil { + inOrderTraverse(tree.Left, sortedValues) + } + *sortedValues = append(*sortedValues, tree.Value) + if tree.Right != nil { + inOrderTraverse(tree.Right, sortedValues) + } +} From a77b2c38187d8380287df948a73db9ebc90aef8d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 13 May 2023 00:11:46 +0530 Subject: [PATCH 1066/1894] add approach 2 using reverse inorder traversal --- Trees/Binary Search Trees/kth_largest.go | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Trees/Binary Search Trees/kth_largest.go b/Trees/Binary Search Trees/kth_largest.go index 703749d0..264688b8 100644 --- a/Trees/Binary Search Trees/kth_largest.go +++ b/Trees/Binary Search Trees/kth_largest.go @@ -25,3 +25,40 @@ func inOrderTraverse(tree *BST, sortedValues *[]int) { inOrderTraverse(tree.Right, sortedValues) } } + + +// Approach 2: Using Reverse InOrder Traversal +// Helper struct to store traversal information +type treeInfo struct { + numberOfNodesVisited int + latestVisitedNodeValue int +} + +// FindKthLargestValueInBst finds the Kth largest value in the BST +func FindKthLargestValueInBst2(tree *BST, k int) int { + // Create treeInfo to track traversal progress + treeInfo := treeInfo{0, -1} + reverseInOrderTraverse(tree, k, &treeInfo) + return treeInfo.latestVisitedNodeValue +} + +// reverseInOrderTraverse performs reverse in-order traversal of the BST +func reverseInOrderTraverse(tree *BST, k int, treeInfo *treeInfo) { + // Base case: if current node is nil or Kth largest value found, return + if tree == nil || treeInfo.numberOfNodesVisited == k { + return + } + + // Traverse the right subtree + reverseInOrderTraverse(tree.Right, k, treeInfo) + + // Check if Kth largest value has been found + if treeInfo.numberOfNodesVisited < k { + // Increment the count of visited nodes and update the latest visited node value + treeInfo.numberOfNodesVisited++ + treeInfo.latestVisitedNodeValue = tree.Value + + // Traverse the left subtree + reverseInOrderTraverse(tree.Left, k, treeInfo) + } +} \ No newline at end of file From 9a931c2e0e5dc15edb43c453753efbe67805b1b7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 13 May 2023 00:14:00 +0530 Subject: [PATCH 1067/1894] update time and space complexity --- Trees/Binary Search Trees/kth_largest.go | 46 +++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Search Trees/kth_largest.go b/Trees/Binary Search Trees/kth_largest.go index 264688b8..3fb1197b 100644 --- a/Trees/Binary Search Trees/kth_largest.go +++ b/Trees/Binary Search Trees/kth_largest.go @@ -27,7 +27,51 @@ func inOrderTraverse(tree *BST, sortedValues *[]int) { } -// Approach 2: Using Reverse InOrder Traversal +// Approach 2: Using Reverse InOrder Traversal +/* + The given code implements a function to find the Kth largest value in a Binary Search Tree (BST). Here's how it works: + + 1. The `BST` struct represents a node in the BST, with a `Value` field and pointers to the left and right child nodes. + + 2. The `treeInfo` struct is a helper struct used to store information during the traversal of the BST. It contains two fields: `numberOfNodesVisited` to keep track of the number of nodes visited, and `latestVisitedNodeValue` to store the value of the latest visited node. + + 3. The `FindKthLargestValueInBst` function takes the root of the BST and the value of K as input and returns the Kth largest value in the BST. + + 4. Inside the `FindKthLargestValueInBst` function, a `treeInfo` instance is created to track the traversal progress. + + 5. The `reverseInOrderTraverse` function is called to perform a reverse in-order traversal of the BST. It starts from the right child, then visits the current node, and finally visits the left child. + + 6. In the `reverseInOrderTraverse` function, the base case is checked: if the current node is `nil` or the desired Kth largest value has already been found (i.e., `numberOfNodesVisited` is equal to K), the function returns. + + 7. The `reverseInOrderTraverse` function is recursively called on the right child node, which traverses the BST in descending order. + + 8. After the right subtree is traversed, the function checks if `numberOfNodesVisited` is still less than K. If so, it increments `numberOfNodesVisited`, assigns the current node's value to `latestVisitedNodeValue`, and recursively calls the function on the left child node. + + 9. The reverse in-order traversal ensures that the largest values are visited first, so when `numberOfNodesVisited` reaches K, the value stored in `latestVisitedNodeValue` will be the Kth largest value in the BST. + + 10. Finally, the Kth largest value is returned by the `FindKthLargestValueInBst` function. + + The code efficiently finds the Kth largest value in a BST by performing a reverse in-order traversal, keeping track of the + number of visited nodes and the latest visited node value. + + The time complexity of the algorithm is O(H + K), where H is the height of the BST and K is the input value. + + The space complexity of the code is O(h), where h is the height of the BST. + During the execution of the FindKthLargestValueInBst function, the space usage is primarily determined by the recursive + calls to the reverseInOrderTraverse function. Each recursive call adds a new frame to the call stack, + consuming additional memory. + + In the worst case scenario, where the BST is skewed and has a height of h (resembling a linked list), the space + complexity will be O(h). This is because the function will make h recursive calls before reaching the base case. + + However, in a balanced BST where the height is log(N), where N is the number of nodes in the tree, the space + complexity will be O(log(N)). + + It's important to note that the space complexity only accounts for the additional space used by the recursive calls + and the call stack. The space required to store the BST itself is not considered in this analysis as it is part of + the input data. + +*/ // Helper struct to store traversal information type treeInfo struct { numberOfNodesVisited int From afa58950848f1437bb4fd33d3e2a876217ecbbce Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 13 May 2023 00:22:28 +0530 Subject: [PATCH 1068/1894] update contributing.md --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d0145236..c7ad2931 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ Contributions are always welcome! - Add Time and Space complexity - Take care of Readability (Code is written once and read multiple times, so keep this in mind) - Provide link for further reading (optional) -- Send a Pull Request (PR) against main branch and mention issue number in the request +- Send a Pull Request (PR) against main branch and mention issue number in the request format (#ISSUENUMBER) # Example program From fe89be8528ab02afc4123e8e07e0ecb6a73cf9b1 Mon Sep 17 00:00:00 2001 From: Niraj Date: Sat, 13 May 2023 09:29:04 +0530 Subject: [PATCH 1069/1894] #450 Add Queries on Number of Points Inside a Circle in Javascript --- ...ies_on_number_of_points_inside_a_circle.js | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Math/add_queries_on_number_of_points_inside_a_circle.js diff --git a/Math/add_queries_on_number_of_points_inside_a_circle.js b/Math/add_queries_on_number_of_points_inside_a_circle.js new file mode 100644 index 00000000..7c12f6dd --- /dev/null +++ b/Math/add_queries_on_number_of_points_inside_a_circle.js @@ -0,0 +1,45 @@ +// Program Author : TheCodeVenturer[Niraj Modi] +/* + Program Definition : Queries on Number of Points inside a circle + Description : you are given n points in a cartesian plane [points] and a queries array + Where each element inside it is an array each consisting of [xj, yj, rj] where, + (xj,yj) is centre of the circle and rj is radius of the circle + Now, you are required to find no.of points inside the circle + + Approach: + The only possible soln somehow will be that you have to calculate distance of each point from the centre of each circle + and if the distance <= radius then the point is inside the the circle else not + + Distance Formula = ((x1-x2)**2 + (y1-y2)**2)**(1/2) + Complexity: + The time complexity of this solution is O(m*n) where m = points.length and n = queries.length + The space complexity is O(1),we are not using any Auxiliary Spaces. + Sample input/outputs: + Example 1: + Input: + points = [[1,3],[3,3],[5,3],[2,2]] + queries = [[2,3,1],[4,3,1],[1,1,2]] + Output: [3,2,2] + Example 1: + Input: + points = [[1,1],[2,2],[3,3],[4,4],[5,5]] + queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]] + Output: [2,3,2,4] + */ + +var countPoints = function(points, queries) { + sol=[] // Initialising solution array + for(let query of queries){ + var count=0 //no.of points inside that circle is initially zero + for(let point of points){ + d = Math.sqrt((query[0]-point[0])**2+(query[1]-point[1])**2) //calculating distance between the points + if(d<=query[2])count++ //if it is <= radius it is inside the circle + } + sol.push(count) //finally add the solution to solution array + } + return sol +}; + +points = [[1,3],[3,3],[5,3],[2,2]] +queries = [[2,3,1],[4,3,1],[1,1,2]] +console.log(countPoints(points,queries)) \ No newline at end of file From ef7391d2afb278651104d5ebae06f28b995de6fd Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 13 May 2023 10:28:10 +0530 Subject: [PATCH 1070/1894] Create Sorted_array_2D --- Arrays/Sorted_array_2D | 67 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Arrays/Sorted_array_2D diff --git a/Arrays/Sorted_array_2D b/Arrays/Sorted_array_2D new file mode 100644 index 00000000..161212be --- /dev/null +++ b/Arrays/Sorted_array_2D @@ -0,0 +1,67 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Search in 2D sorted array in Javascript +Issue Number : #272 +Problem statement : + +Explanation of the below Javascript code : + +The function searchMatrix takes in a matrix (matrix) and a target integer (target) as parameters. It returns true if the target is found in the matrix and false otherwise. + +The function first checks for edge cases where the matrix is empty or the rows are empty, and immediately returns false in such cases. + +It then initializes variables for the number of rows (rows) and columns (cols) in the matrix, and sets the left and right indices for the binary search. + +The binary search is performed using a while loop, with the left and right indices as the condition. Inside the loop, the middle index (mid) is calculated using Math.floor((left + right) / 2), and the corresponding row and column indices are derived from the mid index. + +The element at the mid index is compared with the target, and based on the comparison, the search space is narrowed down by updating the left and right indices accordingly. + +If the target is found, the function returns true. If the loop completes without finding the target, the function returns false. + +The time complexity of this JavaScript solution is O(log(m * n)), as it performs a binary search on a list of size m * n. + + +*/ + +-------------------------------------------------------------------------//Javascript code begins here----------------------------------------------------------------------- + + +/** + * Searches for a target integer in a matrix. + * @param {number[][]} matrix - The matrix to search in. + * @param {number} target - The target integer to search for. + * @return {boolean} - True if the target is found, false otherwise. + */ +function searchMatrix(matrix, target) { + // Check for empty matrix or empty rows + if (!matrix || matrix.length === 0 || matrix[0].length === 0) { + return false; + } + + const rows = matrix.length; + const cols = matrix[0].length; + let left = 0; + let right = rows * cols - 1; + + // Perform binary search on the matrix + while (left <= right) { + const mid = Math.floor((left + right) / 2); + const row = Math.floor(mid / cols); + const col = mid % cols; + + if (matrix[row][col] === target) { + // Target found + return true; + } else if (matrix[row][col] < target) { + // Target is in the right half of the matrix + left = mid + 1; + } else { + // Target is in the left half of the matrix + right = mid - 1; + } + } + + // Target not found + return false; +} From 833a3bb28d33c834d4b3deecffdb14a8d252b072 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 13 May 2023 10:31:55 +0530 Subject: [PATCH 1071/1894] Rename Sorted_array_2D to Sorted_array_2D.js --- Arrays/{Sorted_array_2D => Sorted_array_2D.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{Sorted_array_2D => Sorted_array_2D.js} (100%) diff --git a/Arrays/Sorted_array_2D b/Arrays/Sorted_array_2D.js similarity index 100% rename from Arrays/Sorted_array_2D rename to Arrays/Sorted_array_2D.js From c36e2d544fa3489bc0033ac48b89e060680e36d2 Mon Sep 17 00:00:00 2001 From: Niraj Date: Sat, 13 May 2023 12:25:55 +0530 Subject: [PATCH 1072/1894] #451 Add Queries on Number of Points Inside a Circle in Python --- ...ies_on_number_of_points_inside_a_circle.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Math/add_queries_on_number_of_points_inside_a_circle.py diff --git a/Math/add_queries_on_number_of_points_inside_a_circle.py b/Math/add_queries_on_number_of_points_inside_a_circle.py new file mode 100644 index 00000000..9c646e91 --- /dev/null +++ b/Math/add_queries_on_number_of_points_inside_a_circle.py @@ -0,0 +1,44 @@ +# Program Author : TheCodeVenturer[Niraj Modi] +''' + Program Definition : Queries on Number of Points inside a circle + Description : you are given n points in a cartesian plane [points] and a queries array + Where each element inside it is an array each consisting of [xj, yj, rj] where, + (xj,yj) is centre of the circle and rj is radius of the circle + Now, you are required to find no.of points inside the circle + + Approach: + The only possible soln somehow will be that you have to calculate distance of each point from the centre of each circle + and if the distance <= radius then the point is inside the the circle else not + + Distance Formula = ((x1-x2)**2 + (y1-y2)**2)**(1/2) + Complexity: + The time complexity of this solution is O(m*n) where m = points.length and n = queries.length + The space complexity is O(1),we are not using any Auxiliary Spaces. + Sample input/outputs: + Example 1: + Input: + points = [[1,3],[3,3],[5,3],[2,2]] + queries = [[2,3,1],[4,3,1],[1,1,2]] + Output: [3,2,2] + Example 1: + Input: + points = [[1,1],[2,2],[3,3],[4,4],[5,5]] + queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]] + Output: [2,3,2,4] +''' +class Solution: + def countPoints(self, points: list[list[int]], queries: list[list[int]]) -> list[int]: + sol :list = [] #Initialising solution array + for x1,y1,r in queries: + count:int=0 #no.of points inside that circle is initially zero + for x2,y2 in points: + d = ((x2-x1)**2 + (y2-y1)**2)**(1/2) #calculating distance between the points + if(d<=r): #if it is <= radius it is inside the circle + count+=1 + sol.append(count) #finally add the count to solution array + return sol + + +points = [[1,3],[3,3],[5,3],[2,2]] +queries = [[2,3,1],[4,3,1],[1,1,2]] +print(Solution().countPoints(points,queries)) \ No newline at end of file From edd2bb64402c685ab824cb39b83b8719d9a83082 Mon Sep 17 00:00:00 2001 From: John Doe Date: Sat, 13 May 2023 19:07:02 +0530 Subject: [PATCH 1073/1894] added my code --- ...earest_0_for_each_cell_20230513185932.java | 0 ...earest_0_for_each_cell_20230513190321.java | 47 +++++++++++++ ...earest_0_for_each_cell_20230513190446.java | 66 ++++++++++++++++++ ...earest_0_for_each_cell_20230513190503.java | 67 +++++++++++++++++++ ...earest_0_for_each_cell_20230513190643.java | 67 +++++++++++++++++++ ...me_to_buy_and_sell_stock_20230513102642.py | 38 +++++++++++ ...me_to_buy_and_sell_stock_20230513190028.py | 38 +++++++++++ ...stance_of_the_nearest_0_for_each_cell.java | 67 +++++++++++++++++++ 8 files changed, 390 insertions(+) create mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java create mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java create mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java create mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java create mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java create mode 100644 .history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py create mode 100644 .history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py create mode 100644 Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java new file mode 100644 index 00000000..e69de29b diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java new file mode 100644 index 00000000..ea9fd209 --- /dev/null +++ b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java @@ -0,0 +1,47 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +class Solution { + private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[][] distances = new int[m][n]; + Queue queue = new LinkedList<>(); + for (int i = 0; i < m; i++) { + Arrays.fill(distances[i], Integer.MAX_VALUE); + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + distances[i][j] = 0; + queue.offer(new int[]{i, j}); + } + } + } + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int i = cell[0]; + int j = cell[1]; + for (int[] direction : DIRECTIONS) { + int x = i + direction[0]; + int y = j + direction[1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + if (distances[x][y] <= distances[i][j] + 1) { + continue; + } + distances[x][y] = distances[i][j] + 1; + queue.offer(new int[]{x, y}); + } + } + return distances; + } +} diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java new file mode 100644 index 00000000..551b6ca0 --- /dev/null +++ b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java @@ -0,0 +1,66 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). + +class Solution { + private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[][] distances = new int[m][n]; + Queue queue = new LinkedList<>(); + for (int i = 0; i < m; i++) { + Arrays.fill(distances[i], Integer.MAX_VALUE); + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + distances[i][j] = 0; + queue.offer(new int[]{i, j}); + } + } + } + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int i = cell[0]; + int j = cell[1]; + for (int[] direction : DIRECTIONS) { + int x = i + direction[0]; + int y = j + direction[1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + if (distances[x][y] <= distances[i][j] + 1) { + continue; + } + distances[x][y] = distances[i][j] + 1; + queue.offer(new int[]{x, y}); + } + } + return distances; + } +} + + +//Input +// mat = +// [[0,0,0],[0,1,0],[0,0,0]] + +// Output +// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java new file mode 100644 index 00000000..01803ddb --- /dev/null +++ b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java @@ -0,0 +1,67 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). + +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). + +class Solution { + private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[][] distances = new int[m][n]; + Queue queue = new LinkedList<>(); + for (int i = 0; i < m; i++) { + Arrays.fill(distances[i], Integer.MAX_VALUE); + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + distances[i][j] = 0; + queue.offer(new int[]{i, j}); + } + } + } + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int i = cell[0]; + int j = cell[1]; + for (int[] direction : DIRECTIONS) { + int x = i + direction[0]; + int y = j + direction[1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + if (distances[x][y] <= distances[i][j] + 1) { + continue; + } + distances[x][y] = distances[i][j] + 1; + queue.offer(new int[]{x, y}); + } + } + return distances; + } +} + + +//Input +// mat = +// [[0,0,0],[0,1,0],[0,0,0]] + +// Output +// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java new file mode 100644 index 00000000..01803ddb --- /dev/null +++ b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java @@ -0,0 +1,67 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). + +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). + +class Solution { + private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[][] distances = new int[m][n]; + Queue queue = new LinkedList<>(); + for (int i = 0; i < m; i++) { + Arrays.fill(distances[i], Integer.MAX_VALUE); + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + distances[i][j] = 0; + queue.offer(new int[]{i, j}); + } + } + } + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int i = cell[0]; + int j = cell[1]; + for (int[] direction : DIRECTIONS) { + int x = i + direction[0]; + int y = j + direction[1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + if (distances[x][y] <= distances[i][j] + 1) { + continue; + } + distances[x][y] = distances[i][j] + 1; + queue.offer(new int[]{x, y}); + } + } + return distances; + } +} + + +//Input +// mat = +// [[0,0,0],[0,1,0],[0,0,0]] + +// Output +// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py new file mode 100644 index 00000000..046a7c4a --- /dev/null +++ b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py @@ -0,0 +1,38 @@ +# Best Time to buy and sell stock +''' + The function maxProfit takes a list of integers prices and returns the maximum profit that can be + made from buying and selling the stock represented by prices. The function works by initializing + the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. + + It then loops through the prices, updating the minimum price if the current price is less than the current minimum + price, and updating the maximum profit if the difference between the current price and the minimum + price is greater than the current maximum profit. Finally, it returns the maximum profit. + + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit +''' + + +def maxProfit(prices: List[int]) -> int: + # initialize the minimum price as maximum integer value + min_price = sys.maxsize + + # initialize the maximum profit as 0 + max_profit = 0 + + # loop through the prices + for price in prices: + # if the current price is less than the minimum price, update the minimum price + if price < min_price: + min_price = price + # else if the difference between the current price and the minimum price is greater than the maximum profit, + # update the maximum profit + elif price - min_price > max_profit: + max_profit = price - min_price + + # return the maximum profit + return max_profit + +prices = [7, 1, 5, 3, 6, 4] +profit = maxProfit(prices) +print(profit) # Output: 5 \ No newline at end of file diff --git a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py new file mode 100644 index 00000000..046a7c4a --- /dev/null +++ b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py @@ -0,0 +1,38 @@ +# Best Time to buy and sell stock +''' + The function maxProfit takes a list of integers prices and returns the maximum profit that can be + made from buying and selling the stock represented by prices. The function works by initializing + the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. + + It then loops through the prices, updating the minimum price if the current price is less than the current minimum + price, and updating the maximum profit if the difference between the current price and the minimum + price is greater than the current maximum profit. Finally, it returns the maximum profit. + + Time Complexity: O(n), where n is the length of the prices array. + Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit +''' + + +def maxProfit(prices: List[int]) -> int: + # initialize the minimum price as maximum integer value + min_price = sys.maxsize + + # initialize the maximum profit as 0 + max_profit = 0 + + # loop through the prices + for price in prices: + # if the current price is less than the minimum price, update the minimum price + if price < min_price: + min_price = price + # else if the difference between the current price and the minimum price is greater than the maximum profit, + # update the maximum profit + elif price - min_price > max_profit: + max_profit = price - min_price + + # return the maximum profit + return max_profit + +prices = [7, 1, 5, 3, 6, 4] +profit = maxProfit(prices) +print(profit) # Output: 5 \ No newline at end of file diff --git a/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java b/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java new file mode 100644 index 00000000..01803ddb --- /dev/null +++ b/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java @@ -0,0 +1,67 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). + +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). + +class Solution { + private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + int[][] distances = new int[m][n]; + Queue queue = new LinkedList<>(); + for (int i = 0; i < m; i++) { + Arrays.fill(distances[i], Integer.MAX_VALUE); + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + distances[i][j] = 0; + queue.offer(new int[]{i, j}); + } + } + } + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int i = cell[0]; + int j = cell[1]; + for (int[] direction : DIRECTIONS) { + int x = i + direction[0]; + int y = j + direction[1]; + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + if (distances[x][y] <= distances[i][j] + 1) { + continue; + } + distances[x][y] = distances[i][j] + 1; + queue.offer(new int[]{x, y}); + } + } + return distances; + } +} + + +//Input +// mat = +// [[0,0,0],[0,1,0],[0,0,0]] + +// Output +// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file From 314ee4f4309796797aa072480f2e3d1baab8d2bf Mon Sep 17 00:00:00 2001 From: John Doe Date: Sat, 13 May 2023 19:08:10 +0530 Subject: [PATCH 1074/1894] d --- ...earest_0_for_each_cell_20230513185932.java | 0 ...earest_0_for_each_cell_20230513190321.java | 47 ------------- ...earest_0_for_each_cell_20230513190446.java | 66 ------------------ ...earest_0_for_each_cell_20230513190503.java | 67 ------------------- ...earest_0_for_each_cell_20230513190643.java | 67 ------------------- ...me_to_buy_and_sell_stock_20230513102642.py | 38 ----------- ...me_to_buy_and_sell_stock_20230513190028.py | 38 ----------- 7 files changed, 323 deletions(-) delete mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java delete mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java delete mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java delete mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java delete mode 100644 .history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java delete mode 100644 .history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py delete mode 100644 .history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513185932.java deleted file mode 100644 index e69de29b..00000000 diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java deleted file mode 100644 index ea9fd209..00000000 --- a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190321.java +++ /dev/null @@ -1,47 +0,0 @@ -// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java - - -// Solution -// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. -// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, -// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. -// // Finally, we return the updated distances matrix. - - -class Solution { - private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; - - public int[][] updateMatrix(int[][] mat) { - int m = mat.length; - int n = mat[0].length; - int[][] distances = new int[m][n]; - Queue queue = new LinkedList<>(); - for (int i = 0; i < m; i++) { - Arrays.fill(distances[i], Integer.MAX_VALUE); - for (int j = 0; j < n; j++) { - if (mat[i][j] == 0) { - distances[i][j] = 0; - queue.offer(new int[]{i, j}); - } - } - } - while (!queue.isEmpty()) { - int[] cell = queue.poll(); - int i = cell[0]; - int j = cell[1]; - for (int[] direction : DIRECTIONS) { - int x = i + direction[0]; - int y = j + direction[1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - if (distances[x][y] <= distances[i][j] + 1) { - continue; - } - distances[x][y] = distances[i][j] + 1; - queue.offer(new int[]{x, y}); - } - } - return distances; - } -} diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java deleted file mode 100644 index 551b6ca0..00000000 --- a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190446.java +++ /dev/null @@ -1,66 +0,0 @@ -// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java - - -// Solution -// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. -// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, -// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. -// // Finally, we return the updated distances matrix. - - -// Time Complexity: - -// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. -// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. -// Therefore, the total time complexity of this solution is O(m * n). -// Space Complexity: - -// We store the distances matrix, which requires O(m * n) space. -// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. -// Therefore, the total space complexity of this solution is O(m * n). - -class Solution { - private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; - - public int[][] updateMatrix(int[][] mat) { - int m = mat.length; - int n = mat[0].length; - int[][] distances = new int[m][n]; - Queue queue = new LinkedList<>(); - for (int i = 0; i < m; i++) { - Arrays.fill(distances[i], Integer.MAX_VALUE); - for (int j = 0; j < n; j++) { - if (mat[i][j] == 0) { - distances[i][j] = 0; - queue.offer(new int[]{i, j}); - } - } - } - while (!queue.isEmpty()) { - int[] cell = queue.poll(); - int i = cell[0]; - int j = cell[1]; - for (int[] direction : DIRECTIONS) { - int x = i + direction[0]; - int y = j + direction[1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - if (distances[x][y] <= distances[i][j] + 1) { - continue; - } - distances[x][y] = distances[i][j] + 1; - queue.offer(new int[]{x, y}); - } - } - return distances; - } -} - - -//Input -// mat = -// [[0,0,0],[0,1,0],[0,0,0]] - -// Output -// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java deleted file mode 100644 index 01803ddb..00000000 --- a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190503.java +++ /dev/null @@ -1,67 +0,0 @@ -// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java - - -// Solution -// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. -// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, -// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. -// // Finally, we return the updated distances matrix. - - -// Time Complexity: - -// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. -// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. -// Therefore, the total time complexity of this solution is O(m * n). - -// Space Complexity: - -// We store the distances matrix, which requires O(m * n) space. -// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. -// Therefore, the total space complexity of this solution is O(m * n). - -class Solution { - private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; - - public int[][] updateMatrix(int[][] mat) { - int m = mat.length; - int n = mat[0].length; - int[][] distances = new int[m][n]; - Queue queue = new LinkedList<>(); - for (int i = 0; i < m; i++) { - Arrays.fill(distances[i], Integer.MAX_VALUE); - for (int j = 0; j < n; j++) { - if (mat[i][j] == 0) { - distances[i][j] = 0; - queue.offer(new int[]{i, j}); - } - } - } - while (!queue.isEmpty()) { - int[] cell = queue.poll(); - int i = cell[0]; - int j = cell[1]; - for (int[] direction : DIRECTIONS) { - int x = i + direction[0]; - int y = j + direction[1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - if (distances[x][y] <= distances[i][j] + 1) { - continue; - } - distances[x][y] = distances[i][j] + 1; - queue.offer(new int[]{x, y}); - } - } - return distances; - } -} - - -//Input -// mat = -// [[0,0,0],[0,1,0],[0,0,0]] - -// Output -// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java b/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java deleted file mode 100644 index 01803ddb..00000000 --- a/.history/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell_20230513190643.java +++ /dev/null @@ -1,67 +0,0 @@ -// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java - - -// Solution -// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. -// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, -// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. -// // Finally, we return the updated distances matrix. - - -// Time Complexity: - -// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. -// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. -// Therefore, the total time complexity of this solution is O(m * n). - -// Space Complexity: - -// We store the distances matrix, which requires O(m * n) space. -// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. -// Therefore, the total space complexity of this solution is O(m * n). - -class Solution { - private static final int[][] DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; - - public int[][] updateMatrix(int[][] mat) { - int m = mat.length; - int n = mat[0].length; - int[][] distances = new int[m][n]; - Queue queue = new LinkedList<>(); - for (int i = 0; i < m; i++) { - Arrays.fill(distances[i], Integer.MAX_VALUE); - for (int j = 0; j < n; j++) { - if (mat[i][j] == 0) { - distances[i][j] = 0; - queue.offer(new int[]{i, j}); - } - } - } - while (!queue.isEmpty()) { - int[] cell = queue.poll(); - int i = cell[0]; - int j = cell[1]; - for (int[] direction : DIRECTIONS) { - int x = i + direction[0]; - int y = j + direction[1]; - if (x < 0 || x >= m || y < 0 || y >= n) { - continue; - } - if (distances[x][y] <= distances[i][j] + 1) { - continue; - } - distances[x][y] = distances[i][j] + 1; - queue.offer(new int[]{x, y}); - } - } - return distances; - } -} - - -//Input -// mat = -// [[0,0,0],[0,1,0],[0,0,0]] - -// Output -// [[0,0,0],[0,1,0],[0,0,0]] \ No newline at end of file diff --git a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py deleted file mode 100644 index 046a7c4a..00000000 --- a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513102642.py +++ /dev/null @@ -1,38 +0,0 @@ -# Best Time to buy and sell stock -''' - The function maxProfit takes a list of integers prices and returns the maximum profit that can be - made from buying and selling the stock represented by prices. The function works by initializing - the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. - - It then loops through the prices, updating the minimum price if the current price is less than the current minimum - price, and updating the maximum profit if the difference between the current price and the minimum - price is greater than the current maximum profit. Finally, it returns the maximum profit. - - Time Complexity: O(n), where n is the length of the prices array. - Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit -''' - - -def maxProfit(prices: List[int]) -> int: - # initialize the minimum price as maximum integer value - min_price = sys.maxsize - - # initialize the maximum profit as 0 - max_profit = 0 - - # loop through the prices - for price in prices: - # if the current price is less than the minimum price, update the minimum price - if price < min_price: - min_price = price - # else if the difference between the current price and the minimum price is greater than the maximum profit, - # update the maximum profit - elif price - min_price > max_profit: - max_profit = price - min_price - - # return the maximum profit - return max_profit - -prices = [7, 1, 5, 3, 6, 4] -profit = maxProfit(prices) -print(profit) # Output: 5 \ No newline at end of file diff --git a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py b/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py deleted file mode 100644 index 046a7c4a..00000000 --- a/.history/Dynamic Programming/best_time_to_buy_and_sell_stock_20230513190028.py +++ /dev/null @@ -1,38 +0,0 @@ -# Best Time to buy and sell stock -''' - The function maxProfit takes a list of integers prices and returns the maximum profit that can be - made from buying and selling the stock represented by prices. The function works by initializing - the minimum price to a very large number (sys.maxsize) and the maximum profit to 0. - - It then loops through the prices, updating the minimum price if the current price is less than the current minimum - price, and updating the maximum profit if the difference between the current price and the minimum - price is greater than the current maximum profit. Finally, it returns the maximum profit. - - Time Complexity: O(n), where n is the length of the prices array. - Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit -''' - - -def maxProfit(prices: List[int]) -> int: - # initialize the minimum price as maximum integer value - min_price = sys.maxsize - - # initialize the maximum profit as 0 - max_profit = 0 - - # loop through the prices - for price in prices: - # if the current price is less than the minimum price, update the minimum price - if price < min_price: - min_price = price - # else if the difference between the current price and the minimum price is greater than the maximum profit, - # update the maximum profit - elif price - min_price > max_profit: - max_profit = price - min_price - - # return the maximum profit - return max_profit - -prices = [7, 1, 5, 3, 6, 4] -profit = maxProfit(prices) -print(profit) # Output: 5 \ No newline at end of file From b24681344d75f90a728ffba375653c7a9c80bb30 Mon Sep 17 00:00:00 2001 From: shivanand-patil Date: Sat, 13 May 2023 20:39:09 +0530 Subject: [PATCH 1075/1894] #982 solved --- Linked List/singly_linked_list.java | 92 +++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Linked List/singly_linked_list.java diff --git a/Linked List/singly_linked_list.java b/Linked List/singly_linked_list.java new file mode 100644 index 00000000..32a6d998 --- /dev/null +++ b/Linked List/singly_linked_list.java @@ -0,0 +1,92 @@ +// Linked list: Implement Singly linked list in Java #982 + +/* +APPROACH :Node Class: The Node class is defined to represent a single node in the linked list. It has two instance variables: data to store the value and next to store the reference to the next node. + +Insertion at the Start: The insertStart method allows inserting a new node at the beginning of the linked list. It creates a new node with the given data value and sets its next reference to the current head. Then, it updates the head to point to the newly inserted node. + +Deletion from the Start: The delete method removes the first node from the linked list. It checks if the head is null, indicating an empty list. If not, it updates the head to point to the next node, effectively removing the first node. + +Display: The display method is used to print the elements of the linked list. It starts from the head node and iterates through the list by moving to the next node until the current node becomes null. During each iteration, it prints the data value of the current node. + +Main Method: The main method demonstrates the usage of the linked list implementation. It creates an empty list by initializing the head to null. It then performs several insertions using the insertStart method to add nodes at the beginning of the list. After that, it calls the display method to print the elements of the list. Next, it performs several deletions using the delete method to remove nodes from the beginning of the list. Finally, it calls the display method again to print the updated list. +*/ + +import java.lang.*; + +// Node Class +class Node { + int data; + Node next; + + Node(int x) // parameterized constructor + { + data = x; + next = null; + } +} + +class Main +{ + static Node insertStart(Node head, int data) + { + // Creating newNode memory & assigning data value + Node newNode = new Node(data); + + // assigning this newNode's next as current head node + newNode.next = head; + // re-assigning head to this newNode + head = newNode; + + return head; + } + + public static Node delete(Node head) + { + if (head == null){ + System.out.println("List is empty, not possible to delete"); + return head; + } + + System.out.println("Deleted: " + head.data); + // move head to next node + head = head.next; + + return head; + } + + static void display(Node node) { + + //as linked list will end when Node is Null + while (node != null) { + System.out.print(node.data + " "); + node = node.next; + } + System.out.println(""); + } + + public static void main(String args[]) + { + Node head = null; + head = insertStart(head,6); + head = insertStart(head,5); + head = insertStart(head,4); + head = insertStart(head,3); + head = insertStart(head,2); + head = insertStart(head,1); + + display(head); + + head = delete(head); + head = delete(head); + head = delete(head); + + display(head); + + + } +} + +/* +the space complexity is O(n), and the time complexity for each operation is either O(1) or O(n), depending on the specific operation being performed. +*/ From 798da6a1c84396bdcec7a87ccc915a4821b5eaae Mon Sep 17 00:00:00 2001 From: Mohamed Ashraf Hassan Date: Sat, 13 May 2023 18:43:08 +0300 Subject: [PATCH 1076/1894] Solved K_Closest_Points_to_Origin (#453). --- Math/K_closest_points_to_origin.java | 79 ++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Math/K_closest_points_to_origin.java diff --git a/Math/K_closest_points_to_origin.java b/Math/K_closest_points_to_origin.java new file mode 100644 index 00000000..3bf38816 --- /dev/null +++ b/Math/K_closest_points_to_origin.java @@ -0,0 +1,79 @@ +/** + Time Complexity: O(nlog(n)), Space Complexity: O(n) + + Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). + The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)^2 + (y1 - y2)^2). + You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). + + Example 1: + Input: points = [[1,3],[-2,2]], k = 1 + Output: [[-2,2]] + + Explanation: + The distance between (1, 3) and the origin is sqrt(10). + The distance between (-2, 2) and the origin is sqrt(8). + Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. + We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. + + + Example 2: + Input: points = [[3,3],[5,-1],[-2,4]], k = 2 + Output: [[3,3],[-2,4]] + + Explanation: The answer [[-2,4],[3,3]] would also be accepted. + +**/ + + +class Solution { + public int[][] kClosest(int[][] points, int k) { + + + /** + The solution is very simple, for each point(x, y) we calculate the euclidean distance between + (x, y) and the origin point (0, 0), then add all the distances in Priority Queue (Minimum Heap). + The priority queue will sort them in increasing order. + + + NOTE that we need to return the points not the distances, that's why we make Priority Queue of Pair>. + **/ + + PriorityQueue>> pq = + new PriorityQueue<>(new SortBySmallerDistanceComparator()); + + for (int i = 0; i < points.length; ++i) + { + int x = points[i][0], y = points[i][1]; + double distance = Math.sqrt(x * x + y * y); + pq.add(new Pair(distance, new Pair(x, y))); + } + + int [][]closestK = new int[k][2]; + + for(int i = 0; i < k; ++i) + { + closestK[i][0] = pq.peek().getValue().getKey(); + closestK[i][1] = pq.peek().getValue().getValue(); + pq.poll(); + + } + + return closestK; + + } + + + /* + Compartor to sort the points based on the distance (smaller). + */ + + class SortBySmallerDistanceComparator implements Comparator>> + { + @Override + public int compare(Pair> a, + Pair> b) { + return (a.getKey() - b.getKey()) <= 0 ? -1 : 1; + } + } + +} From 9606f8168970807c3f5df97e0050562090a9ec55 Mon Sep 17 00:00:00 2001 From: John Doe Date: Sat, 13 May 2023 21:26:23 +0530 Subject: [PATCH 1077/1894] changes --- ...=> distane_of_nearest_zero_in_matrix.java} | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) rename Dynamic Programming/{Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java => distane_of_nearest_zero_in_matrix.java} (74%) diff --git a/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java b/Dynamic Programming/distane_of_nearest_zero_in_matrix.java similarity index 74% rename from Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java rename to Dynamic Programming/distane_of_nearest_zero_in_matrix.java index 01803ddb..6d3f8109 100644 --- a/Dynamic Programming/Given_an_m_x_n_binary_matrix_mat_return_the_distance_of_the_nearest_0_for_each_cell.java +++ b/Dynamic Programming/distane_of_nearest_zero_in_matrix.java @@ -26,17 +26,21 @@ class Solution { public int[][] updateMatrix(int[][] mat) { int m = mat.length; int n = mat[0].length; - int[][] distances = new int[m][n]; - Queue queue = new LinkedList<>(); + int[][] distances = new int[m][n]; // Initialize a distances matrix + Queue queue = new LinkedList<>(); // Initialize a queue for BFS + + // Loop through the matrix and set distances to MAX_VALUE except for cells with 0 for (int i = 0; i < m; i++) { Arrays.fill(distances[i], Integer.MAX_VALUE); for (int j = 0; j < n; j++) { if (mat[i][j] == 0) { distances[i][j] = 0; - queue.offer(new int[]{i, j}); + queue.offer(new int[]{i, j}); // Add the cell to the queue } } } + + // Perform BFS while (!queue.isEmpty()) { int[] cell = queue.poll(); int i = cell[0]; @@ -44,17 +48,17 @@ public int[][] updateMatrix(int[][] mat) { for (int[] direction : DIRECTIONS) { int x = i + direction[0]; int y = j + direction[1]; - if (x < 0 || x >= m || y < 0 || y >= n) { + if (x < 0 || x >= m || y < 0 || y >= n) { // Check if cell is out of bounds continue; } - if (distances[x][y] <= distances[i][j] + 1) { + if (distances[x][y] <= distances[i][j] + 1) {// Check if distance is already smaller continue; } - distances[x][y] = distances[i][j] + 1; - queue.offer(new int[]{x, y}); + distances[x][y] = distances[i][j] + 1; // Update the distance + queue.offer(new int[]{x, y});// Add the cell to the queue } } - return distances; + return distances; // Return the updated distances matrix } } From e5f82d96cc1753c94ec8dc771b11e7b622a14fac Mon Sep 17 00:00:00 2001 From: Duz Date: Sat, 13 May 2023 22:06:52 +0200 Subject: [PATCH 1078/1894] added BST kth largest in c++ --- Trees/Binary Search Trees/BST_kth_largest.cpp | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 Trees/Binary Search Trees/BST_kth_largest.cpp diff --git a/Trees/Binary Search Trees/BST_kth_largest.cpp b/Trees/Binary Search Trees/BST_kth_largest.cpp new file mode 100644 index 00000000..eb9b8bc2 --- /dev/null +++ b/Trees/Binary Search Trees/BST_kth_largest.cpp @@ -0,0 +1,167 @@ +/*TASK + Binary Search Tree : Get kth largest element in a BST + A BST is a tree structure that is sorted by the nodes' data. + Following rules are true for every picked node in a BST: + -> all nodes to the left have data that is less than the data of the picked node + -> all nodes to the right have data that is greater than the the data of the picked node + -> all nodes have 2 children (left and right), but they can be empty (null) too. +*/ + +/*SAMPLE DATA + Take a look on the following BST + 3 + 2 7 + 1 5 9 + 4 + + For k = 3, we should get 5 as an output, because 5 is the 3. largest element in the BST +*/ + +/*APPROACH + an recursive algorithm that is going to get to the nodes in descending order. + the visited nodes get appended to an array and if the kth node is visited the recursion will be left + 1. start with the root node of a BST + 2. for each node that is reached, do the first that is possible from the following: + "if possible" means that the node has a valid child in that direction that is not already visited + 1. go to the right if possible to get to the far right node which also has the largest data + 2. go to the left if possible to get larger data than going back + (If the algorithm goes back from the current node, all right nodes will be already visted, that means that we will land on a lower data node) + 3. go back + + If we cannot do 1. we save this node as visited. + The kth visited node is also the kth largest. + if this node is reached it is getting saved in a class member variable. + In each recursion call this variable gets checked. If the node is set (we already found the kth largest node), + the recursion step returns before doing anything. + that is how the programm will get out of the recursion fast after finding the target node. +3. if the member variable is set, that is the kth largest node, if its empty there is no kth largest node (out of range) + +SAMPLE + 1. first we start with the root 3 + 2. we can go right, so we will do so (node 7) + 3. we can go right (node 9) + 4. we cannot go right, we save this in a visited node list (node 9, list 9) + 5. we cannot go left, we go back (node 7) + 6. we cannot go right, because 9 is already visited, we save this in visited nodes (node 7, list 9,7) + 7. we can go left (node 5) + 8. we cannot go right, we save this in visited nodes (node 5, list 9,7,5) + 9. the list's size is equal to k, we will set the member variable to the last saved node 5 (node 5, list 9,7,5, member 5) + 10. we have a member set, we go back (node 7) + 11. we have a member set, we go back (node 3) + 12. we have a member set, we go back (leaving recursion) + 13. member variable holds 5, which is the 3. largest number in the BST +*/ + +/*COMPLEXITY + the algorithm has to go to the far right in h steps, where h is the height of the tree + and additionally k steps to get to the kth largest value. to break out the programm needs additionally h steps + Time complexity is O(2*h+k). The complexity class is O(n), because h is linear in a worst case (skewed to one side) and k is also linear. + Space complexity is O(h), because the algorithm needs to store a maximum of h recursion calls. + The complexity class is O(n), because h is linear in a worst case (skewed to one side). + But in a balanced tree it is only O(log(n)), because h is log(n), where n is the number of nodes in the balanced tree. +*/ +#include +#include +#include +class Node{ + //Node class holds one node of the tree + //every node holds some data (int) and has two children + //an empty children gets represented with nullptr +public: + int data; + Node* left; + Node* right; + +public: + Node(int item){ + //init the node with no children + data = item; + left = nullptr; + right = nullptr; + } + virtual ~Node(){ + /* + IMPORTANT to avoid memory leaks + a virtual constructor is required to correctly delete all children (and children of children) + checking if the child is not empty than calling the children's destructor + */ + if(left != nullptr){delete left;} + if(right != nullptr){delete right;} + }; +}; + +class BinaryTree{ + //holds the full tree (and tree functionalities) +private: + Node* kth_largest; //that is the member variable that our algorithm uses to save the target node + std::vector visited_nodes; //the list of visited nodes +public: + Node* root; //pointer to the root node of the BST + +private: + void traverseRL(Node* node, int k){ + //this method is traversing the BST from the largest to the smallest element + //this algorithm is taking the root node and the k + if(this->kth_largest != nullptr){ //are we ready? + return; + } + if(node->right != nullptr){ //can we go to the right? + traverseRL(node->right, k); //go to the right + } + this->visited_nodes.push_back(node); //cannot go more right, add to visited nodes + if(this->visited_nodes.size() == k){ //if the visited nodes list is long enough to hold the target node + this->kth_largest = node; //save this node in the member variable + return; //start to break down the recursion + } + if(node->left != nullptr){ //can we go to the left? + traverseRL(node->left, k); //go to the left + } + return; //this node is already dealt with + } + +public: + BinaryTree(int root_data){ + //creates a binary tree with one node (root) that gets some given data + kth_largest = nullptr; + root = new Node(root_data); + } + Node* insertNode(Node* node, int data){ //insert a new node on the right position (remember the BST rules) + if(node == nullptr){ //if we reach an empty spot we set the new node there + return new Node(data); + } + if(data <= node->data){ //data is smaller than the data of the current node + node->left = insertNode(node->left, data); //we have to got to the left + } + else{ //data is greater than the data of the current node + node->right = insertNode(node->right, data); //we have to got to the right + } + return node; //get the node back to the previous recursion layer + } + + Node* getKthLargest(int k){ //get the kth largest data node + this->kth_largest = nullptr; //init the member variables that are needed for the algorithm + this->visited_nodes.clear(); + this->traverseRL(this->root, k); //perform the search + if(this->kth_largest == nullptr){ //kth largest element cannot be found (out of range) + std::cout << "There is no " << k << ". largest element in this tree" << std::endl; + std::cout << "Valid k's for a tree are numbers between 1 and the number of nodes inclusive"; + return nullptr; + }else{ + return this->kth_largest; //returrn the kth largest node + } + } +}; + +int main() { + //sample + int k = 3; + BinaryTree tree = BinaryTree(3); //building up the sample BST + tree.insertNode(tree.root, 7); + tree.insertNode(tree.root, 2); + tree.insertNode(tree.root, 5); + tree.insertNode(tree.root, 9); + tree.insertNode(tree.root, 1); + tree.insertNode(tree.root, 4); + std::cout << tree.getKthLargest(k)->data << std::endl; //print the result + return 0; +} \ No newline at end of file From 63675ecb57e440d4a67b90f8893bb672767ccaec Mon Sep 17 00:00:00 2001 From: Moritz Richter <79808908+Duzzuti@users.noreply.github.com> Date: Sat, 13 May 2023 22:25:25 +0200 Subject: [PATCH 1079/1894] small typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eff5e6d3..742119b2 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ n <= 10        O(n!) n <= 20        O(2 ^ n) n <= 500         O(n ^ 3) n <= 5000       O(n ^ 2) -n <= 106      O(nlogn) or O(n) +n <= 10^6      O(nlogn) or O(n) n is large      O(1) or O(logn) For example, if the input size is n = 10 ^ 5, it is probably expected that the time complexity of the algorithm is O(n) or O(nlogn). This information makes it easier to design the algorithm, because it rules out approaches that would yield an algorithm with a worse time complexity. Still, it is important to remember that a time complexity is only an estimate of efficiency, because it hides the constant factors. For example, an algorithm that runs in O(n) time may perform n/2 or 5n operations. This has an important effect on the actual running time of the algorithm. From 53970f17caf8233fcad03a5e14a08dceb81cf703 Mon Sep 17 00:00:00 2001 From: Moritz Richter <79808908+Duzzuti@users.noreply.github.com> Date: Sat, 13 May 2023 22:30:38 +0200 Subject: [PATCH 1080/1894] added spaces for consistency in Readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 742119b2..6daf1a29 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ n <= 10        O(n!) n <= 20        O(2 ^ n) n <= 500         O(n ^ 3) n <= 5000       O(n ^ 2) -n <= 10^6      O(nlogn) or O(n) +n <= 10 ^ 6      O(nlogn) or O(n) n is large      O(1) or O(logn) For example, if the input size is n = 10 ^ 5, it is probably expected that the time complexity of the algorithm is O(n) or O(nlogn). This information makes it easier to design the algorithm, because it rules out approaches that would yield an algorithm with a worse time complexity. Still, it is important to remember that a time complexity is only an estimate of efficiency, because it hides the constant factors. For example, an algorithm that runs in O(n) time may perform n/2 or 5n operations. This has an important effect on the actual running time of the algorithm. From 576226589f8891a665294bce8dce3e369a98f576 Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Sun, 14 May 2023 02:55:38 +0530 Subject: [PATCH 1081/1894] BST Code Updated --- .../Binary Search Trees/Kth_largest_BST.java | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Trees/Binary Search Trees/Kth_largest_BST.java diff --git a/Trees/Binary Search Trees/Kth_largest_BST.java b/Trees/Binary Search Trees/Kth_largest_BST.java new file mode 100644 index 00000000..0f268db8 --- /dev/null +++ b/Trees/Binary Search Trees/Kth_largest_BST.java @@ -0,0 +1,101 @@ +/** + * A class to represent a node in the BST. + */ +class Node { + int data; + Node left, right; + + Node(int data) { + this.data = data; + left = right = null; + } +} + +/** + * A class to represent a binary search tree. + */ +class BST { + Node root; + + BST() { + root = null; + } + + /** + * Function to find the kth largest element in the BST. + Time complexity: O(n), where n is the number of nodes in the BST. This is because we need to visit every node in the worst case to find the kth largest element. + Space complexity: O(h), where h is the height of the BST. This is because we're recursively traversing the tree using a call stack, which can have at most h frames in it + + The kthLargest() function takes an integer k as input and returns the kth largest element in the BST. It first creates an empty result list, calls the kthLargestHelper() function to traverse the BST in reverse inorder, and collects the kth largest element in the result list. It then returns the last element of the result list, which is the kth largest element in the BST. + + Time complexity: O(k), since we're only collecting up to k elements in the result list. + pace complexity: O(h), where h is the height of the BST. This is because we're recursively traversing the tree using a call stack, which can have at most h frames in it + */ + public int kthLargest(int k) { + List result = new ArrayList<>(); + kthLargestHelper(root, result, k); + return result.get(result.size() - 1); + } + + + /**The kthLargestHelper() function is a helper function to traverse the BST in reverse inorder and collect the kth largest element in the result list. It first recursively calls itself on the right child of the current node, then adds the current node's `data */ + private void kthLargestHelper(Node node, List result, int k) { + if (node == null || result.size() == k) { + return; + } + kthLargestHelper(node.right, result, k); + if (result.size() < k) { + result.add(node.data); + } + kthLargestHelper(node.left, result, k); + } + + /** + * Function to insert a node in the BST. + Time complexity: O(h), where h is the height of the BST. This is because we're traversing the tree from the root to the correct position for the new node. + Space complexity: O(1), since we're only creating a new node and not using any extra memory. + */ + public void insert(int data) { + root = insertHelper(root, data); + } + + /** + * Helper function to insert a node in the BST. + Time complexity: O(h), where h is the height of the BST. This is because we're traversing the tree from the root to the correct position for the new node. +S pace complexity: O(1), since we're only creating a new node and not using any extra memory. + + */ + private Node insertHelper(Node node, int data) { + if (node == null) { + node = new Node(data); + return node; + } + if (data < node.data) { + node.left = insertHelper(node.left, data); + } else if (data > node.data) { + node.right = insertHelper(node.right, data); + } + return node; + } +} + +/** + * A class to test the BST implementation. + */ +public class KthLargestBST { + public static void main(String[] args) { + BST bst = new BST(); + bst.insert(50); + bst.insert(30); + bst.insert(20); + bst.insert(40); + bst.insert(70); + bst.insert(60); + bst.insert(80); + int k = 3; + int kthLargest = bst.kthLargest(k); + System.out.println(k + "th largest element in the BST is " + kthLargest); + } +} + +/**Overall, the time complexity of finding the kth largest element in a BST using this code is O(n), and the space complexity is O(h). */ From a5f561bbcc69a52c35a6bca59b2b67b70d740a91 Mon Sep 17 00:00:00 2001 From: mrenigmatic19 <96334291+mrenigmatic19@users.noreply.github.com> Date: Sun, 14 May 2023 13:02:52 +0530 Subject: [PATCH 1082/1894] Create Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp Done the Changes....Please Review it. --- ..._Two_Pointer_Merge_Sorted_Array_in_C++.cpp | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp diff --git a/Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp b/Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp new file mode 100644 index 00000000..3a32f49f --- /dev/null +++ b/Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp @@ -0,0 +1,67 @@ +/* +Problem Statement :- You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, +and two integers m and n, representing the number of elements in nums1 and nums2 respectively. +Merge nums1 and nums2 into a single array sorted in non-decreasing order. +The final sorted array should not be returned by the function, but instead be stored inside the array nums1. +To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, +and the last n elements are set to 0 and should be ignored. nums2 has a length of n. +Example 1 :- +Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 +Output: [1,2,2,3,5,6] +Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. +The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. +Example 2 :- +Input: nums1 = [1], m = 1, nums2 = [], n = 0 +Output: [1] +Explanation: The arrays we are merging are [1] and []. +The result of the merge is [1]. +Example 3 :- +Input: nums1 = [0], m = 0, nums2 = [1], n = 1 +Output: [1] +Explanation: The arrays we are merging are [] and [1]. +The result of the merge is [1]. +Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. +*/ +// Two Pointer Approch From index 0; + +void merge( vector < int > & nums1 , int m , vector< int > & nums2 , int n ) { + int i , j = 0 , u = 0 ; + vector< int > temp ; + + for( i = 0 ; i < m ; i++ ) + temp.push_back( nums1[i] ) ; // Copying the element form num1 that is needed to merged + + i = 0 ; + while( i < m && j < n ){ + + if( temp[i] > nums2[j] ) + nums1[ u++ ] = nums2[ j++ ] ; + else + nums1[ u++ ] = temp[ i++ ] ; + } + + while( i < m ) + nums1[ u++ ] = temp[ i++ ] ; + + while( j < n ) + nums1[ u++ ] = nums2[ j++ ] ; + +} + +// Two Pointer Approch From index last + + void merge( vector< int > & nums1 , int m , vector< int > & nums2 , int n ) { + + int j = n-1 , i = m-1 , k = m+n-1 ; + + while( j >= 0 ){ + if( i >= 0 && nums1[ i ] > nums2[ j ] ) + nums1[ k-- ] = nums1[ i-- ] ; + else + nums1[ k-- ] = nums2[ j-- ] ; + + } + } +/* +Tip :- Dry Run this code on Copy to Understand the key factors. +*/ From 01bac66fb383b4e05f58920fced39f8759ec7de2 Mon Sep 17 00:00:00 2001 From: Duz Date: Sun, 14 May 2023 10:22:50 +0200 Subject: [PATCH 1083/1894] added greedy coin change in python --- Greedy/coin_change.py | 149 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 Greedy/coin_change.py diff --git a/Greedy/coin_change.py b/Greedy/coin_change.py new file mode 100644 index 00000000..1c848418 --- /dev/null +++ b/Greedy/coin_change.py @@ -0,0 +1,149 @@ +"""TASK + Greedy: provide a greedy solution for the coin change problem + A greedy algorithm is trying to make the best local decisions, without caring about future decisions. + That means that a greedy algorithm is faster than better approaches but it has not always the best solution + In some case a greedy approach does not find a solution at all. + + The coin change problem: + -> given sum s + -> given list of possible coin types l + + The output has to be a list r, which's elements represent coins from coin types from l. + r[i] is in l for every i with [0 <= i < length r]; + The sum of r has to be s; + Furthermore the length of r has to be minimal; + + In other words we need to calculate a way to reach the sum s with minimal coins from coin types l + + +SAMPLE DATA + Take a look on the following Samples + Sample A (good for greedy): + s = 60 + l = [25, 10, 5]; + Best output r = [25,25,10] (take 2 coins from type 25 and one 10, we get 60 with only three coins) + + Sample B (bad for greedy): + s = 50; + l = [30, 25, 10, 5] + Best output r = [25,25] (take 2 coins from type 25, we get 50 with only two coins) + + Sample C (greedy fails) + s = 50 + l = [30, 25] + Best output r = [25,25] (take 2 coins from type 25, we get 50 with only two coins)decisions + +APPROACH + The greedy approach is very simple + 1. We have to sort l in descendig order + 2. Iterate over the sorted list, in each step: + 1. if the sum of r is equal to s, break + 2. add n coins of type l[i] to r where n is maximal and sum(r) + l[i]*n <= s (add as many as we can from this coins type) + 3. if the sum of r is equal to s, return r; otherwise the greedy algorithm has failed + +SAMPLE A + 1. l in descending order l = [25,10,5] + 2. loop over l (element 25, r=[]) + 3. take 2 25 coins because 0+25*2 <= 60 but not 0+25*3 <= 60 (sum(r)+l[i]*n <= s) + 4. next iteration (elment 10, r=[25,25]) + 5. take 1 10 coin because 50+10*1 <= 60 (r=[25,25,10]) + 6. sumr == s => break + 7. return r + +SAMPLE B + the greedy takes one 30 coin, a 25 coin cannot be taken (30+25 > 25), but 2 10 coins + r = [30, 10, 10] + the number of coins is 3, but the optimal solution is 2 [25,25]. + A greedy algorithm does not provide the optimnal solution + +SAMPLE C + the greedy takes the 30 coin. But this is a bad decision for the future, because the 25 coin cannot be taken (30+25 > 50) + that means that the greedy does not provide any solution because a bad decision was made. + To get this solution you have to do a dynamic programmic approach + +COMPLEXITY + With sorting (random list l): + sorting takes log(l)*l time. + looping over l takes O(l) time + looping over n takes O(n) time + thats a time complexity of O(l*logl + l*n) + n is dependend on s and l (for a big s and small l values n gets big, for heavily skewed l values too [1000000,1] for s = 1999999) + that means that time complexity class will be O(n ^ 2) in worst case (because n is linear to s) + If it is assumed that n is always in a certain range (i.e below 10), the time complexity class will be O(n*logn) + + sorting has O(l) space complexity + the space complexity for the whole algorithm is O(l+r) with r being the length of r. + Best case space complexity class is O(n) where r is assumed very small (linear or better) + Otherwise the space complexity is O(r). r is dependend on s (linear): + s = 9 + l = [10, 1] + r = [1,1,1,1,1,1,1,1,1] which is O(s) + + that means that space complexity class is O(n) + + Without sorting (sorted list l): + looping over l takes O(l) time + looping over n takes O(n) time + thats a time complexity of O(l*n) + n is dependend on s and l (linear) + that means that time complexity class will be O(n ^ 2) in worst case + If it is assumed that n is always in a certain range (i.e below 10), the time complexity class will be O(n) + + the space complexity for the whole algorithm is O(r) with r being the length of r. + Best case space complexity class is O(1) where r is assumed very small (linear or better) + Otherwise the space complexity is O(n) r is dependend on s (linear) + + that means that space complexity class is O(n) (or O(1) in best case) +""" + +def coinChangeGreedy(s:int, l:list[int]): + #first step: sort l descending + l.sort(reverse=True) #uses some log(n)*n algorithm + r = [] #return list + sumr:int = 0 #keep track of the current sum of r to avoid iterating over r to calculate the sum + for coin in l: + if(sumr == s): #the sum of r is the target sum s + break + n = int((s - sumr)/coin) #calculate the max n with sum(r) + l[i]*n <= s + for i in range(n): #append n elements of this coin to r + r.append(coin) + sumr += coin*n #update the r sum + if(sumr != s): #the target sum s was not reached + return False + return r + +#without sorting +def coinChangeGreedySorted(s:int, l:list[int]): + r = [] #return list + sumr:int = 0 #keep track of the current sum of r to avoid iterating over r to calculate the sum + for coin in l: + if(sumr == s): #the sum of r is the target sum s + break + n = int((s - sumr)/coin) #calculate the max n with sum(r) + l[i]*n <= s + for i in range(n): #append n elements of this coin to r + r.append(coin) + sumr += coin*n #update the r sum + if(sumr != s): #the target sum s was not reached + return False + return r + + +#SAMPLE 1 (optimal) +print(coinChangeGreedy(60, [5, 10, 25])) + +#SAMPLE 2 (not optimal) +print(coinChangeGreedy(50, [25, 10, 30, 5])) + +#SAMPLE 3 (fails) +print(coinChangeGreedy(50, [25, 30])) + +print() + +#SAMPLE 1 (optimal) +print(coinChangeGreedySorted(60, [25, 10, 5])) + +#SAMPLE 2 (not optimal) +print(coinChangeGreedySorted(50, [30, 25, 10, 5])) + +#SAMPLE 3 (fails) +print(coinChangeGreedySorted(50, [30, 25])) \ No newline at end of file From 895d713c8eb5fb13d65a3d44c7b0f585ad67f539 Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Sun, 14 May 2023 15:24:02 +0530 Subject: [PATCH 1084/1894] Heap Sort Implemented in Javascript --- sorting/heap_sort.js | 77 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 sorting/heap_sort.js diff --git a/sorting/heap_sort.js b/sorting/heap_sort.js new file mode 100644 index 00000000..c89fa285 --- /dev/null +++ b/sorting/heap_sort.js @@ -0,0 +1,77 @@ +/** +Heap Sort is a sorting algorithm that works by building a binary heap out of the input array and then repeatedly extracting the maximum element and restoring the heap property. The time complexity of Heap Sort is O(n log n) in the worst, average, and best cases, making it an efficient algorithm for sorting large data sets. The space complexity of the implementation is O(1) because the algorithm sorts the input array in place and does not use any additional data structures other than a few variables used for index tracking and swapping. Therefore, the space used by the algorithm does not depend on the size of the input array. +*/ + +/** + * The heapSort function takes an array as input and returns a sorted array using the Heap Sort algorithm. The function first builds a max heap from the input array using the buildMaxHeap function. It then repeatedly extracts the maximum element from the heap and restores the heap property using the siftDown function + * @param {Array} array The array to be sorted. + * @returns {Array} The sorted array. + * time complexity is O(n log n) because it calls buildMaxHeap function once and then the siftDown function n times in the worst case, where n is the length of the input array. + */ + function heapSort(array) { + // Build a max heap from the input array + buildMaxHeap(array); + + // Extract the max element from the heap and restore the heap property + for (let i = array.length - 1; i > 0; i--) { + // Move the root element to the end of the array + swap(array, 0, i); + + // Restore the heap property by sifting down the root element + siftDown(array, 0, i); + } + + return array; + } + + /** + * The buildMaxHeap function takes an array as input and transforms it into a max heap by calling siftDown on each non-leaf node in the tree. + * @param {Array} array The array to be transformed into a max heap. + * time complexity is O(n) because it calls the siftDown function on each non-leaf node in the tree + */ + function buildMaxHeap(array) { + const startIndex = Math.floor((array.length - 1) / 2); + + for (let i = startIndex; i >= 0; i--) { + siftDown(array, i, array.length); + } + } + + /** + * The siftDown function takes an array, an index, and an endIndex as input. It sifts down the element at the given index in the heap until it reaches its correct position. + * @param {Array} array The array representing the heap. + * @param {number} index The index of the element to be sifted down. + * @param {number} endIndex The index at which to stop sifting down. + * time complexity is O(log n) because it repeatedly swaps the element at the given index with its child elements until it reaches its correct position in the heap. + */ + function siftDown(array, index, endIndex) { + let childIndex1 = index * 2 + 1; + while (childIndex1 < endIndex) { + const childIndex2 = index * 2 + 2 < endIndex ? index * 2 + 2 : null; + const swapIndex = + childIndex2 !== null && array[childIndex2] > array[childIndex1] + ? childIndex2 + : childIndex1; + + if (array[swapIndex] > array[index]) { + swap(array, index, swapIndex); + index = swapIndex; + childIndex1 = index * 2 + 1; + } else { + return; + } + } + } + + /** + * The swap function takes an array and two indices as input and swaps the elements at those indices. It is used in the heapSort function to move the root element of the heap to the end of the array during each iteration of the main loop. This function is also used within the siftDown function to swap the parent element with its child element when restoring the heap property. + * @param {Array} array The array containing the elements to be swapped. + * @param {number} i The index of the first element. + * @param {number} j The index of the second element. + */ + function swap(array, i, j) { + const temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + \ No newline at end of file From c36997ea43eb115edb70d59cb6a6d84722447315 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Sun, 14 May 2023 19:14:31 +0530 Subject: [PATCH 1085/1894] Heapsort implemented in c++ --- sorting/heapSort.cpp | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 sorting/heapSort.cpp diff --git a/sorting/heapSort.cpp b/sorting/heapSort.cpp new file mode 100644 index 00000000..649790d2 --- /dev/null +++ b/sorting/heapSort.cpp @@ -0,0 +1,66 @@ +/*This implementation uses a vector to store the elements to be sorted. The heapify function is used to create a max heap and maintain the heap property. The heapSort function performs the heap sort algorithm by repeatedly extracting the maximum element from the heap. Finally, the printArray function is a utility function to print the elements of an array.*/ +/* time complexity O(n log n) + Space complexity O(1) */ +#include +#include + +using namespace std; + +void heapify(vector& arr, int n, int i) { + int largest = i; // Initialize largest as root + int left = 2 * i + 1; // Left child + int right = 2 * i + 2; // Right child + + // If left child is larger than root + if (left < n && arr[left] > arr[largest]) + largest = left; + + // If right child is larger than largest so far + if (right < n && arr[right] > arr[largest]) + largest = right; + + // If largest is not root + if (largest != i) { + swap(arr[i], arr[largest]); + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +void heapSort(vector& arr) { + int n = arr.size(); + + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i = n - 1; i > 0; i--) { + // Move current root to end + swap(arr[0], arr[i]); + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +// Utility function to print an array +void printArray(const vector& arr) { + for (int i = 0; i < arr.size(); ++i) + cout << arr[i] << " "; + cout << endl; +} + +int main() { + vector arr = {12, 11, 13, 5, 6, 7}; + cout << "Original array: "; + printArray(arr); + + heapSort(arr); + + cout << "Sorted array: "; + printArray(arr); + + return 0; +} From 9fa4eee90f9d3153cc9da602f30227fd517d4d06 Mon Sep 17 00:00:00 2001 From: jayesh-RN <100137975+jayesh-RN@users.noreply.github.com> Date: Sun, 14 May 2023 19:47:11 +0530 Subject: [PATCH 1086/1894] Validate_BST.cpp with comments --- Trees/Binary Search Trees/Validate_BST.cpp | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Trees/Binary Search Trees/Validate_BST.cpp b/Trees/Binary Search Trees/Validate_BST.cpp index 0a183188..4c5d33ab 100644 --- a/Trees/Binary Search Trees/Validate_BST.cpp +++ b/Trees/Binary Search Trees/Validate_BST.cpp @@ -24,10 +24,14 @@ +// C++ program to check if a given tree is BST. #include using namespace std; + + struct Node { + // structure of a node of the tree. int data; struct Node *left, *right; @@ -41,13 +45,18 @@ struct Node { bool validate(Node* root,long long int min , long long int max){ if(!root) - return true; - bool ans = false; + return true; // if the root is null then it is a valid BST. it means that the tree is empty or we had reached the end of tree. + // initializing the ans variable to false (temporarily). + bool ans = false; + + // checking if the root's data is in the range of min and max. if(root->datadata>min) ans = true; else - return ans; - return ans && validate(root->left,min,root->data) && + return ans; // if the root's data is not in the range of min and max then it is not a valid BST. hence returning false. + + // changing min and max for the left and right subtree. and checking for the left and right subtree with respesct to tree root and returning the ans. + return ans && validate(root->left,min,root->data) && validate(root->right,root->data,max); } @@ -55,17 +64,22 @@ bool validate(Node* root,long long int min , long long int max){ bool isValidBST(Node* root) { if(!root) return true; + + // calling validate function so that it can check for the left and right subtree .. while giving the range of the values of the nodes. return validate(root ,-9223372036854775807,9223372036854775807 ); } int main() { + + // Initializing the tree. struct Node* root = new Node(3); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(1); root->left->right = new Node(4); + // calling the function to check BST. if (isValidBST(root)) cout << "Is BST"; else From 3aa035a2f708b3c3d4ee8bea87d4198a396e8858 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 14 May 2023 22:02:56 +0530 Subject: [PATCH 1087/1894] Create distance_of_nearest_zero.js Merge this solution for the issue: Dynamic Programming: Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Javascript --- .../distance_of_nearest_zero.js | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Dynamic Programming/distance_of_nearest_zero.js diff --git a/Dynamic Programming/distance_of_nearest_zero.js b/Dynamic Programming/distance_of_nearest_zero.js new file mode 100644 index 00000000..9495c1c6 --- /dev/null +++ b/Dynamic Programming/distance_of_nearest_zero.js @@ -0,0 +1,50 @@ +Example: +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] + +It can be solved using a Breadth First Search Algorithm(BFS) + +function updateMatrix(mat) { + const m = mat.length; + const n = mat[0].length; + const queue = []; + + // Initialize distance matrix with maximum possible values + const dist = new Array(m).fill().map(() => new Array(n).fill(Number.MAX_VALUE)); + + // Initialize the queue with all cells containing 0 + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (mat[i][j] === 0) { + dist[i][j] = 0; + queue.push([i, j]); + } + } + } + + // Perform a BFS starting from the cells containing 0 + while (queue.length > 0) { + const [i, j] = queue.shift(); + + // Check the neighbors of the current cell + const neighbors = [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]; + for (const [ni, nj] of neighbors) { + // Check if the neighbor is within bounds + if (ni >= 0 && ni < m && nj >= 0 && nj < n) { + // If the distance to the neighbor can be updated + if (dist[ni][nj] > dist[i][j] + 1) { + dist[ni][nj] = dist[i][j] + 1; + queue.push([ni, nj]); + } + } + } + } + + return dist; +} + + +The updateMatrix function takes a binary matrix mat as input and returns a matrix dist with the distance of the nearest 0 for each cell. +The algorithm first initializes the dist matrix with maximum possible values and adds all cells containing 0 to a queue. +Then, it performs a BFS starting from the cells in the queue and updates the distances of the neighboring cells if they can be improved. +Finally, it returns the dist matrix with the updated distances. From a6c6c14ed0b89512f874a728a6b1cbd897c4c64f Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 14 May 2023 22:24:48 +0530 Subject: [PATCH 1088/1894] Create Merge_Sorted_array.go Pull request for the issue Two Pointers: Merge sorted array with Go --- Arrays/Merge_Sorted_array.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Arrays/Merge_Sorted_array.go diff --git a/Arrays/Merge_Sorted_array.go b/Arrays/Merge_Sorted_array.go new file mode 100644 index 00000000..809106e7 --- /dev/null +++ b/Arrays/Merge_Sorted_array.go @@ -0,0 +1,34 @@ +Example: +Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 +Output: [1,2,2,3,5,6] + +Here's an implementation in Go to merge two sorted arrays: + +func merge(nums1 []int, m int, nums2 []int, n int) { + i := m - 1 // Index of last element in nums1 + j := n - 1 // Index of last element in nums2 + + // Merge from the end of the arrays to avoid overwriting + for k := m + n - 1; k >= 0; k-- { + if j < 0 { + // No more elements in nums2, nums1 already sorted + return + } + if i >= 0 && nums1[i] > nums2[j] { + nums1[k] = nums1[i] + i-- + } else { + nums1[k] = nums2[j] + j-- + } + } +} + +The merge function takes in two sorted arrays nums1 and nums2, where nums1 has m elements and nums2 has n elements. +The function then merges nums2 into nums1 in-place, resulting in a single sorted array. + +Starting from the end of both arrays, the function compares the last elements of nums1 and nums2, +and puts the larger one at the end of nums1. This process continues until all elements in nums2 have been merged into nums1. + +Note that since nums1 has enough space to accommodate all elements, we don't need to create a new array to store the merged elements. +We can just overwrite the 0 elements at the end of nums1 with the merged elements. From 83cc31a9ba8592610d95103120a5518284d2d8bb Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 14 May 2023 22:41:53 +0530 Subject: [PATCH 1089/1894] Create bucket_sort.js Pull request for the issue: Implement bucket sort in Javascript --- sorting/bucket_sort.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 sorting/bucket_sort.js diff --git a/sorting/bucket_sort.js b/sorting/bucket_sort.js new file mode 100644 index 00000000..4c32f1e9 --- /dev/null +++ b/sorting/bucket_sort.js @@ -0,0 +1,38 @@ +Here's an implementation of bucket sort in JavaScript: + +function bucketSort(arr, numBuckets = 10) { + const n = arr.length; + const buckets = new Array(numBuckets); + + // Initialize the buckets + for (let i = 0; i < numBuckets; i++) { + buckets[i] = []; + } + + // Distribute the elements into the buckets + for (let i = 0; i < n; i++) { + const bucketIndex = Math.floor(arr[i] * numBuckets); + buckets[bucketIndex].push(arr[i]); + } + + // Sort the elements within each bucket + for (let i = 0; i < numBuckets; i++) { + buckets[i].sort((a, b) => a - b); + } + + // Concatenate the sorted buckets + let sortedArr = []; + for (let i = 0; i < numBuckets; i++) { + sortedArr = sortedArr.concat(buckets[i]); + } + + return sortedArr; +} + + +The bucketSort function takes an array arr of numbers and an optional parameter numBuckets that specifies the number of buckets to use (default is 10). +The algorithm works by distributing the elements of arr into numBuckets buckets based on their value. Each bucket contains elements within a range of values, +and since the buckets are sorted, the elements within each bucket are sorted as well. Finally, the sorted buckets are concatenated to obtain the final sorted +array. + +Note that the performance of bucket sort depends on the distribution of the elements in the input array. If the elements are evenly distributed, bucket sort can achieve a time complexity of O(n), which is faster than many other sorting algorithms. However, if the elements are concentrated in a small range of values, the buckets may become unbalanced and the performance may degrade. Therefore, bucket sort is often used as a sub-routine in other sorting algorithms, or when the distribution of the input is known to be relatively even. From a1d4ab7325e0e71f55a3b7de59a7d2bd86c139c9 Mon Sep 17 00:00:00 2001 From: Niraj Date: Sun, 14 May 2023 23:15:56 +0530 Subject: [PATCH 1090/1894] #1012 Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area --- .../Largest_Rectangle_In_Binary_Matrix.js | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js new file mode 100644 index 00000000..bd359139 --- /dev/null +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js @@ -0,0 +1,75 @@ +//Program Author : TheCodeVenturer [Niraj Modi] +/* + Problem Definition: + Dynamic Programming: Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area in Python + Approach: + This Problem can be termed as updated version of Largest Rectangle in Histogram + If you are given a binary matrix then you can use no.of rows together with one as height + Like + 0 1 1 0 + 1 1 1 1 + 1 1 1 1 + 1 1 0 0 + If you can Visualise then it will be clear that for + first row the histogram row is like [0,1,1,0] + second row the histogram row is like [1,2,2,1] + third row the histogram row is like [2,3,3,2] + fourth row the histogram row is like [3,4,0,0] + then by using a monotonic stack for each row we can get The Largest Rectangle in the Binary Matrix + + we are taking here a row list which keeps track of current height of a particular column . Here, ShiftRow + we are also using a solution variable to keep track of largest rectangle + then first we will iterate through each row + and inside each iteration we will go and look for the particular element of that row matrix[i][j] + if it is 1 then will increase size of jth entry in the shiftRow else will convert it to zero + next will initialize an empty Stack [Monotonic] + next we will iterate through the shiftRow and will first check for the list is not empty and (it's top element is greater than or equal to current element or value of current column is equal to row size) + then will store it's height from the current row array and will update width of the rectangle with stack's top element and will finally update the sol + and will insert the element to the stack + Complexity: + Time Complexity: O(rows * col) for for traversing through each elements of the array + Here in each iteration we are doint three times O(n) => O(3n) ~ O(n) + Space Complexity: O(n) for the shiftRow and O(n) for the stack we are using => O(2n) ~ O(n) + Sample input/outputs: + Example 1: + Input: [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] + Output: 8 + + Example 2: + Input: [[0,1,1],[1,1,1],[0,1,1]] + Output: 6 +*/ +var maxArea = function (matrix, rows, cols) { + let shiftRow = new Array(cols).fill(0); //initialising the row which update after each iteration + var sol = 0; + for (let row of matrix) { + for (let i = 0; i < row.length; i++) { + // Updating the shiftRow if value of ele is 1 => ShiftRow[i] <- shiftRow[i]+1 + // else shiftRow[i]=0 + var ele = row[i]; + if (ele == 1) shiftRow[i]++; + else shiftRow[i] = 0; + } + st = []; + for (let i = 0; i < cols + 1; i++) { + while (st.length > 0 &&(i == cols || shiftRow[st[st.length - 1]] >= shiftRow[i])) { + //checking TOS st.length-1 + height = shiftRow[st[st.length - 1]]; //for getting height of Current index + st.pop(); + width = i; // setting width to i as it is only smallest from beginning + if (st.length > 0) width = i - st[st.length - 1] - 1; // updating width is stack is not empty as it is not the smallest element + sol = Math.max(height * width, sol); // Updating the sol + } + st.push(i); // Pushing the Element's index to the stack + } + } + return sol; +}; + +var matrix = [ + [0, 1, 1, 0], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 0, 0], +]; +console.log(maxArea(matrix, 4, 4)); From 2add31dd577e6c334af944de70db4e5ae70754e8 Mon Sep 17 00:00:00 2001 From: Harsit-Agarwalla Date: Mon, 15 May 2023 19:08:51 +0530 Subject: [PATCH 1091/1894] Add Validate BST in Java --- Trees/Binary Search Trees/Validate_BST.java | 56 +++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Trees/Binary Search Trees/Validate_BST.java diff --git a/Trees/Binary Search Trees/Validate_BST.java b/Trees/Binary Search Trees/Validate_BST.java new file mode 100644 index 00000000..66066825 --- /dev/null +++ b/Trees/Binary Search Trees/Validate_BST.java @@ -0,0 +1,56 @@ +////// Explanation: +// To validate a Binary Search Tree (BST), we need to ensure that the values of nodes in the left subtree of any node are less than the value of the node, and the values of nodes in the right subtree are greater than the value of the node. +// Additionally, the left and right subtrees themselves must also be valid BSTs. + +////// Code: +class HelloWorld { + public static class Node { + public int data; + public Node left, right; + + public Node(int data) { + this.data = data; + left = null; + right = null; + } + }; + + static Node prev; + + static Boolean isBST(Node root) { + + // traverse the tree in inorder fashion and // keep track of prev node + if (root == null) + return true; + + if (!isBST(root.left)) + return false; + + if (prev != null && root.data <= prev.data) + return false; + + prev = root; + return isBST(root.right); + } + + public static void main(String[] args) { + + Node root = new Node(1); + root.left = new Node(-2); + root.right = new Node(3); + root.left.left = new Node(-4); + root.left.right = new Node(-1); + root.right.left = new Node(2); + root.right.right = new Node(7); + + // Function call + if (isBST(root)) + System.out.println("Is Valid BST"); + else + System.out.println("Not a Valid BST"); + } +} + +////// Complexity: +// Time Complexity: O(n) where n is number of nodes +// Space Complexity: O(1) \ No newline at end of file From b9f292a4e57b3dbc9f652681e25144acc66b05c1 Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Mon, 15 May 2023 19:57:39 +0530 Subject: [PATCH 1092/1894] Kth Largest BST Implemented in JS --- Trees/Binary Search Trees/Kth_largest_BST.js | 138 +++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 Trees/Binary Search Trees/Kth_largest_BST.js diff --git a/Trees/Binary Search Trees/Kth_largest_BST.js b/Trees/Binary Search Trees/Kth_largest_BST.js new file mode 100644 index 00000000..c9726bad --- /dev/null +++ b/Trees/Binary Search Trees/Kth_largest_BST.js @@ -0,0 +1,138 @@ +/** + The Node class represents a single node in the BST. It has three properties: value to store the node's value, left to store the reference to the left child node, and right to store the reference to the right child node. + */ + class Node { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } + } + + /** + the BST class represents the Binary Search Tree. It has one property: root to store the reference to the root node of the tree. + */ + class BST { + constructor() { + this.root = null; + } + + /** + insert(value): This function inserts a new node with the given value into the BST. It uses the insertNode helper function for recursive insertion. The time complexity is O(log n) on average (O(n) in the worst case if the tree is heavily unbalanced), and the space complexity is O(1). + * @param {number} value - The value to be inserted + */ + insert(value) { + const newNode = new Node(value); + + if (this.root === null) { + this.root = newNode; + } else { + this.insertNode(this.root, newNode); + } + } + + /** + The insertNode(node, newNode) function is a helper function used by the insert(value) method in the BST class. It recursively inserts a new node (newNode). + + Here's a breakdown of how the insertNode function works: + + * It compares the value of the newNode with the value of the node to determine whether to go left or right in the BST. + * If the value of newNode is less than the value of node, it checks if the left child of node is null. If it is, the newNode becomes the left child; otherwise, the function recursively calls itself with the left child node of node. + * If the value of newNode is greater than or equal to the value of node, it checks if the right child of node is null. If it is, the newNode becomes the right child; otherwise, the function recursively calls itself with the right child node of node. + * This process continues until a suitable position is found for the newNode in the BST. + + The time complexity of the insertNode function depends on the structure of the BST. In the average case, when the tree is balanced, the time complexity is O(log n), where n is the number of nodes in the tree. This is because at each level of the tree, the function divides the remaining nodes to be searched by half. However, in the worst case scenario, when the tree is heavily unbalanced (e.g., resembles a linked list), the time complexity becomes O(n), where n is the number of nodes in the tree. This happens when all nodes are in a straight line from the root. + + The space complexity of the insertNode function is O(log n) in the average case and O(n) in the worst case. This is due to the recursive calls that consume memory on the call stack. In the average case, the maximum number of recursive calls is limited by the height of the balanced tree, which is logarithmic to the number of nodes. In the worst case, where the tree is unbalanced, the maximum number of recursive calls is equal to the number of nodes in the tree. + + * @param {Node} node - The current node being traversed + * @param {Node} newNode - The new node to be inserted + */ + insertNode(node, newNode) { + if (newNode.value < node.value) { + if (node.left === null) { + node.left = newNode; + } else { + this.insertNode(node.left, newNode); + } + } else { + if (node.right === null) { + node.right = newNode; + } else { + this.insertNode(node.right, newNode); + } + } + } + + /** + findKthLargest(k): This function finds the Kth largest value in the BST. It first performs an in-order traversal of the tree to retrieve a sorted array of values. If K is larger than the number of nodes in the tree, it returns null. Otherwise, it returns the Kth largest value from the sorted array. The time complexity of this function is O(n), where n is the number of nodes in the tree. The space complexity is O(n) since it stores all the values in the array during the traversal. + * @param {number} k - The Kth largest value to find + * @returns {number|null} - The Kth largest value, or null if it doesn't exist + */ + findKthLargest(k) { + if (k <= 0) { + throw new Error('k should be a positive integer'); + } + + const sortedValues = []; + this.inOrderTraversal(this.root, sortedValues); + + if (k > sortedValues.length) { + return null; + } + + return sortedValues[sortedValues.length - k]; + } + + /** + inOrderTraversal(node, values): This is a helper function that performs an in-order traversal of the BST and stores the sorted values in the given array. It recursively visits the left subtree, then the current node, and finally the right subtree. The time complexity of this function is O(n), where n is the number of nodes in the tree, as it needs to visit each node exactly once. The space complexity is O(n) since it uses the array to store the values. + * @param {Node} node - The current node being traversed + * @param {Array} values - The array to store the sorted values + */ + inOrderTraversal(node, values) { + if (node !== null) { + this.inOrderTraversal(node.left, values); + values.push(node.value); + this.inOrderTraversal(node.right, values); + } + } + } + // Sample input and imlplementation + /** + 5 + / \ + 3 7 + / \ / \ + 2 4 6 8 + + Now, let's find the 3rd largest value in the BST. + + The sorted order of the tree is [2, 3, 4, 5, 6, 7, 8]. + + The 3rd largest value is 6. + + Here's the updated tree with the 3rd largest value marked: + 5 + / \ + 3 7 + / \ / \ + 2 4 6* 8 + + As you can see, the 3rd largest value, 6, is marked with an asterisk (*). + + */ + // Create a new instance of BST +const bst = new BST(); + +// Insert nodes into the BST +bst.insert(5); +bst.insert(3); +bst.insert(7); +bst.insert(2); +bst.insert(4); +bst.insert(6); +bst.insert(8); + +// Find the 3rd largest value +const kthLargest = bst.findKthLargest(3); +console.log(kthLargest); // Output: 6 \ No newline at end of file From ae94c4097fcac06da2b1f6995501c8ec5e7dc4d8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 15 May 2023 23:20:01 +0530 Subject: [PATCH 1093/1894] add reconstruct bst in go --- Trees/Binary Search Trees/reconstruct_bst.go | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Trees/Binary Search Trees/reconstruct_bst.go diff --git a/Trees/Binary Search Trees/reconstruct_bst.go b/Trees/Binary Search Trees/reconstruct_bst.go new file mode 100644 index 00000000..5dfd0c51 --- /dev/null +++ b/Trees/Binary Search Trees/reconstruct_bst.go @@ -0,0 +1,36 @@ +package main + +// BST represents a binary search tree node. +type BST struct { + Value int + Left *BST + Right *BST +} + +// ReconstructBst takes a slice of integers representing the pre-order traversal of a BST and returns the reconstructed BST. +func ReconstructBst(preOrderTraversalValues []int) *BST { + // Base case: If the pre-order traversal is empty, return nil indicating an empty tree. + if len(preOrderTraversalValues) == 0 { + return nil + } + + // Get the current value from the pre-order traversal values. + currentVal := preOrderTraversalValues[0] + + // Find the index where the right subtree starts by searching for the first value greater than or equal to the current value. + rightSubTreeRootIdx := len(preOrderTraversalValues) + for i := 1; i < len(preOrderTraversalValues); i++ { + value := preOrderTraversalValues[i] + if value >= currentVal { + rightSubTreeRootIdx = i + break + } + } + + // Recursively reconstruct the left and right subtrees by calling the ReconstructBst function on the appropriate sub-arrays. + leftSubTree := ReconstructBst(preOrderTraversalValues[1:rightSubTreeRootIdx]) + rightSubTree := ReconstructBst(preOrderTraversalValues[rightSubTreeRootIdx:]) + + // Create a new BST node with the current value and the reconstructed left and right subtrees. + return &BST{Value: currentVal, Left: leftSubTree, Right: rightSubTree} +} From 8cea85e6ea14d09307505c9ff71cc7c8e3562caa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 15 May 2023 23:22:25 +0530 Subject: [PATCH 1094/1894] add approach 2 with better time complexity --- Trees/Binary Search Trees/reconstruct_bst.go | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Trees/Binary Search Trees/reconstruct_bst.go b/Trees/Binary Search Trees/reconstruct_bst.go index 5dfd0c51..0408f695 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.go +++ b/Trees/Binary Search Trees/reconstruct_bst.go @@ -1,5 +1,7 @@ package main +import "math" + // BST represents a binary search tree node. type BST struct { Value int @@ -7,6 +9,7 @@ type BST struct { Right *BST } +// Approach 1: Time complexity O(n^2) Space O(n), where n is length of input array // ReconstructBst takes a slice of integers representing the pre-order traversal of a BST and returns the reconstructed BST. func ReconstructBst(preOrderTraversalValues []int) *BST { // Base case: If the pre-order traversal is empty, return nil indicating an empty tree. @@ -34,3 +37,48 @@ func ReconstructBst(preOrderTraversalValues []int) *BST { // Create a new BST node with the current value and the reconstructed left and right subtrees. return &BST{Value: currentVal, Left: leftSubTree, Right: rightSubTree} } + + +// Approach 2: Time complexity O(n) Space O(n), where n is length of input array + +// treeInfo is a helper struct to keep track of the current root index during the reconstruction process. +type treeInfo struct { + rootIdx int +} + +// ReconstructBst takes a slice of integers representing the pre-order traversal of a BST and returns the reconstructed BST. +func ReconstructBst2(preOrderTraversalValues []int) *BST { + // Create a treeInfo struct to keep track of the current root index. + treeInfo := &treeInfo{rootIdx: 0} + + // Call the helper function to reconstruct the BST from the given range and return the result. + return reconstructBSTFromRange(math.MinInt32, math.MaxInt32, preOrderTraversalValues, treeInfo) +} + +// reconstructBSTFromRange reconstructs the BST recursively within the given range using the pre-order traversal values. +func reconstructBSTFromRange(lowerBound, upperBound int, preOrderTraversalValues []int, currentSubtreeInfo *treeInfo) *BST { + // Check if the root index has reached the end of the pre-order traversal values. If so, return nil indicating an empty subtree. + if currentSubtreeInfo.rootIdx == len(preOrderTraversalValues) { + return nil + } + + // Get the value of the current root from the pre-order traversal values. + rootValue := preOrderTraversalValues[currentSubtreeInfo.rootIdx] + + // Check if the root value is out of the valid range defined by the lower and upper bounds. If so, return nil indicating an invalid subtree. + if rootValue < lowerBound || rootValue >= upperBound { + return nil + } + + // Increment the root index to move to the next element in the pre-order traversal values. + currentSubtreeInfo.rootIdx++ + + // Recursively reconstruct the left subtree within the range (lowerBound, rootValue) using the updated root index. + leftSubtree := reconstructBSTFromRange(lowerBound, rootValue, preOrderTraversalValues, currentSubtreeInfo) + + // Recursively reconstruct the right subtree within the range (rootValue, upperBound) using the updated root index. + rightSubtree := reconstructBSTFromRange(rootValue, upperBound, preOrderTraversalValues, currentSubtreeInfo) + + // Create a new BST node with the current root value and the reconstructed left and right subtrees. + return &BST{Value: rootValue, Left: leftSubtree, Right: rightSubtree} +} From 3dff12a56736009e74a5aadb5d5178e9264d22cb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 15 May 2023 23:24:30 +0530 Subject: [PATCH 1095/1894] add explanation --- Trees/Binary Search Trees/reconstruct_bst.go | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Trees/Binary Search Trees/reconstruct_bst.go b/Trees/Binary Search Trees/reconstruct_bst.go index 0408f695..f1c7fc8a 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.go +++ b/Trees/Binary Search Trees/reconstruct_bst.go @@ -1,3 +1,59 @@ +/* + Explanation: + + Approach 1: + + The ReconstructBst function takes a slice preOrderTraversalValues which represents the pre-order traversal of a binary search tree. + It reconstructs the BST using a recursive approach. Here's how the algorithm works: + + The base case is defined when the preOrderTraversalValues slice is empty, in which case it returns nil indicating an empty tree. + + The first element in the preOrderTraversalValues slice represents the current node value of the BST. + + The algorithm finds the index (rightSubTreeRootIdx) where the right subtree starts by iterating over the remaining elements in + the preOrderTraversalValues slice and finding the first value greater than or equal to the current value. + + It recursively calls ReconstructBst on the sub-array representing the left subtree (preOrderTraversalValues[1:rightSubTreeRootIdx]) + to reconstruct the left subtree. + + It recursively calls ReconstructBst on the sub-array representing the right subtree (preOrderTraversalValues[rightSubTreeRootIdx:]) + to reconstruct the right subtree. + + Finally, it creates a new BST node with the current value, the reconstructed left subtree, and the reconstructed right subtree, + and returns the node. + + The algorithm builds the BST in a top-down manner by dividing the pre-order traversal values into left and right subtrees. + It constructs the left subtree first and then the right subtree. + + The time complexity of the algorithm is O(n^2) in the worst case, where n is the number of nodes in the BST. + + + ****************************************************************************************** + + Approach 2: + + The ReconstructBst function takes a slice preOrderTraversalValues which represents the pre-order traversal of a binary search tree. + It reconstructs the BST using a range-based approach. Here's how the algorithm works: + + The ReconstructBst function initializes a treeInfo struct to keep track of the current root index. + + The ReconstructBst function calls the reconstructBSTFromRange helper function, passing the minimum and maximum integer values + as the initial range, the pre-order traversal values, and the treeInfo struct. + + The reconstructBSTFromRange function first checks if the current root index has reached the end of the pre-order traversal values. + If so, it returns nil indicating an empty subtree. + + It retrieves the value of the current root from the pre-order traversal values. + + It checks if the root value is outside the valid range defined by the lower and upper bounds. If so, it returns + + The time complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function processes each node exactly once. + + The space complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function creates BST nodes and recursively calls itself to construct the left and right subtrees. + The space complexity is determined by the height of the BST, which can be at most n in the worst case for a skewed BST. +*/ package main import "math" From b035c25c58b513ff1813146900d8926aa32dcdd1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 15 May 2023 23:26:44 +0530 Subject: [PATCH 1096/1894] add question --- Trees/Binary Search Trees/reconstruct_bst.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Trees/Binary Search Trees/reconstruct_bst.go b/Trees/Binary Search Trees/reconstruct_bst.go index f1c7fc8a..d925f5de 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.go +++ b/Trees/Binary Search Trees/reconstruct_bst.go @@ -1,4 +1,15 @@ /* + Reconstruct BST + The pre-order traversal of a Binary Tree is a traversal technique that starts at the tree's root node and visits nodes in the following order: + Current Node + Left Subtree + Right Subtree + + Given a non-empty array of integers representing the pre-order traversal of a Binary Search Tree (BST), + write a function that creates the relevant BST and returns its root node. + + The input array will contain the values of BST nodes in the order in which these nodes would be visited with a pre-order traversal. + Explanation: Approach 1: From df20d2cab2a90bef973332f6ba2e6855bd989d04 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 15 May 2023 23:27:36 +0530 Subject: [PATCH 1097/1894] add sample io --- Trees/Binary Search Trees/reconstruct_bst.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Trees/Binary Search Trees/reconstruct_bst.go b/Trees/Binary Search Trees/reconstruct_bst.go index d925f5de..5a04820c 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.go +++ b/Trees/Binary Search Trees/reconstruct_bst.go @@ -10,6 +10,16 @@ The input array will contain the values of BST nodes in the order in which these nodes would be visited with a pre-order traversal. + Sample Input: [10, 4, 2, 1, 5, 17, 19, 18] + Sample Output: + 10 + / \ + 4 17 + / \ \ + 2 5 19 + / / +1 18 + Explanation: Approach 1: From 7121ff119d41137257b2805b59fdf47ca649609c Mon Sep 17 00:00:00 2001 From: Harsit Agarwalla <84774840+harsitagarwalla187@users.noreply.github.com> Date: Tue, 16 May 2023 12:35:41 +0530 Subject: [PATCH 1098/1894] Update Validate_BST.java --- Trees/Binary Search Trees/Validate_BST.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Trees/Binary Search Trees/Validate_BST.java b/Trees/Binary Search Trees/Validate_BST.java index 66066825..b81e23ed 100644 --- a/Trees/Binary Search Trees/Validate_BST.java +++ b/Trees/Binary Search Trees/Validate_BST.java @@ -3,7 +3,7 @@ // Additionally, the left and right subtrees themselves must also be valid BSTs. ////// Code: -class HelloWorld { +class validateBST { public static class Node { public int data; public Node left, right; @@ -23,19 +23,22 @@ static Boolean isBST(Node root) { if (root == null) return true; + //If Left Node is not BST then return false if (!isBST(root.left)) return false; + //Check if current node is less than its parent node if (prev != null && root.data <= prev.data) return false; - prev = root; + prev = root; return isBST(root.right); } public static void main(String[] args) { - Node root = new Node(1); + //Creating BST + Node root = new Node(1); root.left = new Node(-2); root.right = new Node(3); root.left.left = new Node(-4); @@ -53,4 +56,4 @@ public static void main(String[] args) { ////// Complexity: // Time Complexity: O(n) where n is number of nodes -// Space Complexity: O(1) \ No newline at end of file +// Space Complexity: O(1) From 03d45f6d65481fd6e186b2dd729a9f04584b30ae Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Tue, 16 May 2023 13:56:46 +0530 Subject: [PATCH 1099/1894] Update bucket_sort.java --- sorting/bucket_sort.java | 103 ++++++++++++++++++++++++--------------- 1 file changed, 64 insertions(+), 39 deletions(-) diff --git a/sorting/bucket_sort.java b/sorting/bucket_sort.java index b07b2a03..1a264ce7 100644 --- a/sorting/bucket_sort.java +++ b/sorting/bucket_sort.java @@ -1,42 +1,67 @@ -import java.util.ArrayList; +package util; + import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class BucketSort { + +static void bucketSort(int[] arr, int noOfBuckets) { + +boolean isNegativePresent = false; +int offset = Integer.MAX_VALUE; +for (int i : arr) { + if (i < offset) offset = i; + if (i < 0) isNegativePresent = true; +} + +int globalMax = Integer.MIN_VALUE; +int globalMin = Integer.MAX_VALUE; +for (int i = 0; i < arr.length; i++) { + arr[i] -= offset; + globalMin = Math.min(arr[i], globalMin); + globalMax = Math.max(arr[i], globalMax); +} + +int range = globalMax - globalMin; +int bucketRange = (int) Math.ceil((double) range / noOfBuckets); + +// Create bucket array +List[] buckets = new List[noOfBuckets]; + +// Associate a list with each index in the bucket array +for (int i = 0; i < noOfBuckets; i++) { + buckets[i] = new LinkedList<>(); +} + +// Assign numbers from array to the proper bucket +// by using hashing function +for (int num : arr) { + buckets[hash(num, bucketRange, noOfBuckets)].add(num); +} + +// sort buckets +for (List bucket : buckets) Collections.sort(bucket); + +int idx = 0; +// Merge buckets to get sorted array +for (List bucket : buckets) { + for (int num : bucket) { + arr[idx++] = num; + } +} + +if (isNegativePresent) { + for (int i = 0; i < arr.length; i++) { + arr[i] += offset; + } +} +} -public class Bucket_Sort { - public static void bucketSort(double[] arr) { - int n = arr.length; - ArrayList[] buckets = new ArrayList[n]; - - // Create empty buckets - for (int i = 0; i < n; i++) { - buckets[i] = new ArrayList<>(); - } - - // Add elements to corresponding buckets - for (int i = 0; i < n; i++) { - int bucketIndex = (int) (n * arr[i]); - buckets[bucketIndex].add(arr[i]); - } - - // Sort individual buckets - for (int i = 0; i < n; i++) { - Collections.sort(buckets[i]); - } - - // Concatenate all buckets - int index = 0; - for (int i = 0; i < n; i++) { - for (int j = 0; j < buckets[i].size(); j++) { - arr[index++] = buckets[i].get(j); - } - } - } - - public static void main(String[] args) { - double[] arr = {0.8, 0.3, 0.2, 0.9, 0.1, 0.6, 0.4, 0.7, 0.5, 0.0}; - bucketSort(arr); - System.out.println("Sorted array:"); - for (double d : arr) { - System.out.print(d + " "); - } - } +private static int hash(int num, int hashValue, int numberOfBuckets) { +int bucketNumber = num / hashValue; +if (bucketNumber == numberOfBuckets) +bucketNumber--; +return bucketNumber; } +} \ No newline at end of file From 93d51fc75a3a14ae303f8ef1f88cfebad9793b48 Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Tue, 16 May 2023 14:38:58 +0530 Subject: [PATCH 1100/1894] Update bucket_sort.java --- sorting/bucket_sort.java | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/sorting/bucket_sort.java b/sorting/bucket_sort.java index 1a264ce7..bd621847 100644 --- a/sorting/bucket_sort.java +++ b/sorting/bucket_sort.java @@ -1,5 +1,31 @@ -package util; +/* + +Here is a step by step process : +Set up an array of initially empty "buckets". +Scatter: Go over the original array, putting each object in its bucket. +Sort each non-empty bucket. +Gather: Visit the buckets in order and put all elements back into the original array. + +Bucket Sort time complexity +Best Case Time Complexity: O(n+k) +Average Case Time Complexity: O(n) +Worst Case Time Complexity: O(n^2^) +Best Case Time Complexity: +If the array elements are uniformly distributed, bucket size will almost be the same for all the buckets. Hence, this will be the best case which will take up the least amount of time. +Sorting time complexity will reduce even further if all the elements inside each bucket are already sorted. +To create n buckets and scatter each element from the array, time complexity = O(n). If we use Insertion sort to sort each bucket, time complexity = O(k). Hence, best case time complexity for bucket sort = O(n+k), where n = number of elements, and k = number of buckets +Worst Case Time Complexity +If the array elements are not uniformly distributed, i.e., elements are concentrated within specific ranges. +This will result in one or more buckets having more elements than other buckets, making bucket sort like any other sorting technique, where every element is compared to the other. Time complexity increases even further if the elements in the array are present in the reverse order. If insertion sort is used, the worst-case time complexity can go up to O(n^2^). + +Bucket Sort Space Complexity +Space Complexity : O(n+k) +Space Complexity for bucket sort is O(n+k), where n = number of elements in the array, and k = number of buckets formed Space taken by each bucket is O(k), and inside each bucket, we have n elements scattered. Hence, the space complexity becomes O(n+k). + +*/ + +package util; import java.util.Collections; import java.util.LinkedList; import java.util.List; From 9559b474f81674e79d2890119420c85eb1e2867b Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Tue, 16 May 2023 15:56:07 +0530 Subject: [PATCH 1101/1894] Knight_Probability_in_Chessboard using javascript --- .../Knight_Probability_in_Chessboard.js | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic Programming/Knight_Probability_in_Chessboard.js diff --git a/Dynamic Programming/Knight_Probability_in_Chessboard.js b/Dynamic Programming/Knight_Probability_in_Chessboard.js new file mode 100644 index 00000000..cff78471 --- /dev/null +++ b/Dynamic Programming/Knight_Probability_in_Chessboard.js @@ -0,0 +1,39 @@ +/*Time Complexity: The time complexity of the code is O(n^2 * k) because, in the calculateProbability function, we have a loop that iterates over each cell on the chessboard (n x n) and for each cell, we make recursive calls for k moves. So, the total number of iterations would be proportional to n^2 * k. +Space Complexity: The space complexity of the code is O(n^2 * k) because we use a 3D array dp to store the calculated probabilities for each cell and the number of moves. The size of this array is n x n x k, which requires space proportional to n^2 * k. +*/ + +var knightProbability = function(n, k, row, column) { + const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; + const dp = Array.from({ length: n }, () => Array.from({ length: n }, () => Array(k + 1).fill(0.0))); + // 3D array to store calculated probabilities + + const calculateProbability = (n, k, row, column) => { + // Base cases + if (row < 0 || row >= n || column < 0 || column >= n) { + return 0.0; // Knight is out of the chessboard + } + + if (k === 0) { + return 1.0; // Knight has made all the moves, so it remains on the board + } + + if (dp[row][column][k] > 0.0) { + return dp[row][column][k]; // Return already calculated probability + } + + let probability = 0.0; + + for (const knightMove of moves) { + const nextRow = row + knightMove[0]; + const nextColumn = column + knightMove[1]; + + probability += calculateProbability(n, k - 1, nextRow, nextColumn) / 8.0; // Recursively calculate probability for next moves + } + + dp[row][column][k] = probability; // Store the calculated probability + + return probability; + }; + + return calculateProbability(n, k, row, column); +}; From 349147be6a480c8b27bd064d599b4f1242952b19 Mon Sep 17 00:00:00 2001 From: rajeev Date: Tue, 16 May 2023 16:46:58 +0530 Subject: [PATCH 1102/1894] added Kadane's algorithm c++ --- Famous Algorithms/kadanes_algorithm.c++ | 76 +++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Famous Algorithms/kadanes_algorithm.c++ diff --git a/Famous Algorithms/kadanes_algorithm.c++ b/Famous Algorithms/kadanes_algorithm.c++ new file mode 100644 index 00000000..c6b6fbdb --- /dev/null +++ b/Famous Algorithms/kadanes_algorithm.c++ @@ -0,0 +1,76 @@ +/* Name : Rajeev Kumar +Github username : Tonystark121 +Repository name : data-structures-and-algorithms +Problem : Kadane's algorithm in C++ +Issue Number : #1179 +Problem statement : Given an integer array nums, find the subarray with the largest sum, and return its sum. + +Sample testcases: + +Testcase 1 --> + +Input: number of elements in array = 8 +nums = [-2,-3,5,-1,-2,1,5,-3] +Output: 8 + +Testcase 2 --> +Input: number of elements in array = 5 +nums = [5,4,-1,7,8] +Output: 23 + +Time Complexity = O(n) +Space Complexity = O(1) + + +Explanation: +This code asks the user to enter the number of elements in an array, +and then prompts them to enter each element of the array one at a time. +Once the array is complete, the code applies the Kadane's algorithm to +find the maximum sum of any subarray within the array, and then prints +the result to the console. + +Kadane's algorithm is a way of finding the maximum sum of a contiguous subarray within an array, +and it does so by keeping track of the maximum sum seen so far as it iterates through the array. +At each step, it adds the current element to a running sum, and if that sum becomes negative, +it resets the running sum to zero. If the running sum is ever greater than the maximum seen so far, +it updates the maximum. Finally, it returns the maximum sum. +*/ + +// ----------------------------------------------------------------------------- code begins now! + + +#include +using namespace std; + +int main(){ + + // taking input number of array elements. + int n; + cin>>n; + + // taking input array elements. + int arr[n]; + for(int i=0;i>arr[i]; + } + + // declare current maximum and maximum so far variable. + int curr_max=0,max_so_far=INT_MIN; + + for(int i=0;imax_so_far){ + max_so_far = curr_max; + } + } + + // output result. + cout< Date: Tue, 16 May 2023 19:45:58 +0530 Subject: [PATCH 1103/1894] square of a sorted array --- Arrays/squares_of_a_sorted_array.cpp | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Arrays/squares_of_a_sorted_array.cpp b/Arrays/squares_of_a_sorted_array.cpp index aed496b0..d61688d8 100644 --- a/Arrays/squares_of_a_sorted_array.cpp +++ b/Arrays/squares_of_a_sorted_array.cpp @@ -13,7 +13,7 @@ > nums is sorted in non-decreasing order. */ -class Solution { +/*class Solution { public: int N=10001; vector sortedSquares(vector& nums) { @@ -43,4 +43,27 @@ class Solution { // Return the final ans return ans; } -}; \ No newline at end of file +}; +*/ +class Solution { +public: + vector sortedSquares(vector& nums) { + int n = nums.size(); + vector res(n); // Create a vector to store the squared values + int left = 0, right = n - 1; // Initialize two pointers at the start and end of the array + + for (int i = n - 1; i >= 0; i--) { + if (abs(nums[left]) > abs(nums[right])) { + // If the absolute value of the number at the left pointer is greater than the absolute value of the number at the right pointer + res[i] = nums[left] * nums[left]; // Square the number at the left pointer and store it in the result array + left++; // Move the left pointer to the right + } else { + // If the absolute value of the number at the left pointer is less than or equal to the absolute value of the number at the right pointer + res[i] = nums[right] * nums[right]; // Square the number at the right pointer and store it in the result array + right--; // Move the right pointer to the left + } + } + + return res; // Return the result array + } +}; From 0a8ebefb6e461cd03749cf5d2c7d828fb1139db3 Mon Sep 17 00:00:00 2001 From: Harsit-Agarwalla Date: Tue, 16 May 2023 21:37:21 +0530 Subject: [PATCH 1104/1894] Add Validate BST in js and python --- Trees/Binary Search Trees/Validate_BST.js | 60 +++++++++++++++++++++++ Trees/Binary Search Trees/Validate_BST.py | 53 ++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 Trees/Binary Search Trees/Validate_BST.js create mode 100644 Trees/Binary Search Trees/Validate_BST.py diff --git a/Trees/Binary Search Trees/Validate_BST.js b/Trees/Binary Search Trees/Validate_BST.js new file mode 100644 index 00000000..3c068140 --- /dev/null +++ b/Trees/Binary Search Trees/Validate_BST.js @@ -0,0 +1,60 @@ +////// Explanation: +// To validate a Binary Search Tree (BST), we need to ensure that the values of nodes in the left subtree of any node are less than the value of the node, and the values of nodes in the right subtree are greater than the value of the node. +// Additionally, the left and right subtrees themselves must also be valid BSTs. + +////// Code: +class Node { + constructor(data) { + this.data = data; + this.left = null; + this.right = null; + } + } + + function isBST(root) { + let prev = null; + + function inorderTraversal(node) { + + // Base case + if (node === null) { + return true; + } + + // If left subtree is not BST return false + if (!inorderTraversal(node.left)) { + return false; + } + + // If current node is greater than parent node return false + if (prev !== null && node.data <= prev.data) { + return false; + } + + prev = node; + return inorderTraversal(node.right); + } + + return inorderTraversal(root); + } + + // Create the tree + const root = new Node(100); + root.left = new Node(-2); + root.right = new Node(3); + root.left.left = new Node(-4); + root.left.right = new Node(-1); + root.right.left = new Node(2); + root.right.right = new Node(7); + + // Function call + if (isBST(root)) { + console.log("Is Valid BST"); + } else { + console.log("Not a Valid BST"); + } + + +////// Complexity: +// Time Complexity: O(n) where n is number of nodes +// Space Complexity: O(1) \ No newline at end of file diff --git a/Trees/Binary Search Trees/Validate_BST.py b/Trees/Binary Search Trees/Validate_BST.py new file mode 100644 index 00000000..2ea6eb90 --- /dev/null +++ b/Trees/Binary Search Trees/Validate_BST.py @@ -0,0 +1,53 @@ +## Explanation: +# To validate a Binary Search Tree (BST), we need to ensure that the values of nodes in the left subtree of any node are less than the value of the node, and the values of nodes in the right subtree are greater than the value of the node. +# Additionally, the left and right subtrees themselves must also be valid BSTs. + +## Code: +class Node: + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +def is_bst(root): + global prev + prev = None + + def inorder_traversal(node): + global prev + if node is None: + return True + + // If left subtree is not BST return false + if not inorder_traversal(node.left): + return False + + // If current node is greater than parent node return false + if prev is not None and node.data <= prev.data: + return False + + prev = node + return inorder_traversal(node.right) + + return inorder_traversal(root) + + +# Create the tree +root = Node(1) +root.left = Node(-2) +root.right = Node(3) +root.left.left = Node(-4) +root.left.right = Node(-1) +root.right.left = Node(2) +root.right.right = Node(7) + +# Function call +if is_bst(root): + print("Is Valid BST") +else: + print("Not a Valid BST") + +## Complexity: +# Time Complexity: O(n) where n is number of nodes +# Space Complexity: O(1) \ No newline at end of file From 11c61de2e9460d9c02deb4f115d76ab446e88ddb Mon Sep 17 00:00:00 2001 From: Aneesh Date: Wed, 17 May 2023 09:21:43 +0530 Subject: [PATCH 1105/1894] doubly_linked_list.cpp --- Linked List/doubly_linked_list.cpp | 114 +++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 Linked List/doubly_linked_list.cpp diff --git a/Linked List/doubly_linked_list.cpp b/Linked List/doubly_linked_list.cpp new file mode 100644 index 00000000..7be71cd7 --- /dev/null +++ b/Linked List/doubly_linked_list.cpp @@ -0,0 +1,114 @@ +/* Name : Aneesh +Github username : 007aneesh +Repository name : data-structures-and-algorithms + +Problem : Doubly linked list in c++ +Issue Number : #975 +Problem statement : Given an integer n representing the length of linked list and you have to print linked list from start and end. + +Sample testcases: + +Testcase 1 --> + +Input: +5 +1 2 3 4 5 + +Output: +Printing forwardly................................ +1 +2 +3 +4 +5 +Printing backwardly................................ +5 +4 +3 +2 +1 + + +Testcase 2 --> +Input: +3 +10 20 30 + +Output: +Printing forwardly................................ +10 +20 +30 +Printing backwardly................................ +30 +20 +10 + + + +Time Complexity = O(n) +Space Complexity = O(n) + + +Explanation: +In the main function, the program first takes input n, +the number of nodes to be inserted in the linked list. +Then, in a loop, it takes n values as input and creates new nodes with those values. +The nodes are then linked together to form a doubly linked list. +Finally, it calls the PrintForward and PrintBackward functions +to print the elements of the list in forward and backward order, respectively. +*/ + +// ----------------------------------------------------------------------------- code begins now! + +#include +using namespace std; +class Node{ + public: + int data; + Node* next; + Node* prev; + Node(int d){ + this->data = d; + next = NULL; + prev = NULL; + } +}; +void PrintForward(Node* head){ + Node* traverse = head; + while(traverse!=NULL){ + cout<data<next; + } +} +void PrintBackward(Node* tail){ + Node* traverse = tail; + while(tail!=NULL){ + cout<data<prev; + } +} +int main(){ + int n, value; + cin>>n; + Node *head = nullptr; + Node *tail = nullptr; + for(int i=0; i>value; + Node *newNode = new Node(value); + if(head == NULL){ + head = newNode; + tail = newNode; + }else{ + newNode->next = nullptr; + newNode->prev = tail; + tail->next = newNode; + tail = newNode; + } + } + cout<<"Printing forwardly................................"< Date: Wed, 17 May 2023 09:34:41 +0530 Subject: [PATCH 1106/1894] Update bucket_sort_implementation.cpp --- sorting/bucket_sort_implementation.cpp | 124 +++++++++++-------------- 1 file changed, 56 insertions(+), 68 deletions(-) diff --git a/sorting/bucket_sort_implementation.cpp b/sorting/bucket_sort_implementation.cpp index 725e7554..bbdcb8a7 100644 --- a/sorting/bucket_sort_implementation.cpp +++ b/sorting/bucket_sort_implementation.cpp @@ -1,78 +1,66 @@ /* - Bucket-Sort can be used to sort a set of uniformly distributed floating point numbers. - Input: [0.872, 0.435, 0.516, 0.1004, 0.1065, 0.3464] - Output: [0.1004, 0.1065, 0.3464, 0.435, 0.516, 0.872] - - Input: [9.81, 9.6, 1.1, 1.9, 5.07,5.04, 3.0, 11.11, 0.18, 6.78] - Output: [0.18, 1.1, 1.9, 3, 5.04, 5.07, 6.78, 9.6, 9.81, 11.11 ] +Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem. +Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently? +A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn. +Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers. +The idea is to use bucket sort. Following is bucket algorithm. +bucketSort(arr[], n) +1) Create n empty buckets (Or lists). +2) Do following for every array element arr[i]. +.......a) Insert arr[i] into bucket[n*array[i]] +3) Sort individual buckets using insertion sort. +4) Concatenate all sorted buckets. - APPROACH - 1. Create N buckets. - 2. Calculate the range of floating points using the formula: - RANGE = (MAX_ELEMENT - MIN_ELEMENT)/ N - 3. Calculate bucket index for current element using the following formula: - BUCKET_INDX = (CURR_ELEMENT - MIN_ELEMENT)/RANGE - 4. If BUCKET_INDX is an integer i.e its floating part==0.00 and its is not equal to MIN_ELEMENT, update BUCKET_INDX as follows: - BUCKET_INDX = BUCKET_INDX - 1 - 5. Insert CURR_ELEMENT the bucket as per BUCKET_INDX - 6. Sort each bucket individually. - 7. Concatenate all sorted buckets and return concatenated list as answer. - TIME COMPLEXITY: O(N) - SPACE COMPLEXITY: O(N) + + //TIME COMPLEXITY: O(N) + //SPACE COMPLEXITY: O(N) */ -#include -using namespace std; -void bucketSort(vector& nums) +// C++ program to sort an +// array using bucket sort +#include +#include +#include +using namespace std; + +// Function to sort arr[] of +// size n using bucket sort +void bucketSort(float arr[], int n) { - // Intialize variables we will be needing later - int N=nums.size(); - double max_ele = *max_element(nums.begin(), nums.end()); - double min_ele = *min_element(nums.begin(), nums.end()); - double range = (max_ele - min_ele)/N; - vector buckets[N]; - - // Insert elements into their correct buckets by calculating bucket indexes - for(int i=0;i b[n]; + + // 2) Put array elements + // in different buckets + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; } -int main(){ - -vector nums1={0.872, 0.435, 0.516, 0.1004, 0.1065, 0.3464}; -bucketSort(nums1); -for(auto i:nums1) cout< nums2={ 9.81, 9.6, 1.1, 1.9, 5.07,5.04, 3.0, 11.11, 0.18, 6.78}; -bucketSort(nums2); -cout<<"\n"; -for(auto i:nums2) cout< Date: Wed, 17 May 2023 09:55:06 +0530 Subject: [PATCH 1107/1894] Create floydsCycleDetection.ccp --- Linked List/floydsCycleDetection.ccp | 94 ++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Linked List/floydsCycleDetection.ccp diff --git a/Linked List/floydsCycleDetection.ccp b/Linked List/floydsCycleDetection.ccp new file mode 100644 index 00000000..8bf36396 --- /dev/null +++ b/Linked List/floydsCycleDetection.ccp @@ -0,0 +1,94 @@ +/* + +Initialize two-pointers and start traversing the linked list. +Move the slow pointer by one position. +Move the fast pointer by two positions. +If both pointers meet at some point then a loop exists and if the fast pointer meets the end position then no loop exists. + + +Time complexity: O(n), as the loop is traversed once. +Auxiliary Space: O(1), only two pointers are used therefore constant space complexity. + +*/ + + +#include +using namespace std; + +class Node { +public: + int data; + Node* next; + + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +// initialize a new head for the linked list +Node* head = NULL; +class Linkedlist { +public: + // insert new value at the start + void insert(int value) + { + Node* newNode = new Node(value); + if (head == NULL) + head = newNode; + else { + newNode->next = head; + head = newNode; + } + } + + // detect if there is a loop + // in the linked list + bool detectLoop() + { + Node *slowPointer = head, + *fastPointer = head; + + while (slowPointer != NULL + && fastPointer != NULL + && fastPointer->next != NULL) { + slowPointer = slowPointer->next; + fastPointer = fastPointer->next->next; + if (slowPointer == fastPointer) + return 1; + } + + return 0; + } +}; + +int main() +{ + Linkedlist l1; + // inserting new values + l1.insert(10); + l1.insert(20); + l1.insert(30); + l1.insert(40); + l1.insert(50); + + // adding a loop for the sake + // of this example + Node* temp = head; + while (temp->next != NULL) + temp = temp->next; + + temp->next = head; + + // loop added; + + if (l1.detectLoop()) + cout << "Loop exists in the" + << " Linked List" << endl; + else + cout << "Loop does not exists " + << "in the Linked List" << endl; + + return 0; +} \ No newline at end of file From 8dee18e01d70b5956ca6b6d25b123e2a67607e07 Mon Sep 17 00:00:00 2001 From: Aneesh Date: Wed, 17 May 2023 09:59:34 +0530 Subject: [PATCH 1108/1894] updated double linked_list.cpp --- Linked List/doubly_linked_list.cpp | 63 +++++++++++++++++++----------- 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/Linked List/doubly_linked_list.cpp b/Linked List/doubly_linked_list.cpp index 7be71cd7..c8cd3a15 100644 --- a/Linked List/doubly_linked_list.cpp +++ b/Linked List/doubly_linked_list.cpp @@ -63,52 +63,69 @@ to print the elements of the list in forward and backward order, respectively. #include using namespace std; -class Node{ - public: + +// Define a Node class +class Node { +public: int data; Node* next; Node* prev; - Node(int d){ + Node(int d) { this->data = d; next = NULL; prev = NULL; } }; -void PrintForward(Node* head){ + +// Function to print the linked list forward +void PrintForward(Node* head) { Node* traverse = head; - while(traverse!=NULL){ - cout<data<next; + while (traverse != NULL) { + cout << traverse->data << endl; + traverse = traverse->next; } } -void PrintBackward(Node* tail){ + +// Function to print the linked list backward +void PrintBackward(Node* tail) { Node* traverse = tail; - while(tail!=NULL){ - cout<data<prev; + while (tail != NULL) { + cout << traverse->data << endl; + traverse = traverse->prev; } } -int main(){ + +int main() { int n, value; - cin>>n; - Node *head = nullptr; - Node *tail = nullptr; - for(int i=0; i>value; - Node *newNode = new Node(value); - if(head == NULL){ + cin>>n; // Read the number of nodes to be created + Node *head = nullptr; // Initialize head pointer + Node *tail = nullptr; // Initialize tail pointer + + // Read 'n' values and create a doubly linked list + for (int i = 0; i < n; i++) { + cin >> value; // Read the value for the current node + Node* newNode = new Node(value); // Create a new node with the value + + // If the list is empty, set the head and tail to the new node + if (head == NULL) { head = newNode; tail = newNode; - }else{ + } else { + // Add the new node to the end of the list newNode->next = nullptr; newNode->prev = tail; tail->next = newNode; tail = newNode; } } - cout<<"Printing forwardly................................"< Date: Wed, 17 May 2023 10:08:45 +0530 Subject: [PATCH 1109/1894] Update floydsCycleDetection.ccp --- Linked List/floydsCycleDetection.ccp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Linked List/floydsCycleDetection.ccp b/Linked List/floydsCycleDetection.ccp index 8bf36396..94868fa5 100644 --- a/Linked List/floydsCycleDetection.ccp +++ b/Linked List/floydsCycleDetection.ccp @@ -14,7 +14,7 @@ Auxiliary Space: O(1), only two pointers are used therefore constant space compl #include using namespace std; - + class Node { public: int data; From 0543aac32dfa180c922161dcf6f9e4e96f6174f8 Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Wed, 17 May 2023 10:19:31 +0530 Subject: [PATCH 1110/1894] Create floydsCycleDetection.java --- Linked List/floydsCycleDetection.java | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Linked List/floydsCycleDetection.java diff --git a/Linked List/floydsCycleDetection.java b/Linked List/floydsCycleDetection.java new file mode 100644 index 00000000..5868baf1 --- /dev/null +++ b/Linked List/floydsCycleDetection.java @@ -0,0 +1,93 @@ +/* + +Initialize two-pointers and start traversing the linked list. +Move the slow pointer by one position. +Move the fast pointer by two positions. +If both pointers meet at some point then a loop exists and if the fast pointer meets the end position then no loop exists. + + +Time complexity: O(n), as the loop is traversed once. +Auxiliary Space: O(1), only two pointers are used therefore constant space complexity. + +*/ + + +import java.util.*; + +class GFG{ + +static class Node { + int data; + Node next; + + Node(int data) + { + this.data = data; + next = null; + } +}; + +// initialize a new head for the linked list +static Node head = null; +static class Linkedlist { + // insert new value at the start + void insert(int value) + { + Node newNode = new Node(value); + if (head == null) + head = newNode; + else { + newNode.next = head; + head = newNode; + } + } + + // detect if there is a loop + // in the linked list + boolean detectLoop() + { + Node slowPointer = head, + fastPointer = head; + + while (slowPointer != null + && fastPointer != null + && fastPointer.next != null) { + slowPointer = slowPointer.next; + fastPointer = fastPointer.next.next; + if (slowPointer == fastPointer) + return true; + } + + return false; + } +} + +public static void main(String[] args) +{ + Linkedlist l1 = new Linkedlist(); + // inserting new values + l1.insert(10); + l1.insert(20); + l1.insert(30); + l1.insert(40); + l1.insert(50); + + // adding a loop for the sake + // of this example + Node temp = head; + while (temp.next != null) + temp = temp.next; + + temp.next = head; + + // loop added; + + if (l1.detectLoop()) + System.out.print("Loop exists in the" + + " Linked List" +"\n"); + else + System.out.print("Loop does not exists " + + "in the Linked List" +"\n"); + +} +} \ No newline at end of file From 7a1c4a9576ed32613874df93f0ed11fe0574506b Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Wed, 17 May 2023 10:27:04 +0530 Subject: [PATCH 1111/1894] Create searchIn2DSortedArray.ccp --- 2D Arrays (Matrix)/searchIn2DSortedArray.ccp | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2D Arrays (Matrix)/searchIn2DSortedArray.ccp diff --git a/2D Arrays (Matrix)/searchIn2DSortedArray.ccp b/2D Arrays (Matrix)/searchIn2DSortedArray.ccp new file mode 100644 index 00000000..f977c55f --- /dev/null +++ b/2D Arrays (Matrix)/searchIn2DSortedArray.ccp @@ -0,0 +1,55 @@ +/* + +Follow the given steps to solve the problem: + +Run a nested loop, outer loop for the row, and inner loop for the column +Check every element with x and if the element is found then print “element found” +If the element is not found, then print “element not found” + +Time Complexity: O(N2) +Auxiliary Space: O(1), since no extra space has been taken. + +*/ + +#include + +using namespace std; + +/* Searches the element x in mat[][]. If the +element is found, then prints its position +and returns true, otherwise prints "not found" +and returns false */ +int search(int mat[4][4], int n, int x) +{ + if (n == 0) + return -1; + + // traverse through the matrix + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + // if the element is found + if (mat[i][j] == x) { + cout << "Element found at (" << i << ", " + << j << ")\n"; + return 1; + } + } + + cout << "n Element not found"; + return 0; +} + +// Driver code +int main() +{ + int mat[4][4] = { { 10, 20, 30, 40 }, + { 15, 25, 35, 45 }, + { 27, 29, 37, 48 }, + { 32, 33, 39, 50 } }; + + // Function call + search(mat, 4, 29); + + return 0; +} + \ No newline at end of file From ec81ad65fcaf49611cfdea6fc6937dc5935e4043 Mon Sep 17 00:00:00 2001 From: abhishek nayak Date: Wed, 17 May 2023 12:12:48 +0530 Subject: [PATCH 1112/1894] Added java solution to remove kth node from end of linkedlist --- Linked List/RemoveKthNodeFromEnd.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Linked List/RemoveKthNodeFromEnd.java diff --git a/Linked List/RemoveKthNodeFromEnd.java b/Linked List/RemoveKthNodeFromEnd.java new file mode 100644 index 00000000..e69de29b From c2fa8406560fd3a0c107c23e0f48025f382419b5 Mon Sep 17 00:00:00 2001 From: rajeev Date: Wed, 17 May 2023 13:07:53 +0530 Subject: [PATCH 1113/1894] searching in 2D Sorted matrix --- .../searching_in_2DSorted_Array.cpp | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp diff --git a/2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp b/2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp new file mode 100644 index 00000000..c2c3d350 --- /dev/null +++ b/2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp @@ -0,0 +1,92 @@ +/* Name : Rajeev Kumar +Github username : Tonystart121 +Repository name : data-structures-and-algorithms +Problem : Searching in 2D sorted array in C++ +Issue Number : #273 +Problem statement : Given a sorted matrix mat[n][m] and an element ‘x’. Find the position of x in the matrix if it is present, else print -1. + +Sample testcases: + +Testcase 1 --> + +Input: number of rows(n) and column(m).Let n=3,m=3 and value to search x = 20 . +arr[n][m] = { {1, 5, 9}, + {14, 20, 21}, + {30, 34, 43} } + +Output: found at (1,2); + +Testcase 2 --> +Input: number of rows(n) and column(m).Let n=3,m=4 and value to search x = 43 +arr[n][m] = { {1, 5, 9, 11}, + {14, 20, 21, 26}, + {30, 34, 43, 50} } +Output: Found at (2,3); + +Time Complexity = O(n+m) +Space Complexity = O(n+m) + + +Explanation: +This code asks the user to enter the number of rows and column in the array and element to find in the array, and then prompts them to enter each element of the array one at a time. Once the array is complete, the code applies the linear search/mapping algorithm to find the element within the array, and then prints the position of that element to the console. + +Start at the top left corner of the matrix. +Compare the target element to the element at the current position. +If the target element is equal to the element at the current position, then return the current position. +If the target element is less than the element at the current position, then move down one row. +If the target element is greater than the element at the current position, then move right one column. +Repeat steps 2-5 until the target element is found or the entire matrix has been searched. +*/ + +// ----------------------------------------------------------------------------- code begins now! + + +#include +using namespace std; + +int main(){ + + // enter array rows and column + int n,m; + cin>>n>>m; + + // taking input array. + int arr[n][m]; + for(int i=0;i>arr[i][j]; + } + } + + // taking input value to search. + int key; + cin>>key; + + // initializing rightmost element as current element. + int cr_row = 0, cr_col=m-1; + bool ans = false; + while(cr_row=0){ + + // if key==curr output its position + if(arr[cr_row][cr_col]==key){ + cout<arr[cr_row][cr_col]){ + cr_row++; + } + + // if key less than array elements, col decreasing. + else if(key Date: Wed, 17 May 2023 13:50:29 +0530 Subject: [PATCH 1114/1894] solution added --- Linked List/RemoveKthNodeFromEnd.java | 102 ++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/Linked List/RemoveKthNodeFromEnd.java b/Linked List/RemoveKthNodeFromEnd.java index e69de29b..de390c23 100644 --- a/Linked List/RemoveKthNodeFromEnd.java +++ b/Linked List/RemoveKthNodeFromEnd.java @@ -0,0 +1,102 @@ +//Problem Number : 19 - Leetcode + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ + +/* + * Problem Description : + * Given the head of a linked list, remove the nth node + * from the end of the list and return its head. + * + * linkedlist = 1 -> 2 -> 3 -> 4 -> 5-> null + * n = 2 + */ + +/* + * Approach we follow to solve this Problem. + * Given : head of linkedlist and n = number of node to remove from end + * Solution : + * => Since we have to remove node from end , we need to calculate length of + * linkedlist. + * To do so lets create a function calcLength() , it take head node as parameter + * and return length of linked list . + * => Store the length of linkedlist in variable namely (len) by calling + * function calcLength(). + * => To make it simple , lets calculate position of node from start of + * linkedlist by subtracting length of node with nth node to remove. + * and store the result in another variable called target. [ target = len - n] + * => Now, we check for target == 0 and if its true than we have to remove our + * head and point the head to next element . + * for ex : head.next = head + * After just return our head because we have no need to check other part. + * => create a pointer = 1 and store head of LikedList to temp variable . + * => After that , we have to iterate over linkedlist till our temp is not equal + * to null to find our target element. + * (Note : target element is always prev of node of node to remove for ex : 1-> 2-> 3->4-> 5 + * In this case 3 is our target because we have to remove 4.) + * => for each iteration , we check if our target == pointer , In case its true + * the we have to handle two case : + * Case 1 : if our target node is last node of linked list ,then point temp to + * null + * explanation : 1-> 2-> 3-> 4-> 5 -> null + * if our target is 5 the our new linkedlist will we like this : 1-> 2-> 3-> 4-> + * null + * Case 2 : Target is in middle of linkedlist then , update temp pointer to + * temp.next.next + * explanation : 1-> 2-> 3-> 4-> 5 -> null + * let say we have to remove 3 : then temp = 2 + * temp.next = 3 : node to remove + * temp.next.next = 4 + * output : 1-> 2-> 4-> 5 -> null + * => increment pointer and update temp to next node. + * => In last just return node + */ + +class Solution { + + public int calcLength(ListNode head) { + int cnt = 0; + while (head != null) { + cnt++; + head = head.next; + } + return cnt; + } + + public ListNode removeNthFromEnd(ListNode head, int n) { + + int len = calcLength(head); + int target = len - n; + if (target == 0) { + head = head.next; + return head; + } + int pointer = 1; + + ListNode temp = head; + while (temp != null) { + if (pointer == target) { + ListNode key = temp.next; + if (key == null) { + temp = null; + } else { + temp.next = key.next; + } + + } + pointer++; + temp = temp.next; + } + + return head; + + } +} \ No newline at end of file From d4db4eb1f87e3dd136fafed73326d81aca24c05f Mon Sep 17 00:00:00 2001 From: Arpitshivam Pandey <98251986+Arpit0324@users.noreply.github.com> Date: Wed, 17 May 2023 17:13:26 +0530 Subject: [PATCH 1115/1894] Create Implement Queue using Stacks.cpp --- Stacks/Implement Queue using Stacks.cpp | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Stacks/Implement Queue using Stacks.cpp diff --git a/Stacks/Implement Queue using Stacks.cpp b/Stacks/Implement Queue using Stacks.cpp new file mode 100644 index 00000000..e1c2d22d --- /dev/null +++ b/Stacks/Implement Queue using Stacks.cpp @@ -0,0 +1,37 @@ +/* The basic difference in stack and queues is the order they are filled in practically.In Stacks, +they are inserted on top of previous element while In Queues they are inserted behind the last element. +The push() function is what we have to look out for. First we will empty out our primary stack s1 to another stack s2. +Then We push the element to be inserted x in s1(or s2). +Then just empty out the stack s2 back into s1. But the element x would be at the last place just like in a Queue. +The other Operations are the same as we have already implemented as a queue.*/ + + + +class MyQueue { +private: + stack s1,s2; +public: + MyQueue() { + } + void push(int x) { + s1.push(x); + } + int pop() { + int res = peek(); + s2.pop(); + return res; + } + int peek() { + if(s2.empty()){ + while(!s1.empty()){ + s2.push(s1.top()); + s1.pop(); + } + } + int res = s2.top(); + return res; + } + bool empty() { + return s1.empty()&&s2.empty(); + } +}; From 59a219a60e9736f69342144f04484d40a30e18cb Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Wed, 17 May 2023 17:50:22 +0530 Subject: [PATCH 1116/1894] Add files via upload We start by initializing the dimensions of the input matrix mat as m (number of rows) and n (number of columns). This will be used later in the code. We create a result matrix called result of size m x n to store the distance of the nearest 0 for each cell. Initially, we set all the values in result to a large value (in this case, INT_MAX) to represent an unreachable distance. We create a queue called q to store the cell indices that need to be processed during the breadth-first search. We iterate through the input matrix mat and enqueue the indices of all the cells with value 0 into the queue. Additionally, we mark the distance of these cells in the result matrix as 0. This initialization step ensures that the cells with value 0 are considered as starting points for the breadth-first search. Now, we perform the breadth-first search using the queue q. While the queue is not empty, we process the cells in a breadth-first manner. For each cell (row, col) popped from the queue, we check its neighboring cells in four directions: up, down, left, and right. We define the directions as a vector of pairs called directions, where each pair represents the change in row and column indices to move in a specific direction. If the neighboring cell indices (newRow, newCol) are within the valid range of the matrix and the current distance in the result matrix for (newRow, newCol) is greater than the distance of the current cell plus 1, we update the distance in the result matrix and enqueue the neighboring cell (newRow, newCol) into the queue for further processing. Once the breadth-first search is completed, the result matrix will contain the distance of the nearest 0 for each cell in the input matrix. Finally, we return the result matrix. --- Dynamic Programming/distance_of_nearest_0.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Dynamic Programming/distance_of_nearest_0.cpp diff --git a/Dynamic Programming/distance_of_nearest_0.cpp b/Dynamic Programming/distance_of_nearest_0.cpp new file mode 100644 index 00000000..e272b663 --- /dev/null +++ b/Dynamic Programming/distance_of_nearest_0.cpp @@ -0,0 +1,81 @@ +#include +#include +#include + +using namespace std; + +class Solution +{ +public: + vector> updateMatrix(vector> &mat) + { + int m = mat.size(); + int n = mat[0].size(); + + // Create a result matrix and initialize with large values + vector> result(m, vector(n, INT_MAX)); + + // Create a queue to store cell indices + queue> q; + + // Initialize the queue with 0 cells and mark their distance as 0 + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (mat[i][j] == 0) + { + result[i][j] = 0; + q.push({i, j}); + } + } + } + + // Perform breadth-first search + vector> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + while (!q.empty()) + { + int row = q.front().first; + int col = q.front().second; + q.pop(); + + for (const auto &dir : directions) + { + int newRow = row + dir.first; + int newCol = col + dir.second; + + if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n) + { + if (result[newRow][newCol] > result[row][col] + 1) + { + result[newRow][newCol] = result[row][col] + 1; + q.push({newRow, newCol}); + } + } + } + } + + return result; + } +}; + +int main() +{ + // Example usage + vector> mat = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}; + + Solution s; + vector> result = s.updateMatrix(mat); + + // Print the result + for (const auto &row : result) + { + for (int val : row) + { + cout << val << " "; + } + cout << endl; + } + + return 0; +} From 3ec674eff504a8c7e527e25156d343c076757580 Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Wed, 17 May 2023 12:45:42 +0000 Subject: [PATCH 1117/1894] close --- Dynamic Programming/distance_of_nearest_0.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Dynamic Programming/distance_of_nearest_0.cpp b/Dynamic Programming/distance_of_nearest_0.cpp index e272b663..9c6465fd 100644 --- a/Dynamic Programming/distance_of_nearest_0.cpp +++ b/Dynamic Programming/distance_of_nearest_0.cpp @@ -1,3 +1,55 @@ +/*Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + + + +Example 1: + + +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +Example 2: + + +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] + + +Constraints: + +m == mat.length +n == mat[i].length +1 <= m, n <= 104 +1 <= m * n <= 104 +mat[i][j] is either 0 or 1. +There is at least one 0 in mat. + + +explanation: + +stepwise explanation of the code: + +1. We start by initializing the dimensions of the input matrix mat as m (number of rows) and n (number of columns). This will be used later in the code. + +2. We create a result matrix called result of size m x n to store the distance of the nearest 0 for each cell. Initially, we set all the values in result to a large value (in this case, INT_MAX) to represent an unreachable distance. + +3. We create a queue called q to store the cell indices that need to be processed during the breadth-first search. + +4. We iterate through the input matrix mat and enqueue the indices of all the cells with value 0 into the queue. Additionally, we mark the distance of these cells in the result matrix as 0. This initialization step ensures that the cells with value 0 are considered as starting points for the breadth-first search. + +5. Now, we perform the breadth-first search using the queue q. While the queue is not empty, we process the cells in a breadth-first manner. + +6. For each cell (row, col) popped from the queue, we check its neighboring cells in four directions: up, down, left, and right. We define the directions as a vector of pairs called directions, where each pair represents the change in row and column indices to move in a specific direction. + +7. If the neighboring cell indices (newRow, newCol) are within the valid range of the matrix and the current distance in the result matrix for (newRow, newCol) is greater than the distance of the current cell plus 1, we update the distance in the result matrix and enqueue the neighboring cell (newRow, newCol) into the queue for further processing. + +8. Once the breadth-first search is completed, the result matrix will contain the distance of the nearest 0 for each cell in the input matrix. + +9. Finally, we return the result matrix. + +*/ + #include #include #include From d41aca0efbd6dfc6ecb5429c9accad5126e0aaf1 Mon Sep 17 00:00:00 2001 From: Arpitshivam Pandey <98251986+Arpit0324@users.noreply.github.com> Date: Wed, 17 May 2023 19:31:35 +0530 Subject: [PATCH 1118/1894] Implement Queue using Stacks.cpp Added comment Along side of code --- Stacks/Implement Queue using Stacks.cpp | 96 ++++++++++++++++++------- 1 file changed, 69 insertions(+), 27 deletions(-) diff --git a/Stacks/Implement Queue using Stacks.cpp b/Stacks/Implement Queue using Stacks.cpp index e1c2d22d..b3335e03 100644 --- a/Stacks/Implement Queue using Stacks.cpp +++ b/Stacks/Implement Queue using Stacks.cpp @@ -6,32 +6,74 @@ Then just empty out the stack s2 back into s1. But the element x would be at the The other Operations are the same as we have already implemented as a queue.*/ +/*Complexity Analysis: -class MyQueue { -private: - stack s1,s2; -public: - MyQueue() { - } - void push(int x) { - s1.push(x); - } - int pop() { - int res = peek(); - s2.pop(); - return res; - } - int peek() { - if(s2.empty()){ - while(!s1.empty()){ - s2.push(s1.top()); - s1.pop(); - } - } - int res = s2.top(); - return res; - } - bool empty() { - return s1.empty()&&s2.empty(); - } +Time Complexity: +Push operation : O(1). +Same as pop operation in stack. +Pop operation : O(N). +The difference from above method is that in this method element is returned and all elements are restored back in a single call. +Auxiliary Space: O(N). +Use of stack for storing values. +*/ + + +#include +using namespace std; + +struct Queue { + stack s; + + // Enqueue an item to the queue + void enQueue(int x) + { + s.push(x); + } + + // Dequeue an item from the queue + int deQueue() + { + if (s.empty()) { + cout << "Q is empty"; + exit(0); + } + + // pop an item from the stack + int x = s.top(); + s.pop(); + + // if stack becomes empty, return + // the popped item + if (s.empty()) + return x; + + // recursive call + int item = deQueue(); + + // push popped item back to the stack + s.push(x); + + // return the result of deQueue() call + return item; + } }; + +// Driver code +int main() +{ + Queue q; + q.enQueue(10); + q.enQueue(20); + q.enQueue(30); + + cout << q.deQueue() << '\n'; + cout << q.deQueue() << '\n'; + cout << q.deQueue() << '\n'; + + return 0; +} + + + + + From 4bd9c5f2fc1518827f2c1a7ecc67661ed1527617 Mon Sep 17 00:00:00 2001 From: Niraj Date: Wed, 17 May 2023 21:46:53 +0530 Subject: [PATCH 1119/1894] #1010 Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area --- .../Largest_Rectangle_In_Binary_Matrix.java | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java new file mode 100644 index 00000000..899e0787 --- /dev/null +++ b/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java @@ -0,0 +1,89 @@ +//Program Author : TheCodeVenturer [Niraj Modi] +/* + Problem Definition: + Dynamic Programming: Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area in Python + Approach: + This Problem can be termed as updated version of Largest Rectangle in Histogram + If you are given a binary matrix then you can use no.of rows together with one as height + Like + 0 1 1 0 + 1 1 1 1 + 1 1 1 1 + 1 1 0 0 + If you can Visualise then it will be clear that for + first row the histogram row is like [0,1,1,0] + second row the histogram row is like [1,2,2,1] + third row the histogram row is like [2,3,3,2] + fourth row the histogram row is like [3,4,0,0] + then by using a monotonic stack for each row we can get The Largest Rectangle in the Binary Matrix + + we are taking here a row list which keeps track of current height of a particular column . Here, ShiftRow + we are also using a solution variable to keep track of largest rectangle + then first we will iterate through each row + and inside each iteration we will go and look for the particular element of that row matrix[i][j] + if it is 1 then will increase size of jth entry in the shiftRow else will convert it to zero + next will initialize an empty Stack [Monotonic] + next we will iterate through the shiftRow and will first check for the list is not empty and (it's top element is greater than or equal to current element or value of current column is equal to row size) + then will store it's height from the current row array and will update width of the rectangle with stack's top element and will finally update the sol + and will insert the element to the stack + Complexity: + Time Complexity: O(rows * col) for for traversing through each elements of the array + Here in each iteration we are doint three times O(n) => O(3n) ~ O(n) + Space Complexity: O(n) for the shiftRow and O(n) for the stack we are using => O(2n) ~ O(n) + Sample input/outputs: + Example 1: + Input: [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]] + Output: 8 + + Example 2: + Input: [[0,1,1],[1,1,1],[0,1,1]] + Output: 6 +*/ +import java.util.*; + +public class Solution { + public static int maxArea(int[][] matrix, int rows, int cols) { + int[] shiftRow = new int[cols]; // initializing the row which updates after each iteration + int sol = 0; + + for (int[] row : matrix) { + for (int i = 0; i < row.length; i++) { + // Updating the shiftRow if the value of ele is 1 => shiftRow[i] <- shiftRow[i] + 1 + // else shiftRow[i] = 0 + int ele = row[i]; + if (ele == 1) shiftRow[i]++; + else shiftRow[i] = 0; + } + + Deque stack = new ArrayDeque<>(); + + for (int i = 0; i < cols + 1; i++) { + while (!stack.isEmpty() && (i == cols || shiftRow[stack.peek()] >= shiftRow[i])) { + // checking TOS (top of stack) stack.length - 1 + int height = shiftRow[stack.peek()]; // for getting the height of the current index + stack.pop(); + int width = i; // setting width to i as it is only smallest from the beginning + if (!stack.isEmpty()) width = i - stack.peek() - 1; // updating width if the stack is not empty as it is not the smallest element + sol = Math.max(height * width, sol); // updating the sol + } + + stack.push(i); // pushing the element's index to the stack + } + } + + return sol; + } + + public static void main(String[] args) { + int[][] matrix = { + {0, 1, 1, 0}, + {1, 1, 1, 1}, + {1, 1, 1, 1}, + {1, 1, 0, 0} + }; + + System.out.println(maxArea(matrix, 4, 4)); + } +} + + \ No newline at end of file From 2ea4f77d715b2dd9f22a0a6f55e27c14fea6e995 Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Wed, 17 May 2023 22:20:10 +0530 Subject: [PATCH 1120/1894] file name changed --- .../{floydsCycleDetection.ccp => floydsCycleDetection.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Linked List/{floydsCycleDetection.ccp => floydsCycleDetection.cpp} (100%) diff --git a/Linked List/floydsCycleDetection.ccp b/Linked List/floydsCycleDetection.cpp similarity index 100% rename from Linked List/floydsCycleDetection.ccp rename to Linked List/floydsCycleDetection.cpp From ce475ca7383a771f48a0834115c63f78ba4b455f Mon Sep 17 00:00:00 2001 From: jayesh-RN <100137975+jayesh-RN@users.noreply.github.com> Date: Wed, 17 May 2023 23:54:18 +0530 Subject: [PATCH 1121/1894] LFU_Cache in cpp updated --- Linked List/LFU_Cache.cpp | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Linked List/LFU_Cache.cpp diff --git a/Linked List/LFU_Cache.cpp b/Linked List/LFU_Cache.cpp new file mode 100644 index 00000000..473c6840 --- /dev/null +++ b/Linked List/LFU_Cache.cpp @@ -0,0 +1,79 @@ +// Question--> LFU Cache +// Design and implement a data structure for a Least Frequently Used (LFU) cache. + +// Implement the LFUCache class: + +// LFUCache(int capacity) Initializes the object with the capacity of the data structure. +// int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1. +// void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated. +// To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. + +// When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. + +// The functions get and put must each run in O(1) average time complexity + + +// solution --> + + +#include +using namespace std; + + +class LFUCache { + int cap; + int size; + int minFreq; + unordered_map> m; //key to {value,freq}; + unordered_map::iterator> mIter; //key to list iterator; + unordered_map> fm; //freq to key list; +public: + LFUCache(int capacity) { + // initialize your data structure here + cap=capacity; + size=0; + } + + int get(int key) { + if(m.count(key)==0) return -1; // if key not found return -1; + + fm[m[key].second].erase(mIter[key]); //erase from old freq list + m[key].second++; // increase freq; + fm[m[key].second].push_back(key); // add to new freq list; + mIter[key]=--fm[m[key].second].end();// point to new freq list; + + // if old min freq list empty, increase min freq; + if(fm[minFreq].size()==0 ) + minFreq++; + + return m[key].first; // return value + } + + void put(int key, int value) { + if(cap<=0) return; // corner case + + int storedValue=get(key); // get value if already present + + // if already present update value, increase freq; + if(storedValue!=-1) + { + m[key].first=value; + return; + } + + // if capacity full, erase least freq used element from this list + if(size>=cap ) + { + m.erase( fm[minFreq].front() ); + mIter.erase( fm[minFreq].front() ); + fm[minFreq].pop_front(); + size--; + } + + m[key]={value, 1}; // insert new key value pair with freq 1; + fm[1].push_back(key); // add to freq list 1; + mIter[key]=--fm[1].end(); // point to new freq list; + minFreq=1; // since new element added min freq will be 1; + size++; // increase size + } +}; \ No newline at end of file From aed706f5832354d3f691049e14ba3bf07d63bb00 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 18 May 2023 10:02:43 +0530 Subject: [PATCH 1122/1894] Create Kth_nodedelete.js --- Linked List/Kth_nodedelete.js | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Linked List/Kth_nodedelete.js diff --git a/Linked List/Kth_nodedelete.js b/Linked List/Kth_nodedelete.js new file mode 100644 index 00000000..7b7448b4 --- /dev/null +++ b/Linked List/Kth_nodedelete.js @@ -0,0 +1,83 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Remove Kth node from end in Javascript +Issue Number : #687 +Problem statement : + +Explanation of the below Javascript code : + +Define a Node class to represent each node in the linked list. +Create a function called removeKthFromEnd that accepts the head of the linked list and the value of k as parameters. +Now you can create a linked list and call the removeKthFromEnd function to remove the kth node from the end. + + +*/ + +-------------------------------------------------------------------------//Javascript code begins here------------------------------------------------------------------------ + + + +class Node { + constructor(value) { + this.value = value; + this.next = null; + } +} +function removeKthFromEnd(head, k) { + // Step 1: Create two pointers, fast and slow, and set them both to the head of the linked list. + let fast = head; + let slow = head; + + // Step 2: Move the fast pointer k nodes ahead. + for (let i = 0; i < k; i++) { + if (fast === null) { + // The linked list does not have k nodes. + return head; + } + fast = fast.next; + } + + // Step 3: If the fast pointer reaches the end, the kth node from the end is the head itself. + if (fast === null) { + head = head.next; + return head; + } + + // Step 4: Move the fast and slow pointers together until the fast pointer reaches the end. + while (fast.next !== null) { + fast = fast.next; + slow = slow.next; + } + + // Step 5: Remove the kth node by updating the next pointer of the previous node. + slow.next = slow.next.next; + + // Step 6: Return the modified linked list. + return head; +} +// Example usage: +const head = new Node(1); +head.next = new Node(2); +head.next.next = new Node(3); +head.next.next.next = new Node(4); +head.next.next.next.next = new Node(5); + +const k = 2; +const modifiedHead = removeKthFromEnd(head, k); + +// Display the modified linked list. +let current = modifiedHead; +while (current !== null) { + console.log(current.value); + current = current.next; +} + + +/* +OUTPUT: +1 +2 +3 +5 +*/ From 8ebc5ec1c18189f92fd64d4c241028ebc45d4de2 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 18 May 2023 10:12:46 +0530 Subject: [PATCH 1123/1894] Create Dijkstra.cpp --- Graphs/Dijkstra.cpp | 93 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Graphs/Dijkstra.cpp diff --git a/Graphs/Dijkstra.cpp b/Graphs/Dijkstra.cpp new file mode 100644 index 00000000..52d9dfe7 --- /dev/null +++ b/Graphs/Dijkstra.cpp @@ -0,0 +1,93 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Implement Dijkstra's algorithm in C++ +Issue Number : #947 +Problem statement : + +Explanation of the below C++ code : + +In this implementation, we have a dijkstra function that takes a graph represented as an adjacency list, the starting node, and the total number of nodes. It returns a vector containing the shortest distances from the start node to all other nodes. + +The dijkstra function initializes all distances to infinity except for the start node, which is set to 0. It uses a min heap priority queue to process nodes based on their distances. The algorithm iteratively selects the node with the minimum distance, updates the distances of its neighbors if a shorter path is found, and adds them to the priority queue. + +In the main function, we create a graph using the adjacency list representation. Each element of the graph vector is a vector of pairs, where the first element of the pair represents the neighbor node, and the second element represents the weight of the edge. + +We then call the dijkstra function with the graph, starting node, and the total number of nodes. Finally, we print the shortest distances from the start node to all other nodes. + + +*/ + +-------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ + + +#include +#include +#include +#include + +using namespace std; + +typedef pair pii; + +vector dijkstra(vector>& graph, int start, int n) { + vector dist(n, INT_MAX); // Initialize distances to infinity + dist[start] = 0; // Distance from start node to itself is 0 + + // Create a min heap priority queue to store vertices based on their distances + priority_queue, greater> pq; + pq.push(make_pair(0, start)); + + while (!pq.empty()) { + int u = pq.top().second; + pq.pop(); + + // Traverse all neighboring nodes of u + for (auto& neighbor : graph[u]) { + int v = neighbor.first; + int weight = neighbor.second; + + // Update distance if a shorter path is found + if (dist[v] > dist[u] + weight) { + dist[v] = dist[u] + weight; + pq.push(make_pair(dist[v], v)); + } + } + } + + return dist; +} + +int main() { + int n, m; // Number of nodes and edges + int start; // Starting node + + cout << "Enter the number of nodes: "; + cin >> n; + + cout << "Enter the number of edges: "; + cin >> m; + + cout << "Enter the starting node: "; + cin >> start; + + // Create an adjacency list representation of the graph + vector> graph(n); + + cout << "Enter the edges and their weights (node1 node2 weight):" << endl; + for (int i = 0; i < m; i++) { + int node1, node2, weight; + cin >> node1 >> node2 >> weight; + graph[node1].push_back(make_pair(node2, weight)); + } + + // Run Dijkstra's algorithm + vector distances = dijkstra(graph, start, n); + + // Print the shortest distances from the start node to all other nodes + for (int i = 0; i < n; i++) { + cout << "Shortest distance from node " << start << " to node " << i << ": " << distances[i] << endl; + } + + return 0; +} From a7aab8b8002db79ac2f3632e7d6c991fcba04ec0 Mon Sep 17 00:00:00 2001 From: jayesh-RN <100137975+jayesh-RN@users.noreply.github.com> Date: Thu, 18 May 2023 11:37:03 +0530 Subject: [PATCH 1124/1894] LFU cache with comments has been added --- Linked List/LFU_Cache.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Linked List/LFU_Cache.cpp b/Linked List/LFU_Cache.cpp index 473c6840..b3db5ba7 100644 --- a/Linked List/LFU_Cache.cpp +++ b/Linked List/LFU_Cache.cpp @@ -15,6 +15,10 @@ // solution --> +//minFreq is the smallest frequency so far +//The main idea is to put all keys with the same frequency to a linked list so the most recent one can be evicted; +//mIter stored the key's position in the linked list; + #include using namespace std; @@ -76,4 +80,6 @@ class LFUCache { minFreq=1; // since new element added min freq will be 1; size++; // increase size } -}; \ No newline at end of file +}; + + From 6bd72c02ff8b7ab240329631f720cbbc9c290eca Mon Sep 17 00:00:00 2001 From: jayesh-RN <100137975+jayesh-RN@users.noreply.github.com> Date: Thu, 18 May 2023 11:42:00 +0530 Subject: [PATCH 1125/1894] leetcode LFU CACHE --- Linked List/LFU_Cache.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Linked List/LFU_Cache.cpp b/Linked List/LFU_Cache.cpp index b3db5ba7..120bfa0c 100644 --- a/Linked List/LFU_Cache.cpp +++ b/Linked List/LFU_Cache.cpp @@ -83,3 +83,4 @@ class LFUCache { }; +// https://leetcode.com/problems/lfu-cache/ \ No newline at end of file From 386473898b9acdb135e238f1fde0e257ed32a19e Mon Sep 17 00:00:00 2001 From: gssp4167 Date: Thu, 18 May 2023 11:53:29 +0530 Subject: [PATCH 1126/1894] Added coin_change.js in Dynamic Programming folder --- Dynamic Programming/coin_change.js | 85 ++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Dynamic Programming/coin_change.js diff --git a/Dynamic Programming/coin_change.js b/Dynamic Programming/coin_change.js new file mode 100644 index 00000000..548925aa --- /dev/null +++ b/Dynamic Programming/coin_change.js @@ -0,0 +1,85 @@ +/* + Coin Change Problem:- + + + Question:- + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. + + Example 1: + Input: coins = [1,2,5], amount = 11 + Output: 3 + Explanation: 11 = 5 + 5 + 1 + + Example 2: + Input: coins = [2], amount = 3 + Output: -1 + + Example 3: + Input: coins = [1], amount = 0 + Output: 0 + + Constraints: + 1 <= coins.length <= 12 + 1 <= coins[i] <= 231 - 1 + 0 <= amount <= 104 + + + Approach Explanation:- + + The code uses a dynamic programming approach to solve the coin change problem. The dp array is used to + store the minimum number of coins needed to make each amount from 0 to amount. The minimum number + of coins needed to make an amount of 0 is 0. Then, for each coin, the code iterates through each + amount from the coin value to the target amount. If the current amount minus the coin value is a + valid amount, the code updates the minimum number of coins needed to make that amount by taking + the minimum of the current value and the value of dp[i - coin] + 1. Finally, if the minimum + number of coins needed to make the target amount is still Infinity, it is not possible to make + the amount and the code returns -1. Otherwise, the code returns the minimum number of coins + needed to make the target amount. + + The time complexity is O(n * V), where n is the number of coins and V is the value we want to make change for. + The space complexity is also O(n * V) as we need to store the minimum number of coins required to make + change for every value up to V for every coin. + + In the worst case, when we have a large number of coins and a large value V, the time and space complexity + can become quite large. However, this approach can efficiently handle a wide range of input values and is + guaranteed to give the optimal solution. +*/ + +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ + + +var coinChange = function(coins, amount) { + + // Create a array to store the minimum number of coins needed to make each amount from 0 to amount + const dp=Array(amount+1).fill(Infinity); + + // The minimum number of coins needed to make an amount of 0 is 0 + dp[0]=0; + + // Iterate through each coin + for(const coin of coins){ + // Iterate through each amount from the coin value to the target amount + for(let i=coin;i<=amount;i++){ + // If the current amount minus the coin value is a valid amount, update the minimum number of coins needed + if(dp[i-coin]!=Infinity) + { + dp[i]=Math.min(dp[i],dp[i-coin]+1); + } + } + } + + // If the minimum number of coins needed to make the target amount is still Infinity, it is not possible to make the amount + if(dp[amount]===Infinity) + { + return -1; + } + + // Return the minimum number of coins needed to make the target amount + return dp[amount]; +}; From 24c4a20fb98a4267fe1c70ef89e6cdbfe07162a1 Mon Sep 17 00:00:00 2001 From: payalpm Date: Thu, 18 May 2023 14:43:33 +0530 Subject: [PATCH 1127/1894] java-dijkstras --- Graphs/dijkstras.java | 100 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Graphs/dijkstras.java diff --git a/Graphs/dijkstras.java b/Graphs/dijkstras.java new file mode 100644 index 00000000..70c9ed80 --- /dev/null +++ b/Graphs/dijkstras.java @@ -0,0 +1,100 @@ +import java.util.*; + +class Main { + // Represents a node in the graph + static class Node implements Comparable { + String name; + int distance; + + Node(String name) { + this.name = name; + this.distance = Integer.MAX_VALUE; // Initialize distance to infinity + } + + @Override + public int compareTo(Node other) { + return Integer.compare(this.distance, other.distance); + } + } + + // Represents a weighted edge between two nodes + static class Edge { + Node source; + Node destination; + int weight; + + Edge(Node source, Node destination, int weight) { + this.source = source; + this.destination = destination; + this.weight = weight; + } + } + + // Dijkstra's algorithm implementation + static void dijkstra(Map> graph, String start) { + Map nodes = new HashMap<>(); // Stores nodes and their distances + + // Initialize nodes with their respective distances + for (String nodeName : graph.keySet()) { + Node node = new Node(nodeName); + if (nodeName.equals(start)) { + node.distance = 0; // Set distance of start node to 0 + } + nodes.put(nodeName, node); + } + + PriorityQueue queue = new PriorityQueue<>(); // Priority queue for node selection + queue.add(nodes.get(start)); // Add the start node to the queue + + // Dijkstra's algorithm main loop + while (!queue.isEmpty()) { + Node current = queue.poll(); // Get the node with the smallest distance from the queue + + // Iterate over the edges of the current node + for (Edge edge : graph.get(current.name)) { + int newDistance = current.distance + edge.weight; // Calculate new distance to the neighbor node + Node neighbor = nodes.get(edge.destination.name); // Get the neighbor node + + // If the new distance is shorter, update the neighbor node's distance and re-add it to the queue + if (newDistance < neighbor.distance) { + queue.remove(neighbor); // Remove the neighbor node from the queue + neighbor.distance = newDistance; // Update the distance of the neighbor node + queue.add(neighbor); // Re-add the neighbor node to the queue + } + } + } + } + + public static void main(String[] args) { + Map> graph = new HashMap<>(); // Graph represented as a map of nodes and edges + + // Create edges and add them to the graph + List edgesA = new ArrayList<>(); + edgesA.add(new Edge(new Node("A"), new Node("B"), 2)); + edgesA.add(new Edge(new Node("A"), new Node("C"), 3)); + graph.put("A", edgesA); + + List edgesB = new ArrayList<>(); + edgesB.add(new Edge(new Node("B"), new Node("C"), 1)); + edgesB.add(new Edge(new Node("B"), new Node("D"), 1)); + graph.put("B", edgesB); + + List edgesC = new ArrayList<>(); + edgesC.add(new Edge(new Node("C"), new Node("D"), 4)); + graph.put("C", edgesC); + + List edgesD = new ArrayList<>(); + edgesD.add(new Edge(new Node("D"), new Node("C"), 2)); + graph.put("D", edgesD); + + String start = "A"; // Starting node + dijkstra(graph, start); // Run Dijkstra's algorithm + + // Print the shortest distances from the start node to each node in the graph + for (String nodeName : graph.keySet()) { + Node node = graph.get(nodeName).get(0).source; + System.out.println("Shortest distance from " + start + " to " + node.name + ": " + node.distance); + } + } +} + From eb1392d4e5e4b91826cbbafd18a5b45ce87a790f Mon Sep 17 00:00:00 2001 From: payalpm Date: Thu, 18 May 2023 15:37:21 +0530 Subject: [PATCH 1128/1894] knight-probabilty-check --- Dynamic Programming/Knight -Probability.go | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Dynamic Programming/Knight -Probability.go diff --git a/Dynamic Programming/Knight -Probability.go b/Dynamic Programming/Knight -Probability.go new file mode 100644 index 00000000..9b132c04 --- /dev/null +++ b/Dynamic Programming/Knight -Probability.go @@ -0,0 +1,70 @@ +/* +On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly k moves or has moved off the chessboard. + +Return the probability that the knight remains on the board after it has stopped moving. + + + +Example 1: + +Input: n = 3, k = 2, row = 0, column = 0 +Output: 0.06250 +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +From each of those positions, there are also two moves that will keep the knight on the board. +The total probability the knight stays on the board is 0.0625. +Example 2: + +Input: n = 1, k = 0, row = 0, column = 0 +Output: 1.00000 +*/ +func knightProbability(n int, k int, row int, column int) float64 { + // Create a 3D grid to store the probabilities + dp := make([][][]float64, n) + for i := 0; i < n; i++ { + dp[i] = make([][]float64, n) + for j := 0; j < n; j++ { + dp[i][j] = make([]float64, k+1) + } + } + + // Define the eight possible knight moves + moves := [][]int{{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}} + + // Set the initial probability of the knight being on the starting cell to 1 + dp[row][column][0] = 1.0 + + // Calculate the probabilities for each move + for s := 1; s <= k; s++ { + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + for _, move := range moves { + x := i + move[0] + y := j + move[1] + + // Check if the move is within the chessboard + if x >= 0 && x < n && y >= 0 && y < n { + // Accumulate the probability for the current cell + dp[i][j][s] += dp[x][y][s-1] / 8.0 + } + } + } + } + } + + // Calculate the total probability of the knight remaining on the board + probability := 0.0 + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + probability += dp[i][j][k] + } + } + + return probability +} From 3127d02f297a7118b0863e8012bc3a08f5ae1db7 Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Thu, 18 May 2023 23:17:13 +0530 Subject: [PATCH 1129/1894] Reconstruction of BST to return root node --- Trees/Binary Search Trees/reconstruct_bst.js | 83 ++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Trees/Binary Search Trees/reconstruct_bst.js diff --git a/Trees/Binary Search Trees/reconstruct_bst.js b/Trees/Binary Search Trees/reconstruct_bst.js new file mode 100644 index 00000000..6ba8c6fb --- /dev/null +++ b/Trees/Binary Search Trees/reconstruct_bst.js @@ -0,0 +1,83 @@ +/** + * Class representing a node in the Binary Search Tree (BST). + */ + class TreeNode { + /** + * Create a new TreeNode. + * @param {*} value - The value to be stored in the node. + */ + constructor(value) { + this.val = value; + this.left = null; + this.right = null; + } + } + + /** + * Reconstructs a Binary Search Tree (BST) from its pre-order traversal. + * @param {number[]} preorder - The pre-order traversal array of the BST. + * @return {TreeNode} - The root node of the reconstructed BST. + */ + function constructBST(preorder) { + // Base case: if the array is empty, return null + if (preorder.length === 0) { + return null; + } + + // The first element in the pre-order array is the root value + const rootValue = preorder[0]; + const rootNode = new TreeNode(rootValue); + + // Find the index where the elements are greater than the root value + let i = 1; + while (i < preorder.length && preorder[i] < rootValue) { + i++; + } + + // Split the remaining elements into left and right subtrees + const leftSubtree = preorder.slice(1, i); + const rightSubtree = preorder.slice(i); + + // Recursively construct the left and right subtrees + rootNode.left = constructBST(leftSubtree); + rootNode.right = constructBST(rightSubtree); + + return rootNode; + } + + // Example usage + const preorder = [10, 4, 2, 1, 5, 17, 19, 18]; + const root = constructBST(preorder); + + /** + * Prints the values of the BST in ascending order using an in-order traversal. + * @param {TreeNode} node - The root node of the BST. + */ + function printInOrder(node) { + if (node === null) { + return; + } + + printInOrder(node.left); + console.log(node.val); + printInOrder(node.right); + } + + // Print the values of the reconstructed BST in ascending order + printInOrder(root); + +/** + * The time complexity of the constructBST function can be analyzed as follows: + +In each recursive call, we split the pre-order traversal array into two parts based on the root value. This operation takes O(N) time, where N is the number of elements in the array. +Since the function is called recursively for the left and right subtrees, the total time complexity can be expressed as a summation of the work done in each recursive call. +In the worst case, the pre-order traversal array is completely unbalanced, resulting in a linear chain of nodes. In this case, the function will make N recursive calls, each taking O(N) time. +Therefore, the overall time complexity of the constructBST function is O(N^2) in the worst case. +However, in the average case, when the BST is balanced, the time complexity can be approximated as O(NlogN). + */ + +/** + * In each recursive call, the function creates new arrays for the left and right subtrees using the slice method. The space required for these arrays is proportional to the size of the pre-order traversal array. +In the worst case, when the BST is completely unbalanced, the size of the arrays will be O(N), where N is the number of elements in the pre-order traversal array. +Therefore, the overall space complexity of the `construct + */ \ No newline at end of file From 2b13c79c48aa4d68eea00719859a4bf39bdc6fbe Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Thu, 18 May 2023 23:21:21 +0530 Subject: [PATCH 1130/1894] missing segment of documentation updated --- Trees/Binary Search Trees/reconstruct_bst.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Trees/Binary Search Trees/reconstruct_bst.js b/Trees/Binary Search Trees/reconstruct_bst.js index 6ba8c6fb..5eb41077 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.js +++ b/Trees/Binary Search Trees/reconstruct_bst.js @@ -79,5 +79,5 @@ However, in the average case, when the BST is balanced, the time complexity can /** * In each recursive call, the function creates new arrays for the left and right subtrees using the slice method. The space required for these arrays is proportional to the size of the pre-order traversal array. In the worst case, when the BST is completely unbalanced, the size of the arrays will be O(N), where N is the number of elements in the pre-order traversal array. -Therefore, the overall space complexity of the `construct +Therefore, the overall space complexity of the `constructBST function is O(N) in the worst case. */ \ No newline at end of file From 81700de53dd39e025d3dc52f8770f216c0995d03 Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Fri, 19 May 2023 08:48:13 +0530 Subject: [PATCH 1131/1894] file name changed --- .../{searchIn2DSortedArray.ccp => searchIn2DSortedArray.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{searchIn2DSortedArray.ccp => searchIn2DSortedArray.cpp} (100%) diff --git a/2D Arrays (Matrix)/searchIn2DSortedArray.ccp b/2D Arrays (Matrix)/searchIn2DSortedArray.cpp similarity index 100% rename from 2D Arrays (Matrix)/searchIn2DSortedArray.ccp rename to 2D Arrays (Matrix)/searchIn2DSortedArray.cpp From e7d97c391ef064921f902b85483411ebef6706b0 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 19 May 2023 09:30:33 +0530 Subject: [PATCH 1132/1894] Create Graphs_dfs.java --- Graphs/Graphs_dfs.java | 74 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Graphs/Graphs_dfs.java diff --git a/Graphs/Graphs_dfs.java b/Graphs/Graphs_dfs.java new file mode 100644 index 00000000..d62b868a --- /dev/null +++ b/Graphs/Graphs_dfs.java @@ -0,0 +1,74 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Implement Depth First Search in Java +Issue Number : #733 +Problem statement : + +Explanation of the below Java code : + +In this example, we have a Node class representing each node in the graph. Each Node has a value, a list of neighbors, and a boolean flag to track if it has been visited. + +The DepthFirstSearch class contains the dfs method, which performs the depth-first search traversal. It takes a starting node as an argument and recursively visits all unvisited neighbors of that node. When visiting a node, it marks it as visited and prints its value. + +In the main method, we create a small graph with five nodes and test the dfs method by starting the traversal from the first node (node1). The output will display the visited nodes in the order they are traversed: + + +*/ + +-------------------------------------------------------------------------//Java code begins here------------------------------------------------------------------------ + + +import java.util.ArrayList; +import java.util.List; + +class Node { + int value; + List neighbors; + boolean visited; + + Node(int value) { + this.value = value; + this.neighbors = new ArrayList<>(); + this.visited = false; + } + + void addNeighbor(Node neighbor) { + this.neighbors.add(neighbor); + } +} + +class DepthFirstSearch { + void dfs(Node startNode) { + // Mark the startNode as visited + startNode.visited = true; + System.out.println("Visited Node: " + startNode.value); + + // Recursively visit all unvisited neighbors + for (Node neighbor : startNode.neighbors) { + if (!neighbor.visited) { + dfs(neighbor); + } + } + } +} + +public class Main { + public static void main(String[] args) { + // Create a graph for testing + Node node1 = new Node(1); + Node node2 = new Node(2); + Node node3 = new Node(3); + Node node4 = new Node(4); + Node node5 = new Node(5); + + node1.addNeighbor(node2); + node1.addNeighbor(node3); + node2.addNeighbor(node4); + node3.addNeighbor(node4); + node4.addNeighbor(node5); + + DepthFirstSearch dfs = new DepthFirstSearch(); + dfs.dfs(node1); + } +} From 096f9929f6504ab7446172bf67eb204c414f711d Mon Sep 17 00:00:00 2001 From: mohitsingh1011 Date: Fri, 19 May 2023 10:47:44 +0530 Subject: [PATCH 1133/1894] Implement Singly linked list in C++ --- Linked List/implementSinglyLinkedList.cpp | 154 +++++++++++++++++ .../implementation_singly_linked_list.cpp | 155 ------------------ 2 files changed, 154 insertions(+), 155 deletions(-) create mode 100644 Linked List/implementSinglyLinkedList.cpp delete mode 100644 Linked List/implementation_singly_linked_list.cpp diff --git a/Linked List/implementSinglyLinkedList.cpp b/Linked List/implementSinglyLinkedList.cpp new file mode 100644 index 00000000..53943b4c --- /dev/null +++ b/Linked List/implementSinglyLinkedList.cpp @@ -0,0 +1,154 @@ +// Implementation of singly LinkedList + +/*Search for a node in the list +You can determine and retrieve a specific node from the front, end, or anywhere in the list. +The worst-case​ Time Complexity for retrieving a node from anywhere in the list is O(n). + +Add a node to the list +You can add a node at the front, end, or anywhere in the linked list. +The worst-case Time Complexities for performing these operations are: +Add an item to the front of the list: O(1) +Add an item to the end of the list: O(n) +Add an item a​nywhere in the list: O(n) + +Remove a node from the list +You can remove a node from the front, end, or anywhere in the list. +The worst-case Time Complexities for performing this operation are: +Remove an item from the front of the list: O(1) +Remove an item from the end of the list: O(n) +Remove an item from anywhere in the list: O(n) + +Time complexity : O(n) +Space complexity : O(n) +*/ + +#include +using namespace std; + +// Making a node struct containing an int data and a pointer +// to next node +struct Node +{ + int data; + Node *next; + + // Parameterised constructor with default argument + Node(int val = 0) : data(val), next(nullptr) {} + // Parameterise constructor + Node(int val, Node *tempNext) : data(val), next(tempNext) {} +}; + +class LinkedList +{ + // Head pointer + Node *head; + +public: + // default constructor. Initializing head pointer + LinkedList() : head(nullptr) + { + } + + // inserting elements (At start of the list) + void insert(int val) + { + // make a new node + Node *new_node = new Node(val); + + // If list is empty, make the new node, the head + if (head == nullptr) + { + head = new_node; + } + // else, make the new_node the head and its next, the previous + // head + else + { + new_node->next = head; + head = new_node; + } + } + + // loop over the list. return true if element found + bool search(int val) + { + Node *temp = head; + while (temp != nullptr) + { + if (temp->data == val) + return true; + temp = temp->next; + } + return false; + } + + void remove(int val) + { + Node *temp = head; + // If the head is to be deleted + if (temp != nullptr && temp->data == val) + { + head = temp->next; + delete temp; + return; + } + // Else loop over the list and search for the node to delete + else + { + Node *curr = head; + while (temp != nullptr && temp->data != val) + { + // When node is found, delete the node and modify the pointers + curr = temp; + temp = temp->next; + } + // If values is not found in the linked list + if (!temp) + { + cout << "Value not found" << endl; + return; + } + + curr->next = temp->next; + delete temp; + } + } + + void display() + { + Node *temp = head; + while (temp != nullptr) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << endl; + } +}; + +int main() +{ + + LinkedList l; + // inserting elements + l.insert(6); + l.insert(9); + l.insert(1); + l.insert(3); + l.insert(7); + cout << "Current Linked List: "; + l.display(); + + cout << "Deleting 1: "; + l.remove(1); + l.display(); + + cout << "Deleting 13: "; + l.remove(13); + + cout << "Searching for 7: "; + cout << l.search(7) << endl; + + cout << "Searching for 13: "; + cout << l.search(13) << endl; +} \ No newline at end of file diff --git a/Linked List/implementation_singly_linked_list.cpp b/Linked List/implementation_singly_linked_list.cpp deleted file mode 100644 index 514dbd9c..00000000 --- a/Linked List/implementation_singly_linked_list.cpp +++ /dev/null @@ -1,155 +0,0 @@ -// Implementation of singly LinkedList -// Program Author : SNEHA CHAUHAN - -/*A class and a Node class can be used individually in C++ to represent a linked list. The class contains two elements, data and a next pointer that links to the next node. */ -/*Three function are implementing in the Linked list class*/ -/*InsertNode: Insetion can be done at the end the linked list*/ -/*DeleteNode: Deletion is done using index of the node*/ -/*PrintNode: Print the Linked list*/ -#include -using namespace std; - -// Class Represent node of the linked list -class Node -{ -public: - int data; - Node *next; - - // Default Constructor - Node() - { - data = 0; - next = NULL; - } - - // // Parameterized Constructor - Node(int data) - { - this->data = data; - this->next = NULL; - } -}; - -// Linked list class -class Linkedlist -{ - Node *head; - -public: - Linkedlist() - { - head = NULL; - } - - // Function for Instering a node in the Linked list - void insertNode(int data) - { - // Create the new Node. - Node *newNode = new Node(data); - - // Assign to head - if (head == NULL) - { - head = newNode; - return; - } - - // Traverse till end of list - Node *temp = head; - while (temp->next != NULL) - { - // Update temp - temp = temp->next; - } - // Insert at the last. - temp->next = newNode; - } - // Function for Deleting a node in the Linked list at given position - void deleteNode(int index) - { - Node *temp1 = head, *temp2 = NULL; - int ListLen = 0; - - if (head == NULL) - { - cout << "List empty." << endl; - return; - } - - // Find length of the linked-list. - while (temp1 != NULL) - { - temp1 = temp1->next; - ListLen++; - } - - // Check if the position to be - // deleted is greater than the length - // of the linked list. - if (ListLen < index) - { - cout << "Index out of range" - << endl; - return; - } - - // Declare temp1 - temp1 = head; - - // Deleting the head. - if (index == 1) - { - // Update head - head = head->next; - delete temp1; - return; - } - - // Traverse the list to - // find the node to be deleted. - while (index-- > 1) - { - // Update temp2 - temp2 = temp1; - // Update temp1 - temp1 = temp1->next; - } - - // Change the next pointer - // of the previous node. - temp2->next = temp1->next; - - // Delete the node - delete temp1; - } - void printList() - { - Node *temp = head; - - // Check for empty list. - if (head == NULL) - { - cout << "List empty" << endl; - return; - } - - // Traverse the list. - while (temp != NULL) - { - cout << temp->data << " "; - temp = temp->next; - } - } -}; - -int main() -{ - Linkedlist list; - list.insertNode(4); - list.insertNode(2); - list.insertNode(3); - list.insertNode(8); - - list.printList(); -} \ No newline at end of file From 2ee903510bec39155a3f93a07b911d7bdc881078 Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Fri, 19 May 2023 14:11:57 +0530 Subject: [PATCH 1134/1894] Question documentation updated --- Trees/Binary Search Trees/reconstruct_bst.js | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Trees/Binary Search Trees/reconstruct_bst.js b/Trees/Binary Search Trees/reconstruct_bst.js index 5eb41077..02196c94 100644 --- a/Trees/Binary Search Trees/reconstruct_bst.js +++ b/Trees/Binary Search Trees/reconstruct_bst.js @@ -1,3 +1,25 @@ +/** Reconstruct BST + The pre-order traversal of a Binary Tree is a traversal technique that starts at the tree's root + node and visits nodes in the following order: + Current Node + Left Subtree + Right Subtree + + Given a non-empty array of integers representing the pre-order traversal of a Binary Search Tree + (BST), write a function that creates the relevant BST and returns its root node. + + The input array will contain the values of BST nodes in the order in which these nodes would be + visited with a pre-order traversal. + Sample Input: [10, 4, 2, 1, 5, 17, 19, 18] + Sample Output: + 10 + / \ + 4 17 + / \ \ + 2 5 19 + / / +1 18 +*/ /** * Class representing a node in the Binary Search Tree (BST). */ From 28190551d03d447d7591e0335b8afc054a35e2b1 Mon Sep 17 00:00:00 2001 From: Harsit Agarwalla <84774840+harsitagarwalla187@users.noreply.github.com> Date: Fri, 19 May 2023 21:06:43 +0530 Subject: [PATCH 1135/1894] Update Validate_BST.js --- Trees/Binary Search Trees/Validate_BST.js | 48 +++++++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/Trees/Binary Search Trees/Validate_BST.js b/Trees/Binary Search Trees/Validate_BST.js index 3c068140..7d2ffc41 100644 --- a/Trees/Binary Search Trees/Validate_BST.js +++ b/Trees/Binary Search Trees/Validate_BST.js @@ -1,8 +1,39 @@ -////// Explanation: -// To validate a Binary Search Tree (BST), we need to ensure that the values of nodes in the left subtree of any node are less than the value of the node, and the values of nodes in the right subtree are greater than the value of the node. -// Additionally, the left and right subtrees themselves must also be valid BSTs. +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) + and returns a boolean representing whether the BST is valid. + Sample Input : + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 + Output : True -////// Code: + Explanation: + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can + point to other BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating + whether the tree is a valid BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree + is a valid BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum + and maximum values that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined + by the min and max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left + and right child nodes to check whether their values are within their valid ranges. The valid range for the + left child node is defined by the minimum value and the parent node's value, while the valid range for the + right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree + is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST + +*/ class Node { constructor(data) { this.data = data; @@ -11,7 +42,8 @@ class Node { } } - function isBST(root) { +// isBst is a method of BST that checks if the binary search tree is valid +function isBST(root) { let prev = null; function inorderTraversal(node) { @@ -21,12 +53,12 @@ class Node { return true; } - // If left subtree is not BST return false + // recursively check the left subtree, making sure all values are less than the current node's value if (!inorderTraversal(node.left)) { return false; } - // If current node is greater than parent node return false + // if the current node's value is outside the allowed range, then the tree is invalid if (prev !== null && node.data <= prev.data) { return false; } @@ -57,4 +89,4 @@ class Node { ////// Complexity: // Time Complexity: O(n) where n is number of nodes -// Space Complexity: O(1) \ No newline at end of file +// Space Complexity: O(1) From f7dcde547b3399ea7e09b987179e3ff0a9918028 Mon Sep 17 00:00:00 2001 From: Harsit Agarwalla <84774840+harsitagarwalla187@users.noreply.github.com> Date: Fri, 19 May 2023 21:10:34 +0530 Subject: [PATCH 1136/1894] Update Validate_BST.py --- Trees/Binary Search Trees/Validate_BST.py | 53 +++++++++++++++++++---- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/Trees/Binary Search Trees/Validate_BST.py b/Trees/Binary Search Trees/Validate_BST.py index 2ea6eb90..559b09c4 100644 --- a/Trees/Binary Search Trees/Validate_BST.py +++ b/Trees/Binary Search Trees/Validate_BST.py @@ -1,8 +1,39 @@ -## Explanation: -# To validate a Binary Search Tree (BST), we need to ensure that the values of nodes in the left subtree of any node are less than the value of the node, and the values of nodes in the right subtree are greater than the value of the node. -# Additionally, the left and right subtrees themselves must also be valid BSTs. +''' + Write a function that takes in a potentially invalid Binary Search Tree (BST) + and returns a boolean representing whether the BST is valid. + Sample Input : + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 + Output : True -## Code: + Explanation: + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can + point to other BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating + whether the tree is a valid BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree + is a valid BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum + and maximum values that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined + by the min and max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left + and right child nodes to check whether their values are within their valid ranges. The valid range for the + left child node is defined by the minimum value and the parent node's value, while the valid range for the + right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree + is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST + +''' class Node: def __init__(self, data): self.data = data @@ -10,20 +41,26 @@ def __init__(self, data): self.right = None +# ValidateBst is a method of BST that checks if the binary search tree is valid def is_bst(root): global prev prev = None - + + #validateBST is a recursive helper function that checks if the binary search tree is valid + #min is the minimum value that a node in the subtree rooted at this node can have + #max is the maximum value that a node in the subtree rooted at this node can have def inorder_traversal(node): global prev + + # if the current node's value is outside the allowed range, then the tree is invalid if node is None: return True - // If left subtree is not BST return false + # If left subtree is not BST return false if not inorder_traversal(node.left): return False - // If current node is greater than parent node return false + # recursively check the left subtree, making sure all values are less than the current node's value if prev is not None and node.data <= prev.data: return False @@ -50,4 +87,4 @@ def inorder_traversal(node): ## Complexity: # Time Complexity: O(n) where n is number of nodes -# Space Complexity: O(1) \ No newline at end of file +# Space Complexity: O(1) From 41943c35187f430081f5c473b862f060307bb985 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 19 May 2023 22:56:49 +0530 Subject: [PATCH 1137/1894] rename file --- .../{BST_kth_largest.cpp => Kth_largest_BST.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trees/Binary Search Trees/{BST_kth_largest.cpp => Kth_largest_BST.cpp} (100%) diff --git a/Trees/Binary Search Trees/BST_kth_largest.cpp b/Trees/Binary Search Trees/Kth_largest_BST.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_kth_largest.cpp rename to Trees/Binary Search Trees/Kth_largest_BST.cpp From d076d43b7c58c5d883a5b249c1eb71f7721ad037 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 19 May 2023 22:57:21 +0530 Subject: [PATCH 1138/1894] rename file --- .../{Implement Queue using Stacks.cpp => queue_using_stacks.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Stacks/{Implement Queue using Stacks.cpp => queue_using_stacks.cpp} (100%) diff --git a/Stacks/Implement Queue using Stacks.cpp b/Stacks/queue_using_stacks.cpp similarity index 100% rename from Stacks/Implement Queue using Stacks.cpp rename to Stacks/queue_using_stacks.cpp From 250a18e25abcca2f2be6eb1b1f0f2f66ac3e34c9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 19 May 2023 22:58:32 +0530 Subject: [PATCH 1139/1894] remove duplicate --- 2D Arrays (Matrix)/searchIn2DSortedArray.cpp | 55 -------------------- 1 file changed, 55 deletions(-) delete mode 100644 2D Arrays (Matrix)/searchIn2DSortedArray.cpp diff --git a/2D Arrays (Matrix)/searchIn2DSortedArray.cpp b/2D Arrays (Matrix)/searchIn2DSortedArray.cpp deleted file mode 100644 index f977c55f..00000000 --- a/2D Arrays (Matrix)/searchIn2DSortedArray.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - -Follow the given steps to solve the problem: - -Run a nested loop, outer loop for the row, and inner loop for the column -Check every element with x and if the element is found then print “element found” -If the element is not found, then print “element not found” - -Time Complexity: O(N2) -Auxiliary Space: O(1), since no extra space has been taken. - -*/ - -#include - -using namespace std; - -/* Searches the element x in mat[][]. If the -element is found, then prints its position -and returns true, otherwise prints "not found" -and returns false */ -int search(int mat[4][4], int n, int x) -{ - if (n == 0) - return -1; - - // traverse through the matrix - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) - // if the element is found - if (mat[i][j] == x) { - cout << "Element found at (" << i << ", " - << j << ")\n"; - return 1; - } - } - - cout << "n Element not found"; - return 0; -} - -// Driver code -int main() -{ - int mat[4][4] = { { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 27, 29, 37, 48 }, - { 32, 33, 39, 50 } }; - - // Function call - search(mat, 4, 29); - - return 0; -} - \ No newline at end of file From f8bb36247099c94bf10b406e7f411027ac8fb1de Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 19 May 2023 23:01:37 +0530 Subject: [PATCH 1140/1894] rename file --- Strings/{group_anagram.py => group_anagrams.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Strings/{group_anagram.py => group_anagrams.py} (100%) diff --git a/Strings/group_anagram.py b/Strings/group_anagrams.py similarity index 100% rename from Strings/group_anagram.py rename to Strings/group_anagrams.py From 91b7eabab2c4d05cd3d39b12abe002719fa11db8 Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 06:00:59 +0000 Subject: [PATCH 1141/1894] The TreeNode class represents each node of the BST. The constructBST function takes the pre-order traversal array as input and recursively constructs the BST. It uses the first element as the root, finds the partition point in the array based on the root's value, and recursively constructs the left and right subtrees. The inorderTraversal function is provided to verify the reconstructed BST by printing its inorder traversal. In this example, it prints [1, 2, 4, 5, 10, 17, 18, 19], which matches the expected output tree you provided. Note: This code assumes that the input array is a valid pre-order traversal of a BST and does not perform any error checking. --- .../reconstruct_bst_in_python.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Dynamic Programming/reconstruct_bst_in_python.py diff --git a/Dynamic Programming/reconstruct_bst_in_python.py b/Dynamic Programming/reconstruct_bst_in_python.py new file mode 100644 index 00000000..24610a73 --- /dev/null +++ b/Dynamic Programming/reconstruct_bst_in_python.py @@ -0,0 +1,36 @@ +class TreeNode: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +def constructBST(preorder): + if not preorder: + return None + + root = TreeNode(preorder[0]) + + i = 1 + while i < len(preorder) and preorder[i] < root.val: + i += 1 + + root.left = constructBST(preorder[1:i]) + root.right = constructBST(preorder[i:]) + + return root + +def inorderTraversal(root): + if root is None: + return [] + + return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right) + +# Sample Input +preorder = [10, 4, 2, 1, 5, 17, 19, 18] + +# Construct the BST +root = constructBST(preorder) + +# Print the inorder traversal of the reconstructed BST +inorder = inorderTraversal(root) +print(inorder) From 3c11981100f3dc57024f30b27e74eb73228599a6 Mon Sep 17 00:00:00 2001 From: Rohith1816 <–mude.rohith.cse21@itbhu.ac.in> Date: Sat, 20 May 2023 14:36:35 +0530 Subject: [PATCH 1142/1894] Created total_hamming_distance.cpp file --- Arrays/total_hamming_distance.cpp | 108 ++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Arrays/total_hamming_distance.cpp diff --git a/Arrays/total_hamming_distance.cpp b/Arrays/total_hamming_distance.cpp new file mode 100644 index 00000000..95846145 --- /dev/null +++ b/Arrays/total_hamming_distance.cpp @@ -0,0 +1,108 @@ +/* + +Introduction: + + This documentation provides a detailed explanation of the problem statement, algorithm, and implementation of + calculating the sum of Hamming distances between all pairs of integers in an integer array. + Hamming distance measures the number of positions at which corresponding bits are different between two numbers. + The algorithm aims to find the sum of Hamming distances for all possible pairs of integers in the given array. + +Problem Statement: + + Given an integer array nums, the task is to calculate the sum of Hamming distances between all the pairs of integers in nums. + The goal is to determine the total count of differing bits at each position for all possible pairs of integers in the array. + +Hamming Distance : + + Hamming distance is a metric for comparing two binary data strings. + While comparing two binary strings of equal length, Hamming distance is the number of bit positions in which the two bits are different. + +Sample Input : [4,14,2] +expected Output : 6 + +Explaination : In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). +Total Hamming distance = HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + +Method 1 : + + (Brute Force Method) We can iterate over the whole array and find all pairs calculate Hamming distance and add all the distances. + Time complexity : O(n^2) + Space Complexity : O(1) + +Method 2 : + + 1. Initialize a variable `totalDistance` to store the sum of Hamming distances. + 2. Iterate over each bit position from 0 to 31 (assuming integers are 32-bit). + 3. For each bit position `i`, initialize two variables: `countZeros` and `countOnes` to keep track of the count of zeros and ones at that position. + 4. Iterate over each element `num` in `nums`. + a. Right shift `num` by `i` positions and perform a bitwise AND with 1 to check the value at bit position `i`. + b. If the result is 0, increment `countZeros` by 1; otherwise, increment `countOnes` by 1. + 5. Add `countZeros * countOnes` to `totalDistance`. This calculates the Hamming distance for the current bit position and adds it to the running total. + 6. Repeat steps 3-5 for all bit positions. + 7. Return `totalDistance` as the sum of Hamming distances between all pairs of integers in `nums`. + + Time Complexity : O(k*n) where , + k = maximum number of bits required to represent a number in the array + n = size of array + + Space Complexity : O(1) + + +Explaination : + + Number ==> Binary Representation + 4 0 1 0 0 + 14 1 1 1 0 + 2 0 0 1 0 + + The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set. + Let this count be ‘c'. There would be “n-c” numbers with i’th bit not set. + So count of differences at i’th bit would be “count * (n-count)”, the reason for this formula is as every pair having one element + which has set bit at i’th position and second element having unset bit at i’th position contributes exactly 1 to sum. + + 1st bit = 2*1 = 2 + 2nd bit = 2*1 = 2 + 3rd bit = 2*1 = 2 + 4th bit = 3*0 = 0 +-------------------------- + Total = 6 + + +*/ + +// CODE : + +// #include +#include +#include +using namespace std; + +int totalHammingDistance(vector& nums) { + int ans=0; + int n=nums.size(); + // Here we are assuing that the 32 bits are sufficient to represent all the numbers in the array + for(int i=0;i<32;i++){ + int c=0;// c represents number of set bits of a particular position in the whole array. + for(int j=0;j> n; + vector nums(n); + for(int i=0;i> nums[i]; + } + int total_hamming_distance = totalHammingDistance(nums); + cout << total_hamming_distance << endl; + return 0; +} \ No newline at end of file From 7da3d7c0b853bffa075c012acadbe6e8b5dfda9f Mon Sep 17 00:00:00 2001 From: arsallanShahab Date: Sat, 20 May 2023 16:02:44 +0530 Subject: [PATCH 1143/1894] Implement Knuth-Morris-Pratt (KMP) algorithm for string pattern matching --- Graphs/Graph_KMPAlgorithm.java | 83 ++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Graphs/Graph_KMPAlgorithm.java diff --git a/Graphs/Graph_KMPAlgorithm.java b/Graphs/Graph_KMPAlgorithm.java new file mode 100644 index 00000000..a8f1a3c5 --- /dev/null +++ b/Graphs/Graph_KMPAlgorithm.java @@ -0,0 +1,83 @@ +/* + * KMP Algorithm for Pattern Searching + * + * Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function + * search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. + * You may assume that n > m. + * + * Examples: + * + * Input: txt[] = "THIS IS A TEST TEXT" + * pat[] = "TEST" + * + * Output: Pattern found at index 10 + * + */ + +public class Graph_KMPAlgorithm { + + public static int[] computeLPSArray(String pattern) { + int[] lps = new int[pattern.length()]; + int len = 0; // Length of the previous longest prefix suffix + int i = 1; + + while (i < pattern.length()) { + if (pattern.charAt(i) == pattern.charAt(len)) { + len++; + lps[i] = len; + i++; + } else { + if (len != 0) { + len = lps[len - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + + return lps; + } + + public static int searchPattern(String text, String pattern) { + int n = text.length(); + int m = pattern.length(); + + int[] lps = computeLPSArray(pattern); + + int i = 0; // index for text + int j = 0; // index for pattern + + while (i < n) { + if (text.charAt(i) == pattern.charAt(j)) { + i++; + j++; + } + + if (j == m) { + return i - j; + } else if (i < n && text.charAt(i) != pattern.charAt(j)) { + if (j != 0) { + j = lps[j - 1]; + } else { + i++; + } + } + } + + return -1; // pattern not found in text + } + + public static void main(String[] args) { + String text = "ABABDABACDABABCABAB"; + String pattern = "ABABCABAB"; + + int index = searchPattern(text, pattern); + + if (index != -1) { + System.out.println("Pattern found at index: " + index); + } else { + System.out.println("Pattern not found in the text."); + } + } +} From 65bc348cdb40de35746ca1ca81b44294304380eb Mon Sep 17 00:00:00 2001 From: Rohith1816 <–mude.rohith.cse21@itbhu.ac.in> Date: Sat, 20 May 2023 17:30:27 +0530 Subject: [PATCH 1144/1894] Created total_hamming_distance.cpp file --- Arrays/total_hamming_distance.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Arrays/total_hamming_distance.cpp b/Arrays/total_hamming_distance.cpp index 95846145..04f5857c 100644 --- a/Arrays/total_hamming_distance.cpp +++ b/Arrays/total_hamming_distance.cpp @@ -78,7 +78,7 @@ Explaination : using namespace std; int totalHammingDistance(vector& nums) { - int ans=0; + int totalDistance=0; int n=nums.size(); // Here we are assuing that the 32 bits are sufficient to represent all the numbers in the array for(int i=0;i<32;i++){ @@ -87,9 +87,9 @@ int totalHammingDistance(vector& nums) { if((nums[j]&(1< Date: Sat, 20 May 2023 18:17:49 +0530 Subject: [PATCH 1145/1894] Implementation Singly linked list in C++ --- ...inglyLinkedList.cpp => implementation_Singly_Linked_List.cpp} | 1 + 1 file changed, 1 insertion(+) rename Linked List/{implementSinglyLinkedList.cpp => implementation_Singly_Linked_List.cpp} (99%) diff --git a/Linked List/implementSinglyLinkedList.cpp b/Linked List/implementation_Singly_Linked_List.cpp similarity index 99% rename from Linked List/implementSinglyLinkedList.cpp rename to Linked List/implementation_Singly_Linked_List.cpp index 53943b4c..f65aecb0 100644 --- a/Linked List/implementSinglyLinkedList.cpp +++ b/Linked List/implementation_Singly_Linked_List.cpp @@ -1,5 +1,6 @@ // Implementation of singly LinkedList +// Author : Mohit Singh /*Search for a node in the list You can determine and retrieve a specific node from the front, end, or anywhere in the list. The worst-case​ Time Complexity for retrieving a node from anywhere in the list is O(n). From 391d0071d656f564953728a3168f300dcecdd51f Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 13:16:06 +0000 Subject: [PATCH 1146/1894] =?UTF-8?q?=F0=9F=8C=B8Greetings=F0=9F=8C=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this repository our approach is basically to utilize a stack to keep the track of nodes while constructing the binary search tree from pre-order traversal. --- Dynamic Programming/distance_of_nearest_0.py | 79 ++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Dynamic Programming/distance_of_nearest_0.py diff --git a/Dynamic Programming/distance_of_nearest_0.py b/Dynamic Programming/distance_of_nearest_0.py new file mode 100644 index 00000000..be6332f6 --- /dev/null +++ b/Dynamic Programming/distance_of_nearest_0.py @@ -0,0 +1,79 @@ +'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + + + +Example 1: + + +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +Example 2: + + +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] + + +Constraints: + +m == mat.length +n == mat[i].length +1 <= m, n <= 104 +1 <= m * n <= 104 +mat[i][j] is either 0 or 1. +There is at least one 0 in mat. + +Explanation: + +In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. + +We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. + +If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. + +Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. + +When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. + +''' + +class TreeNode: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +def constructBST(preorder): + if not preorder: + return None + + root = TreeNode(preorder[0]) + stack = [root] + + for val in preorder[1:]: + node = TreeNode(val) + + if val < stack[-1].val: + stack[-1].left = node + else: + while stack and val > stack[-1].val: + last = stack.pop() + last.right = node + + stack.append(node) + + return root + +def inorderTraversal(root): + if root: + inorderTraversal(root.left) + print(root.val, end=' ') + inorderTraversal(root.right) + +preorder = [10, 4, 2, 1, 5, 17, 19, 18] +root = constructBST(preorder) + +# Verify the constructed BST by performing an in-order traversal +inorderTraversal(root) From 98d789cb7f3577f472db757ac6d3d98f87dd9fa6 Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 19:22:38 +0530 Subject: [PATCH 1147/1894] Delete distance_of_nearest_0.py --- Dynamic Programming/distance_of_nearest_0.py | 79 -------------------- 1 file changed, 79 deletions(-) delete mode 100644 Dynamic Programming/distance_of_nearest_0.py diff --git a/Dynamic Programming/distance_of_nearest_0.py b/Dynamic Programming/distance_of_nearest_0.py deleted file mode 100644 index be6332f6..00000000 --- a/Dynamic Programming/distance_of_nearest_0.py +++ /dev/null @@ -1,79 +0,0 @@ -'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. - -The distance between two adjacent cells is 1. - - - -Example 1: - - -Input: mat = [[0,0,0],[0,1,0],[0,0,0]] -Output: [[0,0,0],[0,1,0],[0,0,0]] -Example 2: - - -Input: mat = [[0,0,0],[0,1,0],[1,1,1]] -Output: [[0,0,0],[0,1,0],[1,2,1]] - - -Constraints: - -m == mat.length -n == mat[i].length -1 <= m, n <= 104 -1 <= m * n <= 104 -mat[i][j] is either 0 or 1. -There is at least one 0 in mat. - -Explanation: - -In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. - -We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. - -If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. - -Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. - -When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. - -''' - -class TreeNode: - def __init__(self, val): - self.val = val - self.left = None - self.right = None - -def constructBST(preorder): - if not preorder: - return None - - root = TreeNode(preorder[0]) - stack = [root] - - for val in preorder[1:]: - node = TreeNode(val) - - if val < stack[-1].val: - stack[-1].left = node - else: - while stack and val > stack[-1].val: - last = stack.pop() - last.right = node - - stack.append(node) - - return root - -def inorderTraversal(root): - if root: - inorderTraversal(root.left) - print(root.val, end=' ') - inorderTraversal(root.right) - -preorder = [10, 4, 2, 1, 5, 17, 19, 18] -root = constructBST(preorder) - -# Verify the constructed BST by performing an in-order traversal -inorderTraversal(root) From 20ffa032c16746a570dabe577fda4ed8fd2ee68a Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 13:55:49 +0000 Subject: [PATCH 1148/1894] distance of the nearest 0 for each cell --- Dynamic Programming/distance_of_nearest_0.py | 79 ++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Dynamic Programming/distance_of_nearest_0.py diff --git a/Dynamic Programming/distance_of_nearest_0.py b/Dynamic Programming/distance_of_nearest_0.py new file mode 100644 index 00000000..edc5ac00 --- /dev/null +++ b/Dynamic Programming/distance_of_nearest_0.py @@ -0,0 +1,79 @@ +'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + + + +Example 1: + + +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +Example 2: + + +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] + + +Constraints: + +m == mat.length +n == mat[i].length +1 <= m, n <= 104 +1 <= m * n <= 104 +mat[i][j] is either 0 or 1. +There is at least one 0 in mat. + +Explanation: + +In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. + +We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. + +If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. + +Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. + +When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. + +''' + +class TreeNode: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +def constructBST(preorder): + if not preorder: + return None + + root = TreeNode(preorder[0]) + stack = [root] + + for val in preorder[1:]: + node = TreeNode(val) + + if val < stack[-1].val: + stack[-1].left = node + else: + while stack and val > stack[-1].val: + last = stack.pop() + last.right = node + + stack.append(node) + + return root + +def inorderTraversal(root): + if root: + inorderTraversal(root.left) + print(root.val, end=' ') + inorderTraversal(root.right) + +preorder = [10, 4, 2, 1, 5, 17, 19, 18] +root = constructBST(preorder) + +# Verify the constructed BST by performing an in-order traversal +inorderTraversal(root) \ No newline at end of file From 9292cd45d2e798195f3448594e2cf3d00e4cb2be Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 14:04:48 +0000 Subject: [PATCH 1149/1894] In this repository our approach is basically to utilize a stack to keep the track of nodes while constructing the binary search tree from pre-order traversal. --- Dynamic Programming/distance_of_nearest_0.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Dynamic Programming/distance_of_nearest_0.py b/Dynamic Programming/distance_of_nearest_0.py index edc5ac00..3cc1d0f2 100644 --- a/Dynamic Programming/distance_of_nearest_0.py +++ b/Dynamic Programming/distance_of_nearest_0.py @@ -27,15 +27,24 @@ Explanation: -In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. +In this Python implementation, we define a TreeNode class to represent each node in the binary tree. + The constructBST function takes the pre-order traversal array as input and returns the root node of + the constructed BST. -We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. +We create the root node using the first element of the pre-order array and also initialize a stack +with the root node. Then, for each element in the pre-order array (starting from the second element), +we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. -If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. +If the value is less than the top of the stack, we add it as the left child of the top node. +Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. + The last popped node becomes the parent of the new node and we add the new node as its right child. -Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. +Finally, we return the root node of the constructed BST. The inorderTraversal functionis used to +verify the correctness of the construction by performing an in-order traversal of the BST and +printing the values. -When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. +When executed, this code will output the in-order traversal of the constructed BST, which should + match the expected output you provided. ''' From a1ecaec5e75f1e1de31b11ce43190499796ae3f0 Mon Sep 17 00:00:00 2001 From: Akrati Singh <94162536+Coding-whiz@users.noreply.github.com> Date: Sat, 20 May 2023 20:00:09 +0530 Subject: [PATCH 1150/1894] Add files via upload #1006 In this repository our approach is basically to utilize a stack to keep the track of nodes while constructing the binary search tree from pre-order traversal. --- distance_of_nearest_0.py | 79 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 distance_of_nearest_0.py diff --git a/distance_of_nearest_0.py b/distance_of_nearest_0.py new file mode 100644 index 00000000..edc5ac00 --- /dev/null +++ b/distance_of_nearest_0.py @@ -0,0 +1,79 @@ +'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. + +The distance between two adjacent cells is 1. + + + +Example 1: + + +Input: mat = [[0,0,0],[0,1,0],[0,0,0]] +Output: [[0,0,0],[0,1,0],[0,0,0]] +Example 2: + + +Input: mat = [[0,0,0],[0,1,0],[1,1,1]] +Output: [[0,0,0],[0,1,0],[1,2,1]] + + +Constraints: + +m == mat.length +n == mat[i].length +1 <= m, n <= 104 +1 <= m * n <= 104 +mat[i][j] is either 0 or 1. +There is at least one 0 in mat. + +Explanation: + +In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. + +We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. + +If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. + +Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. + +When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. + +''' + +class TreeNode: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +def constructBST(preorder): + if not preorder: + return None + + root = TreeNode(preorder[0]) + stack = [root] + + for val in preorder[1:]: + node = TreeNode(val) + + if val < stack[-1].val: + stack[-1].left = node + else: + while stack and val > stack[-1].val: + last = stack.pop() + last.right = node + + stack.append(node) + + return root + +def inorderTraversal(root): + if root: + inorderTraversal(root.left) + print(root.val, end=' ') + inorderTraversal(root.right) + +preorder = [10, 4, 2, 1, 5, 17, 19, 18] +root = constructBST(preorder) + +# Verify the constructed BST by performing an in-order traversal +inorderTraversal(root) \ No newline at end of file From 6e07ed401e1ac162714bf2152426f18a0366fa7d Mon Sep 17 00:00:00 2001 From: Manmay Ghosh Date: Sun, 21 May 2023 11:16:09 +0530 Subject: [PATCH 1151/1894] Create Graphs_kruskals_algo.cpp A MST is created by Following Kruskal's algorithm --- Graphs/Graphs_kruskals_algo.cpp | 130 ++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Graphs/Graphs_kruskals_algo.cpp diff --git a/Graphs/Graphs_kruskals_algo.cpp b/Graphs/Graphs_kruskals_algo.cpp new file mode 100644 index 00000000..f6f77aa0 --- /dev/null +++ b/Graphs/Graphs_kruskals_algo.cpp @@ -0,0 +1,130 @@ +/* +Name : MAnmay Ghosh +Github username : ManmayGhosh +Repository name : data-structures-and-algorithms +Problem : Implement Kruskal's algorithm in C++ +Issue Number : #1301 + +Explanation of the below C++ code : + +In this implementation, we have a dijkstra function that takes a graph represented as an adjacency list, the starting node, and the total number of nodes. It returns a vector containing the shortest distances from the start node to all other nodes. + +The dijkstra function initializes all distances to infinity except for the start node, which is set to 0. It uses a min heap priority queue to process nodes based on their distances. The algorithm iteratively selects the node with the minimum distance, updates the distances of its neighbors if a shorter path is found, and adds them to the priority queue. + +In the main function, we create a graph using the adjacency list representation. Each element of the graph vector is a vector of pairs, where the first element of the pair represents the neighbor node, and the second element represents the weight of the edge. + +We then call the dijkstra function with the graph, starting node, and the total number of nodes. Finally, we print the shortest distances from the start node to all other nodes. + +-------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ +*/ + +#include +using namespace std; + +// DS data structure +// path compression + rank by union +class D_S { + int* parent; + int* rank; + +public: + D_S(int n) + { + parent = new int[n]; + rank = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = -1; + rank[i] = 1; + } + } + + // Find function + int find(int i) + { + if (parent[i] == -1) + return i; + return parent[i] = find(parent[i]); + } + + // Union function + void unite(int x, int y) + { + int s1 = find(x); + int s2 = find(y); + + if (s1 != s2) { + if (rank[s1] < rank[s2]) + parent[s1] = s2; + else if (rank[s1] > rank[s2]) + parent[s2] = s1; + else { + parent[s2] = s1; + rank[s1] += 1; + } + } + } +}; + +class Graph { + vector> edgelist; + int V; + +public: + Graph(int V) { this->V = V; } + + // Function to add edge in a graph + void addEdge(int x, int y, int w) + { + edgelist.push_back({ w, x, y }); + } + + void kruskals_mst() + { + // Arrange all edges in ascending order to find minimum weight edge + sort(edgelist.begin(), edgelist.end()); + + // Initialize the DSU + D_S gr(V); + int ans = 0; + cout << "Following are the edges in the constructed MST"<< endl; + for (auto edge : edgelist) { + int w = edge[0]; + int x = edge[1]; + int y = edge[2]; + + // Take the edge in MST if it does not forms a cycle + if (gr.find(x) != gr.find(y)) { + gr.unite(x, y); + ans += w; + cout << x << " -- " << y << " == " << w<< endl; + } + } + cout << "Minimum Cost Spanning Tree: " << ans; + } +}; + +// Driver code +int main() +{ + Graph g(4); + g.addEdge(0, 1, 10); + g.addEdge(1, 3, 15); + g.addEdge(2, 3, 4); + g.addEdge(2, 0, 6); + g.addEdge(0, 3, 5); + + // Function call + g.kruskals_mst(); + + return 0; +} + + +/* +Time Complexity: O(E * logE) or O(E * logV) + +Sorting of edges takes O(E * logE) time. +After sorting, we iterate through all edges and apply the find-union algorithm. The find and union operations can take at most O(logV) time. +So overall complexity is O(E * logE + E * logV) time. +The value of E can be at most O(V2), so O(logV) and O(logE) are the same. Therefore, the overall time complexity is O(E * logE) or O(E*logV). +*/ \ No newline at end of file From b9d7bb972bc54de9ee11b744fa39e1b7327b9cc3 Mon Sep 17 00:00:00 2001 From: Manmay Ghosh Date: Sun, 21 May 2023 11:33:07 +0530 Subject: [PATCH 1152/1894] Update Graphs_kruskals_algo.cpp --- Graphs/Graphs_kruskals_algo.cpp | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Graphs/Graphs_kruskals_algo.cpp b/Graphs/Graphs_kruskals_algo.cpp index f6f77aa0..f95733dc 100644 --- a/Graphs/Graphs_kruskals_algo.cpp +++ b/Graphs/Graphs_kruskals_algo.cpp @@ -7,14 +7,16 @@ Issue Number : #1301 Explanation of the below C++ code : -In this implementation, we have a dijkstra function that takes a graph represented as an adjacency list, the starting node, and the total number of nodes. It returns a vector containing the shortest distances from the start node to all other nodes. - -The dijkstra function initializes all distances to infinity except for the start node, which is set to 0. It uses a min heap priority queue to process nodes based on their distances. The algorithm iteratively selects the node with the minimum distance, updates the distances of its neighbors if a shorter path is found, and adds them to the priority queue. - -In the main function, we create a graph using the adjacency list representation. Each element of the graph vector is a vector of pairs, where the first element of the pair represents the neighbor node, and the second element represents the weight of the edge. - -We then call the dijkstra function with the graph, starting node, and the total number of nodes. Finally, we print the shortest distances from the start node to all other nodes. +In this implementation, In Kruskal’s algorithm, sort all edges of the given graph in increasing order. +Then it keeps on adding new edges and nodes in the MST if the newly added edge does not form a cycle. +It picks the minimum weighted edge at first at the maximum weighted edge at last. +Thus we can say that it makes a locally optimal choice in each step in order to find the optimal solution +pseudosteps +1. Sort all the edges in non-decreasing order of their weight. +2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. + If the cycle is not formed, include this edge. Else, discard it. +3. Repeat step#2 until there are (V-1) edges in the spanning tree. -------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ */ @@ -22,19 +24,18 @@ We then call the dijkstra function with the graph, starting node, and the total using namespace std; // DS data structure -// path compression + rank by union class D_S { int* parent; - int* rank; + int* child; public: D_S(int n) { parent = new int[n]; - rank = new int[n]; + child = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; - rank[i] = 1; + child[i] = 1; } } @@ -53,13 +54,13 @@ class D_S { int s2 = find(y); if (s1 != s2) { - if (rank[s1] < rank[s2]) + if (child[s1] < child[s2]) parent[s1] = s2; - else if (rank[s1] > rank[s2]) + else if (child[s1] > child[s2]) parent[s2] = s1; else { parent[s2] = s1; - rank[s1] += 1; + child[s1] += 1; } } } From a028b3ce5a0a4a7dc16ca6072e80a7cf11cb99ad Mon Sep 17 00:00:00 2001 From: ChiragAgg5k Date: Sun, 21 May 2023 12:39:49 +0530 Subject: [PATCH 1153/1894] added A* algorithm in python --- Graphs/A*_algorithm.py | 160 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 Graphs/A*_algorithm.py diff --git a/Graphs/A*_algorithm.py b/Graphs/A*_algorithm.py new file mode 100644 index 00000000..47ec9840 --- /dev/null +++ b/Graphs/A*_algorithm.py @@ -0,0 +1,160 @@ +""" +A* Algorithm + +Motivation - To approximate the shortest path in real-life situations, like- in maps, games where there can be many hindrances. + +Unlike other traversal techniques which focus on the path to be taken, A* algorithm focuses on the distance to be travelled. +It is a combination of Uniform Cost Search(UCS) and Best First Search(BFS). + +Explanation +A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. +heuristic means guess or estimate. + +Consider a square grid having many obstacles and we are given a starting cell and a target cell. We want to reach the target cell (if possible) from the starting cell as quickly as possible. + +Here g(n) is the distance between the current cell and the start cell. So we can say g(n) is the cost of the path from initial state to n. +h(n) is a heuristic function that is used to estimate the cost of the cheapest path from n to the goal. So we can say h(n) is the cost from n to goal. + +So we can say f(n) is the cost of the cheapest path from initial state to goal passing through n. + +pseudocode +1. Initialize the open list +2. Initialize the closed list +put the starting node on the open list (you can leave its f at zero) + +3. while the open list is not empty + a) find the node with the least f on the open list, call it "q" + b) pop q off the open list + c) generate q's 8 successors and set their parents to q + d) for each successor + i) if successor is the goal, stop search + + ii) else, compute both g and h for successor + successor.g = q.g + distance between successor and q + successor.h = distance from goal to successor + successor.f = successor.g + successor.h + + iii) if a node with the same position as successor is in the OPEN list which has a lower f than successor, skip this successor + + iv) if a node with the same position as successor is in the CLOSED list which has a lower f than successor, skip this successor + otherwise, add the node to the open list + + e) push q on the closed list + +For more information, visit: https://www.geeksforgeeks.org/a-search-algorithm/ or https://stackabuse.com/courses/graphs-in-python-theory-and-implementation/lessons/a-star-search-algorithm/ + +""" + +from collections import deque + + +class Graph: + # example of adjacency list (or rather map) + # adjacency_list = { + # 'A': [('B', 1), ('C', 3), ('D', 7)], + # 'B': [('D', 5)], + # 'C': [('D', 12)] + # } + + def __init__(self, adjacency_list): + self.adjacency_list = adjacency_list + + def get_neighbors(self, v): + return self.adjacency_list[v] + + # heuristic function with equal values for all nodes + def h(self, n): + H = {"A": 1, "B": 1, "C": 1, "D": 1} + + return H[n] + + def a_star_algorithm(self, start_node, stop_node): + # open_list is a list of nodes which have been visited, but who's neighbors + # haven't all been inspected, starts off with the start node + # closed_list is a list of nodes which have been visited + # and who's neighbors have been inspected + open_list = set([start_node]) + closed_list = set([]) + + # g contains current distances from start_node to all other nodes + # the default value (if it's not found in the map) is +infinity + g = {} + + g[start_node] = 0 + + # parents contains an adjacency map of all nodes + parents = {} + parents[start_node] = start_node + + while len(open_list) > 0: + n = None + + # find a node with the lowest value of f() - evaluation function + for v in open_list: + if n == None or g[v] + self.h(v) < g[n] + self.h(n): + n = v + + if n == None: + print("Path does not exist!") + return None + + # if the current node is the stop_node + # then we begin reconstructin the path from it to the start_node + if n == stop_node: + reconst_path = [] + + while parents[n] != n: + reconst_path.append(n) + n = parents[n] + + reconst_path.append(start_node) + + reconst_path.reverse() + + print("Path found: {}".format(reconst_path)) + return reconst_path + + # for all neighbors of the current node do + for m, weight in self.get_neighbors(n): + # if the current node isn't in both open_list and closed_list + # add it to open_list and note n as it's parent + if m not in open_list and m not in closed_list: + open_list.add(m) + parents[m] = n + g[m] = g[n] + weight + + # otherwise, check if it's quicker to first visit n, then m + # and if it is, update parent data and g data + # and if the node was in the closed_list, move it to open_list + else: + if g[m] > g[n] + weight: + g[m] = g[n] + weight + parents[m] = n + + if m in closed_list: + closed_list.remove(m) + open_list.add(m) + + # remove n from the open_list, and add it to closed_list + # because all of his neighbors were inspected + open_list.remove(n) + closed_list.add(n) + + print("Path does not exist!") + return None + + +# Driver code + +adjacency_list = { + "A": [("B", 1), ("C", 3), ("D", 7)], + "B": [("D", 5)], + "C": [("D", 12)], +} + +graph1 = Graph(adjacency_list) +graph1.a_star_algorithm("A", "D") + +# Output: +# Path found: ['A', 'B', 'D'] +# Explanation: The path with the lowest cost is A -> B -> D with a cost of 6. From 1ccd8c7a60c98831ca5d06815ece6ab0ec1007e3 Mon Sep 17 00:00:00 2001 From: arsallanShahab Date: Sun, 21 May 2023 13:41:36 +0530 Subject: [PATCH 1154/1894] Updated documentation for Knuth-Morris-Pratt (KMP) algorithm in Java --- Graphs/Graph_KMPAlgorithm.java | 37 +++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/Graphs/Graph_KMPAlgorithm.java b/Graphs/Graph_KMPAlgorithm.java index a8f1a3c5..ee97dcb1 100644 --- a/Graphs/Graph_KMPAlgorithm.java +++ b/Graphs/Graph_KMPAlgorithm.java @@ -1,17 +1,34 @@ -/* - * KMP Algorithm for Pattern Searching +/** + * Summary: + * This program implements the Knuth-Morris-Pratt (KMP) algorithm for string pattern matching. + * Given a text string and a pattern string, the algorithm searches for the pattern in the text and returns + * the index where the pattern is found in the text. If the pattern is not found, it returns -1. * - * Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function - * search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. - * You may assume that n > m. + * Inputs: + * The program expects two strings as inputs: text and pattern. * - * Examples: + * Outputs: + * The output of the program is the index where the pattern is found in the text, or -1 if the pattern is not found. * - * Input: txt[] = "THIS IS A TEST TEXT" - * pat[] = "TEST" + * Example Usage: + * // Input + * String text = "ABABDABACDABABCABAB"; + * String pattern = "ABABCABAB"; * - * Output: Pattern found at index 10 - * + * // Execute the KMP algorithm for string pattern matching + * int index = searchPattern(text, pattern); + * + * // Output + * if (index != -1) { + * System.out.println("Pattern found at index: " + index); + * } else { + * System.out.println("Pattern not found in the text."); + * } + * + * Complexity Analysis: + * The time complexity of the KMP algorithm is O(n + m), where n is the length of the text and m is the length of the pattern. + * This is because the algorithm avoids unnecessary comparisons by utilizing the computed Longest Proper Prefix-Suffix (LPS) array. + * The space complexity is O(m) as it requires storing the LPS array of the pattern. */ public class Graph_KMPAlgorithm { From e707affb6dc0dccccc9305e4a1633ae38408c240 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Sun, 21 May 2023 16:56:48 +0530 Subject: [PATCH 1155/1894] implemented bucket sort --- sorting/BucketSort.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 sorting/BucketSort.cpp diff --git a/sorting/BucketSort.cpp b/sorting/BucketSort.cpp new file mode 100644 index 00000000..32879eb7 --- /dev/null +++ b/sorting/BucketSort.cpp @@ -0,0 +1,53 @@ +/*The code implements the bucket sort algorithm in C++. It defines a bucketSort function that takes a vector of integers as input and sorts it using the bucket sort technique. The algorithm distributes the elements into separate buckets based on their values, sorts each bucket individually, and then concatenates the sorted buckets to obtain the final sorted array.*/ +/*Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case. +The space complexity of bucket sort is O(n + k)*/ +#include +#include +#include + +using namespace std; + +void bucketSort(vector& arr) { + // Find the maximum value in the array to determine the range of buckets + int max_value = *max_element(arr.begin(), arr.end()); + + // Calculate the number of buckets needed + int num_buckets = max_value + 1; + + // Create empty buckets + vector> buckets(num_buckets); + + // Distribute the elements into buckets + for (int num : arr) { + buckets[num].push_back(num); + } + + // Sort each bucket individually + for (auto& bucket : buckets) { + sort(bucket.begin(), bucket.end()); + } + + // Concatenate the sorted buckets to get the sorted array + int index = 0; + for (const auto& bucket : buckets) { + for (int num : bucket) { + arr[index++] = num; + } + } +} + +int main() { + // Create an array of integers + vector array = {5, 3, 9, 1, 8, 2, 7, 4, 6}; + + // Sort the array using bucket sort + bucketSort(array); + + // Print the sorted array + for (int num : array) { + cout << num << " "; + } + cout << endl; + + return 0; +} From 353e9a4f432e7147d9cb1f7d07a7a7fd1fad80e2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:07:50 +0530 Subject: [PATCH 1156/1894] add is_balanced in go --- Trees/Binary Trees/is_balanced.go | 101 ++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Trees/Binary Trees/is_balanced.go diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go new file mode 100644 index 00000000..37209063 --- /dev/null +++ b/Trees/Binary Trees/is_balanced.go @@ -0,0 +1,101 @@ +package main + +import "fmt" + +// This is an input class. Do not edit. +type BinaryTree struct { + Value int + + Left *BinaryTree + Right *BinaryTree +} + +type TreeeInfo struct { + isBalanced bool + height int +} + +// HeightBalancedBinaryTree checks if a binary tree is height-balanced. +func HeightBalancedBinaryTree(tree *BinaryTree) bool { + // Retrieve the tree information using the helper function. + treeInfo := getTreeInfo(tree) + + // Return the balance status of the tree. + return treeInfo.isBalanced +} + +// getTreeInfo retrieves the information of a binary tree, including its balance status and height. +func getTreeInfo(tree *BinaryTree) TreeeInfo { + // Base case: If the tree is nil, it is considered balanced with height -1. + if tree == nil { + return TreeeInfo{isBalanced: true, height: -1} + } + + // Recursively calculate the tree information of the left and right subtrees. + leftSubtreeInfo := getTreeInfo(tree.Left) + rightSubtreeInfo := getTreeInfo(tree.Right) + + // Check if both left and right subtrees are balanced and their height difference is at most 1. + isBalanced := leftSubtreeInfo.isBalanced && rightSubtreeInfo.isBalanced && + abs(leftSubtreeInfo.height-rightSubtreeInfo.height) <= 1 + + // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1. + height := max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1 + + // Create and return the tree information. + return TreeeInfo{ + isBalanced: isBalanced, + height: height, + } +} + +// max returns the maximum of two integers. +func max(a, b int) int { + if a > b { + return a + } + return b +} + +// abs returns the absolute value of an integer. +func abs(a int) int { + if a < 0 { + return -a + } + return a +} + +func main() { + // Create a binary tree + tree := &BinaryTree{ + Value: 1, + Left: &BinaryTree{ + Value: 2, + Left: &BinaryTree{ + Value: 4, + }, + Right: &BinaryTree{ + Value: 5, + }, + }, + Right: &BinaryTree{ + Value: 3, + Right: &BinaryTree{ + Value: 6, + Left: &BinaryTree{ + Value: 7, + }, + }, + }, + } + + // Check if the binary tree is height-balanced + isBalanced := HeightBalancedBinaryTree(tree) + + // Output the result + if isBalanced { + fmt.Println("The binary tree is height-balanced.") + } else { + fmt.Println("The binary tree is not height-balanced.") + } +} From 667f2ece6cdabb4202f757a1e3266c35d7604d61 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:09:08 +0530 Subject: [PATCH 1157/1894] add question --- Trees/Binary Trees/is_balanced.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go index 37209063..966bbf36 100644 --- a/Trees/Binary Trees/is_balanced.go +++ b/Trees/Binary Trees/is_balanced.go @@ -1,3 +1,15 @@ +/* + You're given the root node of a Binary Tree. Write a function that returns true if this Binary Tree is height balanced and + false if it isn't. + +*/ + 1 + / \ + 2 3 + / \ \ + 4 5 6 + / + 7 package main import "fmt" From f824282761c3eb3912e757a812eb691f9df84c49 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:09:49 +0530 Subject: [PATCH 1158/1894] add sample io --- Trees/Binary Trees/is_balanced.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go index 966bbf36..309759af 100644 --- a/Trees/Binary Trees/is_balanced.go +++ b/Trees/Binary Trees/is_balanced.go @@ -3,13 +3,7 @@ false if it isn't. */ - 1 - / \ - 2 3 - / \ \ - 4 5 6 - / - 7 + package main import "fmt" From ddf1a7a58a469fad73bbb3aa12a996792e5f089c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:09:54 +0530 Subject: [PATCH 1159/1894] add sample io --- Trees/Binary Trees/is_balanced.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go index 309759af..9b53ae91 100644 --- a/Trees/Binary Trees/is_balanced.go +++ b/Trees/Binary Trees/is_balanced.go @@ -1,6 +1,15 @@ /* You're given the root node of a Binary Tree. Write a function that returns true if this Binary Tree is height balanced and false if it isn't. + Sample Input: + 1 + / \ + 2 3 + / \ \ + 4 5 6 + / + 7 + Output: False */ From 40cdfb59594480b04bdee393ba6ec321f73b10d3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:11:30 +0530 Subject: [PATCH 1160/1894] add explanation --- Trees/Binary Trees/is_balanced.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go index 9b53ae91..42ceb8d0 100644 --- a/Trees/Binary Trees/is_balanced.go +++ b/Trees/Binary Trees/is_balanced.go @@ -1,4 +1,4 @@ -/* +/* You're given the root node of a Binary Tree. Write a function that returns true if this Binary Tree is height balanced and false if it isn't. Sample Input: @@ -9,9 +9,31 @@ 4 5 6 / 7 - Output: False - -*/ + Output: False + + Explanation: + + The code checks whether a given binary tree is height-balanced or not. A binary tree is height-balanced if + the heights of its left and right subtrees differ by at most 1, and both the left and right subtrees + are themselves height-balanced. + + The HeightBalancedBinaryTree function is the entry point of the code. It calls the getTreeInfo helper + function to retrieve the tree information, including the balance status and height. + + The getTreeInfo function recursively calculates the tree information of the current node by + obtaining the tree information of its left and right subtrees. It checks if both subtrees are + balanced and calculates the height of the current tree. + + The balance status is determined by checking if the left and right subtrees are balanced and if their + height difference is at most 1. + + The height of the current tree is the maximum height between the left and right subtrees plus 1. + + The max function returns the maximum of two integers, and the abs function returns the absolute value of an integer. + These helper functions are used in the main logic of the code. + + Overall, the code efficiently determines whether a binary tree is height-balanced by recursively calculating the tree information and checking the balance status based on height differences. +*/ package main From f8fe6c9630a1feead2f0a7489fb74fc3b0fdb221 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 21 May 2023 18:13:02 +0530 Subject: [PATCH 1161/1894] add time and space --- Trees/Binary Trees/is_balanced.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go index 42ceb8d0..83cc4942 100644 --- a/Trees/Binary Trees/is_balanced.go +++ b/Trees/Binary Trees/is_balanced.go @@ -33,6 +33,22 @@ These helper functions are used in the main logic of the code. Overall, the code efficiently determines whether a binary tree is height-balanced by recursively calculating the tree information and checking the balance status based on height differences. + + The time complexity of the `HeightBalancedBinaryTree` function, which calls the `getTreeInfo` helper function, is O(n), where n is the number of nodes in the binary tree. + This is because the function traverses each node once in a depth-first manner, calculating the tree information for each node. + + The space complexity is O(h), where h is the height of the binary tree. This is because the recursive calls consume memory on the call + stack proportional to the height of the tree. In the worst case, for a skewed tree where the height is equal to the number of nodes, + the space complexity would be O(n). + + However, in a balanced binary tree, the height is logarithmic in the number of nodes, resulting in a space complexity of O(log n). + + Additionally, the `max` and `abs` helper functions have constant time complexity as they perform simple + mathematical operations on two integers. They do not depend on the size of the tree. + + Overall, the time complexity is O(n) and the space complexity is O(h) or O(log n) in the case of a + balanced binary tree. + */ package main From c605efac22fb1e88bfa16416186cd43512e23fe7 Mon Sep 17 00:00:00 2001 From: Kumar Rajeev <117367016+Kumar-Raajeev@users.noreply.github.com> Date: Sun, 21 May 2023 19:19:35 +0530 Subject: [PATCH 1162/1894] Added the qustion to the solution #1006 --- Dynamic Programming/distance_of_nearest_0.py | 126 +++++++-------- Graphs/A*_algorithm.py | 160 ------------------- 2 files changed, 59 insertions(+), 227 deletions(-) delete mode 100644 Graphs/A*_algorithm.py diff --git a/Dynamic Programming/distance_of_nearest_0.py b/Dynamic Programming/distance_of_nearest_0.py index 3cc1d0f2..71ea55ff 100644 --- a/Dynamic Programming/distance_of_nearest_0.py +++ b/Dynamic Programming/distance_of_nearest_0.py @@ -1,23 +1,15 @@ -'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. - +''' +Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. - - Example 1: - - Input: mat = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,1,0],[0,0,0]] Example 2: - - Input: mat = [[0,0,0],[0,1,0],[1,1,1]] Output: [[0,0,0],[0,1,0],[1,2,1]] - Constraints: - m == mat.length n == mat[i].length 1 <= m, n <= 104 @@ -25,64 +17,64 @@ mat[i][j] is either 0 or 1. There is at least one 0 in mat. -Explanation: - -In this Python implementation, we define a TreeNode class to represent each node in the binary tree. - The constructBST function takes the pre-order traversal array as input and returns the root node of - the constructed BST. - -We create the root node using the first element of the pre-order array and also initialize a stack -with the root node. Then, for each element in the pre-order array (starting from the second element), -we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. - -If the value is less than the top of the stack, we add it as the left child of the top node. -Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. - The last popped node becomes the parent of the new node and we add the new node as its right child. - -Finally, we return the root node of the constructed BST. The inorderTraversal functionis used to -verify the correctness of the construction by performing an in-order traversal of the BST and -printing the values. - -When executed, this code will output the in-order traversal of the constructed BST, which should - match the expected output you provided. +Intuition +The goal is to get the nearest 0 for each 1. So how can we get the nearest 0 for each 1? Lets use Multisource BFS and Dynamic Programming. +Approach +To get the nearest 0 for each 1, we should treat every 0 as if they are on the same level, make a BFS on them and keep track of the distance as we go further. Since we are finding the nearest zero, we may need to use pre-calculated distances for the current 1 when all of its neighbours are all 1. +Lets see this with example! +Here is the given grid. + 0 0 0 + 0 1 0 + 1 1 1 +Then by taking all zeros and making a BFS on them, the nearest distance becomes 1 for all ones other than the back ticked 1 found on the third row. + 0 0 0 + 0 1 0 + 1 `1` 1 +The back ticked '1' is not adjacent to 0, so it should use the precalculated distance of the nearest 1 it get. +So, in here we are using precalculated values to get the nearest distance. This technique is called Dynamic programming. +Then we will get this grid by using the values we calculated for its adjacent 1 + 0 0 0 + 0 1 0 + 1 2 1 +Complexity +Time complexity: O(N) +Space complexity: O(V + E) +Code +sample input and output: + +1. Input: mat = [[0,0,0],[0,1,0],[0,0,0]] + Output: [[0,0,0],[0,1,0],[0,0,0]] ''' - -class TreeNode: - def __init__(self, val): - self.val = val - self.left = None - self.right = None - -def constructBST(preorder): - if not preorder: - return None - - root = TreeNode(preorder[0]) - stack = [root] - - for val in preorder[1:]: - node = TreeNode(val) +class Solution: + def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: - if val < stack[-1].val: - stack[-1].left = node - else: - while stack and val > stack[-1].val: - last = stack.pop() - last.right = node + # it a Multi-source BFS like 994. Rotting Oranges + # treat every 0 as if they are on the same level and make BFS on them + def isvalid(row, col): + if row >= len(mat) or row < 0 or col >= len(mat[0]) or col < 0: + return False + return True - stack.append(node) - - return root - -def inorderTraversal(root): - if root: - inorderTraversal(root.left) - print(root.val, end=' ') - inorderTraversal(root.right) - -preorder = [10, 4, 2, 1, 5, 17, 19, 18] -root = constructBST(preorder) - -# Verify the constructed BST by performing an in-order traversal -inorderTraversal(root) \ No newline at end of file + # get every zero and add them to a queue + q, visited = deque(), set() + for row in range( len(mat)): + for col in range( len(mat[0])): + if mat[row][col] == 0: + q.append([row, col]) + visited.add((row, col)) + + level = 1 # the distance to the nearest zero starts from 1 + while q: + size = len(q) + for _ in range( size ): + row, col =q.popleft() + for r, c in [ [1, 0], [-1, 0], [0, 1], [0, -1]]: + newRow, newCol = row + r, col + c + if (newRow, newCol) not in visited and isvalid(newRow, newCol): + mat[newRow][newCol] = level + q.append([newRow, newCol]) + visited.add( (newRow, newCol)) + level += 1 + + return mat \ No newline at end of file diff --git a/Graphs/A*_algorithm.py b/Graphs/A*_algorithm.py deleted file mode 100644 index 47ec9840..00000000 --- a/Graphs/A*_algorithm.py +++ /dev/null @@ -1,160 +0,0 @@ -""" -A* Algorithm - -Motivation - To approximate the shortest path in real-life situations, like- in maps, games where there can be many hindrances. - -Unlike other traversal techniques which focus on the path to be taken, A* algorithm focuses on the distance to be travelled. -It is a combination of Uniform Cost Search(UCS) and Best First Search(BFS). - -Explanation -A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. -heuristic means guess or estimate. - -Consider a square grid having many obstacles and we are given a starting cell and a target cell. We want to reach the target cell (if possible) from the starting cell as quickly as possible. - -Here g(n) is the distance between the current cell and the start cell. So we can say g(n) is the cost of the path from initial state to n. -h(n) is a heuristic function that is used to estimate the cost of the cheapest path from n to the goal. So we can say h(n) is the cost from n to goal. - -So we can say f(n) is the cost of the cheapest path from initial state to goal passing through n. - -pseudocode -1. Initialize the open list -2. Initialize the closed list -put the starting node on the open list (you can leave its f at zero) - -3. while the open list is not empty - a) find the node with the least f on the open list, call it "q" - b) pop q off the open list - c) generate q's 8 successors and set their parents to q - d) for each successor - i) if successor is the goal, stop search - - ii) else, compute both g and h for successor - successor.g = q.g + distance between successor and q - successor.h = distance from goal to successor - successor.f = successor.g + successor.h - - iii) if a node with the same position as successor is in the OPEN list which has a lower f than successor, skip this successor - - iv) if a node with the same position as successor is in the CLOSED list which has a lower f than successor, skip this successor - otherwise, add the node to the open list - - e) push q on the closed list - -For more information, visit: https://www.geeksforgeeks.org/a-search-algorithm/ or https://stackabuse.com/courses/graphs-in-python-theory-and-implementation/lessons/a-star-search-algorithm/ - -""" - -from collections import deque - - -class Graph: - # example of adjacency list (or rather map) - # adjacency_list = { - # 'A': [('B', 1), ('C', 3), ('D', 7)], - # 'B': [('D', 5)], - # 'C': [('D', 12)] - # } - - def __init__(self, adjacency_list): - self.adjacency_list = adjacency_list - - def get_neighbors(self, v): - return self.adjacency_list[v] - - # heuristic function with equal values for all nodes - def h(self, n): - H = {"A": 1, "B": 1, "C": 1, "D": 1} - - return H[n] - - def a_star_algorithm(self, start_node, stop_node): - # open_list is a list of nodes which have been visited, but who's neighbors - # haven't all been inspected, starts off with the start node - # closed_list is a list of nodes which have been visited - # and who's neighbors have been inspected - open_list = set([start_node]) - closed_list = set([]) - - # g contains current distances from start_node to all other nodes - # the default value (if it's not found in the map) is +infinity - g = {} - - g[start_node] = 0 - - # parents contains an adjacency map of all nodes - parents = {} - parents[start_node] = start_node - - while len(open_list) > 0: - n = None - - # find a node with the lowest value of f() - evaluation function - for v in open_list: - if n == None or g[v] + self.h(v) < g[n] + self.h(n): - n = v - - if n == None: - print("Path does not exist!") - return None - - # if the current node is the stop_node - # then we begin reconstructin the path from it to the start_node - if n == stop_node: - reconst_path = [] - - while parents[n] != n: - reconst_path.append(n) - n = parents[n] - - reconst_path.append(start_node) - - reconst_path.reverse() - - print("Path found: {}".format(reconst_path)) - return reconst_path - - # for all neighbors of the current node do - for m, weight in self.get_neighbors(n): - # if the current node isn't in both open_list and closed_list - # add it to open_list and note n as it's parent - if m not in open_list and m not in closed_list: - open_list.add(m) - parents[m] = n - g[m] = g[n] + weight - - # otherwise, check if it's quicker to first visit n, then m - # and if it is, update parent data and g data - # and if the node was in the closed_list, move it to open_list - else: - if g[m] > g[n] + weight: - g[m] = g[n] + weight - parents[m] = n - - if m in closed_list: - closed_list.remove(m) - open_list.add(m) - - # remove n from the open_list, and add it to closed_list - # because all of his neighbors were inspected - open_list.remove(n) - closed_list.add(n) - - print("Path does not exist!") - return None - - -# Driver code - -adjacency_list = { - "A": [("B", 1), ("C", 3), ("D", 7)], - "B": [("D", 5)], - "C": [("D", 12)], -} - -graph1 = Graph(adjacency_list) -graph1.a_star_algorithm("A", "D") - -# Output: -# Path found: ['A', 'B', 'D'] -# Explanation: The path with the lowest cost is A -> B -> D with a cost of 6. From 0c4fb9db43337525cd5a2af25fa529937cc33611 Mon Sep 17 00:00:00 2001 From: arsallanShahab Date: Sun, 21 May 2023 23:47:08 +0530 Subject: [PATCH 1163/1894] Add implementation of Kruskal's Algorithm for Graphs in JavaScript --- Graphs/Graphs_kruskalsAlgorithm.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Graphs/Graphs_kruskalsAlgorithm.js diff --git a/Graphs/Graphs_kruskalsAlgorithm.js b/Graphs/Graphs_kruskalsAlgorithm.js new file mode 100644 index 00000000..e69de29b From f59f0b4141140b99953df6e5a5120dadf9d4ac24 Mon Sep 17 00:00:00 2001 From: Aniket Sonawane <72734761+aniketsona23@users.noreply.github.com> Date: Mon, 22 May 2023 01:05:34 +0530 Subject: [PATCH 1164/1894] Rename A*_algorithm.py to Astar_algorithm.py ->Changing 'A*_algorithm.py' to 'Astar_algorithm.py' Reason : special characters like ' * ' are not allowed in the file name. --- Graphs/{A*_algorithm.py => Astar_algorithm.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{A*_algorithm.py => Astar_algorithm.py} (100%) diff --git a/Graphs/A*_algorithm.py b/Graphs/Astar_algorithm.py similarity index 100% rename from Graphs/A*_algorithm.py rename to Graphs/Astar_algorithm.py From 195c690a79861edfe789a65ad40e4da8734febe9 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Mon, 22 May 2023 19:14:36 +0530 Subject: [PATCH 1165/1894] Implemented Monotonic Array Checking --- Arrays/Monotonic_Array.cpp | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Arrays/Monotonic_Array.cpp diff --git a/Arrays/Monotonic_Array.cpp b/Arrays/Monotonic_Array.cpp new file mode 100644 index 00000000..fc543019 --- /dev/null +++ b/Arrays/Monotonic_Array.cpp @@ -0,0 +1,45 @@ +/*The isMonotonic function takes a std::vector as input and iterates over the array to check if it is either strictly increasing or strictly decreasing. It uses two boolean variables, increasing and decreasing, to keep track of whether the array satisfies those conditions. If both variables remain true after the loop, it means the array is monotonic. The function returns true if the array is monotonic and false otherwise.*/ +/*The time complexity of the isMonotonic function is O(n) +The space complexity of the isMonotonic function is O(1)*/ + +#include +#include + +using namespace std; + +// Function to check if an array is monotonic +bool isMonotonic(const vector& array) { + const int size = array.size(); + bool increasing = true; + bool decreasing = true; + + // Iterate over the array + for (int i = 1; i < size; i++) { + // Check for non-increasing condition + if (array[i] < array[i - 1]) + increasing = false; + + // Check for non-decreasing condition + if (array[i] > array[i - 1]) + decreasing = false; + } + + // Return true if either increasing or decreasing condition holds + return increasing || decreasing; +} + +int main() { + vector arr1 = {1, 2, 3, 4, 5}; // Monotonic (Increasing) + vector arr2 = {5, 4, 3, 2, 1}; // Monotonic (Decreasing) + vector arr3 = {1, 2, 2, 3, 1}; // Not Monotonic + vector arr4 = {1, 1, 1, 1, 1}; // Monotonic (Increasing) + vector arr5 = {5, 5, 5, 5, 5}; // Monotonic (Increasing) + + cout << "Array 1 is monotonic: " << boolalpha << isMonotonic(arr1) << endl; + cout << "Array 2 is monotonic: " << boolalpha << isMonotonic(arr2) << endl; + cout << "Array 3 is monotonic: " << boolalpha << isMonotonic(arr3) << endl; + cout << "Array 4 is monotonic: " << boolalpha << isMonotonic(arr4) << endl; + cout << "Array 5 is monotonic: " << boolalpha << isMonotonic(arr5) << endl; + + return 0; +} From c5fe48387f060642c602193580f10b731cc9852f Mon Sep 17 00:00:00 2001 From: Suyashsingh Date: Mon, 22 May 2023 19:56:50 +0530 Subject: [PATCH 1166/1894] intial commit" suyash added " --- Math/K_closest.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Math/K_closest.cpp diff --git a/Math/K_closest.cpp b/Math/K_closest.cpp new file mode 100644 index 00000000..a23b4f25 --- /dev/null +++ b/Math/K_closest.cpp @@ -0,0 +1,63 @@ +/* +Expalination: + +Input: points = [[1,3],[-2,2]], k = 1 +Output: [[-2,2]] +Explanation: +The distance between (1, 3) and the origin is sqrt(10). +The distance between (-2, 2) and the origin is sqrt(8). +Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. +We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. +Example 2: +Input: points = [[3,3],[5,-1],[-2,4]], k = 2 +Output: [[3,3],[-2,4]] +Explanation: The answer [[-2,4],[3,3]] would also be accepted. +*/ + +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> kClosest(vector>& points, int k) { + // Answer vector + vector> result(k); + // Max heap storage initialization + priority_queue> maxHeap; + // Construction of max heap + for (auto& p : points) { + int x = p[0], y = p[1]; + maxHeap.push({x * x + y * y, x, y}); + if (maxHeap.size() > k) { + maxHeap.pop(); + } + } + + for (int i = k - 1; i >= 0; --i) { + vector top = maxHeap.top(); + maxHeap.pop(); + result[i] = {top[1], top[2]}; + } + + return result; + } +}; + +int main() { + vector> points = {{1, 3}, {-2, 2}, {5, -1}, {0, 0}, {3, 4}}; + int k = 3; + + Solution solution; + vector> closestPoints = solution.kClosest(points, k); + + cout << "The " << k << " closest points to the origin are:\n"; + for (const auto& point : closestPoints) { + cout << "(" << point[0] << ", " << point[1] << ")\n"; + } + + return 0; +} From 357be0438c02b3c6edabceabf06792c9c2eb4942 Mon Sep 17 00:00:00 2001 From: Sulabh Jha <66020896+sulabh007@users.noreply.github.com> Date: Mon, 22 May 2023 20:03:28 +0530 Subject: [PATCH 1167/1894] Add files via upload --- sorting/wave_sort.cpp | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 sorting/wave_sort.cpp diff --git a/sorting/wave_sort.cpp b/sorting/wave_sort.cpp new file mode 100644 index 00000000..77ae2b82 --- /dev/null +++ b/sorting/wave_sort.cpp @@ -0,0 +1,48 @@ +#include + +/* +In this sorting method we arrange array in +Arr[0] >=arr[1]<=arr[2]>=arr[3]<=arr[4]………. Like a wave +*/ + +using namespace std; + +void wavesort(int arr[], int n) +{ + for (int i = 1; i < n; i += 2) + { + if (arr[i] > arr[i - 1]) + { + swap(arr[i], arr[i - 1]); + } + if (arr[i] > arr[i + 1] && i <= n - 2) + { + swap(arr[i], arr[i + 1]); + } + } +} + +int main() +{ + int arr[9] = {1, 3, 4, 7, 5, 6, 2}; + wavesort(arr, 7); + for (int i = 0; i < 7; i++) + { + cout << arr[i] << " "; + } + return 0; +} + +/* +Time Complexity: O(N) +Auxiliary Space: O(1) +*/ + +/* +The idea is based on the fact that if we make sure that all even positioned (at index 0, 2, 4, ..) +elements are greater than their adjacent odd elements, we don’t need to worry about oddly positioned elements. + +- Traverse all even positioned elements of the input array, and do the following. + - If the current element is smaller than the previous odd element, swap the previous and current. + - If the current element is smaller than the next odd element, swap next and current. +*/ \ No newline at end of file From 3c22fbca6da24573f12ea1c0a646846602b26746 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:28:04 +0530 Subject: [PATCH 1168/1894] rename file --- Graphs/{Astar_algorithm.py => a_star_algorithm.py} | 0 Graphs/{Graph_KMPAlgorithm.java => knuth_morris_pratt.java} | 0 sorting/{BucketSort.cpp => bucket_sort.cpp} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Astar_algorithm.py => a_star_algorithm.py} (100%) rename Graphs/{Graph_KMPAlgorithm.java => knuth_morris_pratt.java} (100%) rename sorting/{BucketSort.cpp => bucket_sort.cpp} (100%) diff --git a/Graphs/Astar_algorithm.py b/Graphs/a_star_algorithm.py similarity index 100% rename from Graphs/Astar_algorithm.py rename to Graphs/a_star_algorithm.py diff --git a/Graphs/Graph_KMPAlgorithm.java b/Graphs/knuth_morris_pratt.java similarity index 100% rename from Graphs/Graph_KMPAlgorithm.java rename to Graphs/knuth_morris_pratt.java diff --git a/sorting/BucketSort.cpp b/sorting/bucket_sort.cpp similarity index 100% rename from sorting/BucketSort.cpp rename to sorting/bucket_sort.cpp From e483ed7114966442a349386b3d1b810873e3e4e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:29:44 +0530 Subject: [PATCH 1169/1894] add is symmetric recursive solution in go --- Trees/Binary Trees/is_symmetric.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Trees/Binary Trees/is_symmetric.go diff --git a/Trees/Binary Trees/is_symmetric.go b/Trees/Binary Trees/is_symmetric.go new file mode 100644 index 00000000..aee518ac --- /dev/null +++ b/Trees/Binary Trees/is_symmetric.go @@ -0,0 +1,28 @@ +package main + +// This is an input class. Do not edit. +type BinaryTree struct { + Value int + + Left *BinaryTree + Right *BinaryTree +} + +// SymmetricalTree checks if a binary tree is symmetrical. +func SymmetricalTree(tree *BinaryTree) bool { + // Call the helper function to check if the left and right subtrees are mirrored. + return treesAreMirrored(tree.Left, tree.Right) +} + +// treesAreMirrored checks if two binary trees are mirrored. +func treesAreMirrored(left, right *BinaryTree) bool { + // Base case: If both left and right trees are non-nil and have the same value, + // recursively check if their subtrees are mirrored. + if left != nil && right != nil && left.Value == right.Value { + return treesAreMirrored(left.Left, right.Right) && treesAreMirrored(left.Right, right.Left) + } + + // If either left or right tree is nil or their values are not equal, they are not mirrored. + // Also, if both left and right trees are nil, they are considered mirrored. + return left == right +} From e35574ae6076b3e9bc5ceebb411f0b109d3eb9c2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:30:50 +0530 Subject: [PATCH 1170/1894] add iterative approach using stack --- Trees/Binary Trees/is_symmetric.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/is_symmetric.go b/Trees/Binary Trees/is_symmetric.go index aee518ac..ecbeecfa 100644 --- a/Trees/Binary Trees/is_symmetric.go +++ b/Trees/Binary Trees/is_symmetric.go @@ -8,8 +8,9 @@ type BinaryTree struct { Right *BinaryTree } +// Approach 1: Recursive Approach // SymmetricalTree checks if a binary tree is symmetrical. -func SymmetricalTree(tree *BinaryTree) bool { +func SymmetricalTreerecursive(tree *BinaryTree) bool { // Call the helper function to check if the left and right subtrees are mirrored. return treesAreMirrored(tree.Left, tree.Right) } @@ -26,3 +27,30 @@ func treesAreMirrored(left, right *BinaryTree) bool { // Also, if both left and right trees are nil, they are considered mirrored. return left == right } + +// Approach 2: Iterative Approach using Stack +func SymmetricalTreeIterative(tree *BinaryTree) bool { + stackLeft := []*BinaryTree{tree.Left} // Initialize stackLeft with the left child of the root node + stackRight := []*BinaryTree{tree.Right} // Initialize stackRight with the right child of the root node + + // Perform mirror traversal of the left and right subtrees + for len(stackLeft) > 0 { + var left, right *BinaryTree + left, stackLeft = stackLeft[len(stackLeft)-1], stackLeft[:len(stackLeft)-1] // Pop the top node from stackLeft + right, stackRight = stackRight[len(stackRight)-1], stackRight[:len(stackRight)-1] // Pop the top node from stackRight + + if left == nil && right == nil { + continue // Both left and right subtrees are symmetric, continue to the next iteration + } + + if left == nil || right == nil || left.Value != right.Value { + return false // Asymmetry detected, tree is not symmetric + } + + // Push the children of left and right onto the respective stacks in reverse order + stackLeft = append(stackLeft, left.Left, left.Right) + stackRight = append(stackRight, right.Right, right.Left) + } + + return true // Tree is symmetric +} \ No newline at end of file From 8039641e28ac5b81d7c2c28b88197d7c280fc667 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:32:11 +0530 Subject: [PATCH 1171/1894] add explanation --- Trees/Binary Trees/is_symmetric.go | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Trees/Binary Trees/is_symmetric.go b/Trees/Binary Trees/is_symmetric.go index ecbeecfa..ae13af19 100644 --- a/Trees/Binary Trees/is_symmetric.go +++ b/Trees/Binary Trees/is_symmetric.go @@ -28,6 +28,39 @@ func treesAreMirrored(left, right *BinaryTree) bool { return left == right } +/* Explanation: + + The code snippet defines a function SymmetricalTree that checks if a binary tree is symmetrical. + The binary tree is represented by the BinaryTree struct, which has a Value field and pointers to + its left and right child nodes. + + The function uses two stacks, stackLeft and stackRight, to perform a mirror traversal of the + left and right subtrees of the input tree. It starts by pushing the left child of the root + node onto stackLeft and the right child of the root node onto stackRight. + + The function then enters a loop that continues until the stackLeft is empty. In each iteration + of the loop, it pops the top nodes from stackLeft and stackRight, assigning them to variables + left and right, respectively. + + If both left and right are nil, it means the corresponding subtrees are symmetric, so the loop + continues to the next iteration. + + If either left or right is nil, or their values are not equal, it means the tree is not symmetric, + and the function returns false. + + Otherwise, it pushes the left child of left and the right child of right onto stackLeft and stackRight, + respectively, in reverse order. This ensures that the subsequent nodes popped from the stacks are + compared as mirror images. + + Once the loop is completed, and no asymmetry has been detected, the function returns true, indicating + that the binary tree is symmetric. + + The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree, as + it traverses each node once. The space complexity is O(max(d, h)), where d is the maximum width of + the tree (number of nodes at the widest level) and h is the height of the tree. The space complexity + depends on the maximum number of nodes stored in the stacks during the traversal. +*/ + // Approach 2: Iterative Approach using Stack func SymmetricalTreeIterative(tree *BinaryTree) bool { stackLeft := []*BinaryTree{tree.Left} // Initialize stackLeft with the left child of the root node From f7dca529dd745063023f2d981646e631f8dd14e7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:34:08 +0530 Subject: [PATCH 1172/1894] add explanation --- Trees/Binary Trees/is_symmetric.go | 45 ++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Trees/Binary Trees/is_symmetric.go b/Trees/Binary Trees/is_symmetric.go index ae13af19..fcb3bec3 100644 --- a/Trees/Binary Trees/is_symmetric.go +++ b/Trees/Binary Trees/is_symmetric.go @@ -7,7 +7,52 @@ type BinaryTree struct { Left *BinaryTree Right *BinaryTree } +/* +The code consists of two functions. The SymmetricalTree function serves as an entry point and checks if the +binary tree is symmetrical by calling the treesAreMirrored helper function with the left and right subtrees +of the root node. +The treesAreMirrored function is a recursive helper function that checks if two binary trees are mirrored. +It uses a bottom-up approach to compare corresponding nodes of the left and right subtrees. + +The function performs the following steps: + + 1. Base case: If both the left and right trees are non-nil and have the same value, recursively check if + their respective subtrees are mirrored by calling treesAreMirrored with the left subtree's left and + the right subtree's right children, as well as the left subtree's right and the right subtree's left children. + + 2. If either the left or right tree is nil or their values are not equal, they are not mirrored, and the function returns false. + + 3. If both the left and right trees are nil, they are considered mirrored, and the function returns true. + + The recursive nature of the treesAreMirrored function allows it to traverse and compare corresponding nodes + in a symmetrical manner. If the function successfully reaches the base case for all nodes, it indicates + that the binary tree is symmetrical. + + Overall, the code leverages recursion and the concept of mirror images to determine if a binary tree is symmetrical or not. + The time and space complexity of the code snippet can be analyzed as follows: + + Time Complexity: + The time complexity of the SymmetricalTree function primarily depends on the size of the binary tree. + In the worst case, where the tree is symmetric, the function needs to traverse all the nodes of the tree once. + + Let's assume there are 'n' nodes in the tree. In the worst case, the function will visit each node exactly once. + Therefore, the time complexity is O(n), where 'n' is the number of nodes in the binary tree. + + Space Complexity: + The space complexity is determined by the recursive calls and the stack space used during the recursion. + + In the worst case, when the binary tree is highly unbalanced and resembles a linked list, the depth of the + recursion can be 'n' (the number of nodes in the tree). This means that the space required on the function + call stack will be O(n). + + Additionally, the space complexity also includes the space used to store the function arguments and local variables. + However, as these are constant-sized values (pointers), they don't contribute significantly to the overall space complexity. + + Therefore, the overall space complexity is O(n), where 'n' is the number of nodes in the binary tree, considering the worst-case scenario. + + In summary, the time complexity is O(n), and the space complexity is O(n), where 'n' is the number of nodes in the binary tree. +*/ // Approach 1: Recursive Approach // SymmetricalTree checks if a binary tree is symmetrical. func SymmetricalTreerecursive(tree *BinaryTree) bool { From 8269e85c73e1bcf730298b9d5396d7999a6262c6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 22 May 2023 22:41:28 +0530 Subject: [PATCH 1173/1894] add question --- Trees/Binary Trees/is_symmetric.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Trees/Binary Trees/is_symmetric.go b/Trees/Binary Trees/is_symmetric.go index fcb3bec3..f0df1350 100644 --- a/Trees/Binary Trees/is_symmetric.go +++ b/Trees/Binary Trees/is_symmetric.go @@ -1,3 +1,7 @@ +/* + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical + if the left and right subtrees are mirror images of each other. +*/ package main // This is an input class. Do not edit. From e16c35ca6d4eeed369c0d3d62a4e913707b2de50 Mon Sep 17 00:00:00 2001 From: Suyashsingh Date: Mon, 22 May 2023 23:05:12 +0530 Subject: [PATCH 1174/1894] problem statement added ,well expalined --- Math/K_closest.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Math/K_closest.cpp b/Math/K_closest.cpp index a23b4f25..e3fee636 100644 --- a/Math/K_closest.cpp +++ b/Math/K_closest.cpp @@ -1,5 +1,12 @@ /* -Expalination: +Problem statement:-Find K Closest Elements +Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. + +An integer a is closer to x than an integer b if: + +|a - x| < |b - x|, or +|a - x| == |b - x| and a < b +Explaination: Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] @@ -31,18 +38,23 @@ class Solution { // Construction of max heap for (auto& p : points) { int x = p[0], y = p[1]; + // Calculate the squared distance from the origin using the formula x^2 + y^2 + // Store the distance along with the coordinates (x, y) in the maxHeap maxHeap.push({x * x + y * y, x, y}); + // If the size of the maxHeap exceeds k, remove the point with the maximum distance if (maxHeap.size() > k) { maxHeap.pop(); } } - + // Extract the k closest points from the maxHeap and store them in the result vector for (int i = k - 1; i >= 0; --i) { vector top = maxHeap.top(); maxHeap.pop(); result[i] = {top[1], top[2]}; } + // Return the result vector containing the k closest points + return result; } }; From 9877065b5939c03decca83eb08e16635edda0f78 Mon Sep 17 00:00:00 2001 From: Suyashsingh Date: Mon, 22 May 2023 23:13:54 +0530 Subject: [PATCH 1175/1894] problem statement added ,well expalined.TC/SC added --- Math/K_closest.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Math/K_closest.cpp b/Math/K_closest.cpp index e3fee636..b3f334ee 100644 --- a/Math/K_closest.cpp +++ b/Math/K_closest.cpp @@ -1,4 +1,6 @@ /* + Author: SUYASH SINGH + Problem statement:-Find K Closest Elements Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. @@ -72,4 +74,15 @@ int main() { } return 0; -} +}/* +Time Complexity: + +Constructing the maxHeap: the overall time complexity is O(N log K). +Extracting the k closest points: O(K log K). We extract the top element from the maxHeap k times, each operation taking O(log K) time. Hence, the time complexity is O(K log K). +Therefore, the overall time complexity of the solution is O(N log K), where N is the number of points and K is the value of k. + +Space Complexity: + +The maxHeap stores at most k elements, so the space complexity for the maxHeap is O(K). +The result vector stores k closest points, resulting in O(K) space. +Apart from these, the solution uses a constant amount of space for variables and temporary storage.*/ From abdb41e6d26f6d7d8b84e9bae1155b0087b5d42f Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Tue, 23 May 2023 03:06:17 +0530 Subject: [PATCH 1176/1894] Monotonic_Array implemented --- Arrays/Monotonic_Array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/Monotonic_Array.cpp b/Arrays/Monotonic_Array.cpp index fc543019..c8975760 100644 --- a/Arrays/Monotonic_Array.cpp +++ b/Arrays/Monotonic_Array.cpp @@ -1,4 +1,4 @@ -/*The isMonotonic function takes a std::vector as input and iterates over the array to check if it is either strictly increasing or strictly decreasing. It uses two boolean variables, increasing and decreasing, to keep track of whether the array satisfies those conditions. If both variables remain true after the loop, it means the array is monotonic. The function returns true if the array is monotonic and false otherwise.*/ +/*The problem is about determining whether an array is monotonic. A monotonic array is defined as an array that is either entirely non-increasing or non-decreasing.*/ /*The time complexity of the isMonotonic function is O(n) The space complexity of the isMonotonic function is O(1)*/ From 21edbf7dd43edbb29fff2c415bd7b5c5893522a9 Mon Sep 17 00:00:00 2001 From: payalpm Date: Tue, 23 May 2023 14:21:56 +0530 Subject: [PATCH 1177/1894] coin-change-js --- Greedy/coin_change.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Greedy/coin_change.js diff --git a/Greedy/coin_change.js b/Greedy/coin_change.js new file mode 100644 index 00000000..56059099 --- /dev/null +++ b/Greedy/coin_change.js @@ -0,0 +1,37 @@ +function coinChangeGreedy(s, l) { + // First step: sort l in descending order + l.sort((a, b) => b - a); + + let r = []; // Result list + let sumr = 0; // Keep track of the current sum of r to avoid iterating over r to calculate the sum + + for (let coin of l) { + if (sumr === s) { // The sum of r is the target sum s + break; + } + + let n = Math.floor((s - sumr) / coin); // Calculate the max n with sum(r) + l[i] * n <= s + + for (let i = 0; i < n; i++) { // Append n elements of this coin to r + r.push(coin); + } + + sumr += coin * n; // Update the sum of r + } + + if (sumr !== s) { // The target sum s was not reached + return false; + } + + return r; + } + + // SAMPLE 1 (optimal) + console.log(coinChangeGreedy(60, [5, 10, 25])); + + // SAMPLE 2 (not optimal) + console.log(coinChangeGreedy(50, [25, 10, 30, 5])); + + // SAMPLE 3 (fails) + console.log(coinChangeGreedy(50, [25, 30])); + \ No newline at end of file From cd689a43bb919341b5575ad94d7642644515b1b1 Mon Sep 17 00:00:00 2001 From: payalpm Date: Tue, 23 May 2023 17:36:51 +0530 Subject: [PATCH 1178/1894] coinchagejava --- Greedy/CoinChange.java | 60 ++++++++++++++++++++++++++++++++++++++++++ Greedy/coin_change.js | 1 + 2 files changed, 61 insertions(+) create mode 100644 Greedy/CoinChange.java diff --git a/Greedy/CoinChange.java b/Greedy/CoinChange.java new file mode 100644 index 00000000..b8a7d4a8 --- /dev/null +++ b/Greedy/CoinChange.java @@ -0,0 +1,60 @@ +package Greedy; + + /* + * write a code in java with comments foor As a first example, + * we consider a problem where we are given a set of coins and our task is to + * form a sum of money n using the coins. The values of the coins are coins = {c1, c2,..., ck}, + * and each coin can be used as many times we want. What is the minimum number of coins needed? + * For example, if the coins are the euro coins (in cents) {1,2,5,10,20,50,100,200} and n = 520, + * we need at least four coins. The optimal solution is to select coins 200 + 200 + 100 + 20 whose sum is 520 + */ +import java.util.Arrays; + +public class CoinChange { + + /** + * This method finds the minimum number of coins required to make change for a given amount of money using a given set of coins. + * + * coins The set of coins that can be used to make change. + * n The amount of money to make change for. + * @return The minimum number of coins required to make change for n. + */ + public static int minCoins(int[] coins, int n) { + // Create an array to store the minimum number of coins required to make change for each amount of money. + int[] dp = new int[n + 1]; + + // Initialize the array to Integer.MAX_VALUE. This means that we do not know the minimum number of coins required to make change for any amount of money yet. + Arrays.fill(dp, Integer.MAX_VALUE); + + // Set the minimum number of coins required to make change for 0 to 0. + dp[0] = 0; + + // Iterate over the coins array. + for (int i = 0; i < coins.length; i++) { + // Iterate over the dp array. + for (int j = coins[i]; j <= n; j++) { + // Update the dp[j] element to be the minimum of dp[j] and dp[j - coins[i]] + 1. + dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1); + } + } + + // Return the minimum number of coins required to make change for n. + return dp[n]; + } + + public static void main(String[] args) { + // Create a set of coins. + int[] coins = {1, 2, 5, 10, 20, 50, 100, 200}; + + // The amount of money to make change for. + int n = 520; + + // Find the minimum number of coins required to make change for n. + int minCoins = minCoins(coins, n); + + // Print the minimum number of coins. + System.out.println("The minimum number of coins required to make change for " + n + " cents is " + minCoins); + } +} + +// The minimum number of coins required to make change for 520 cents is 4 diff --git a/Greedy/coin_change.js b/Greedy/coin_change.js index 56059099..399b3e67 100644 --- a/Greedy/coin_change.js +++ b/Greedy/coin_change.js @@ -1,3 +1,4 @@ + function coinChangeGreedy(s, l) { // First step: sort l in descending order l.sort((a, b) => b - a); From f8a2e81cfad3f8c1543babfbbfb523bc6f9198b0 Mon Sep 17 00:00:00 2001 From: arsallanShahab Date: Tue, 23 May 2023 19:24:19 +0530 Subject: [PATCH 1179/1894] Add implementation of Kruskal's Algorithm for Graphs in JavaScript --- Graphs/Graphs_kruskalsAlgorithm.js | 97 ++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/Graphs/Graphs_kruskalsAlgorithm.js b/Graphs/Graphs_kruskalsAlgorithm.js index e69de29b..6a8388a3 100644 --- a/Graphs/Graphs_kruskalsAlgorithm.js +++ b/Graphs/Graphs_kruskalsAlgorithm.js @@ -0,0 +1,97 @@ +/** + * Graphs: Implement Kruskal's Algorithm in JavaScript + * + * This code implements Kruskal's Algorithm to find the Minimum Spanning Tree (MST) + * in a graph. The graph is represented using an adjacency list. The algorithm works + * by repeatedly adding the minimum weight edges that do not form a cycle in the MST. + * + * Time Complexity: O(E log V), where E is the number of edges and V is the number of vertices. + * Space Complexity: O(V), where V is the number of vertices. + */ + +/** + * Class representing a Disjoint Set data structure. + * Used to track disjoint sets and perform union-find operations. + */ +class DisjointSet { + constructor(n) { + this.parent = new Array(n).fill(-1); // Array to store parent of each node + this.rank = new Array(n).fill(0); // Array to store the rank of each node + } + + /** + * Find the parent of a node in the disjoint set. + * Implements path compression to optimize future finds. + * @param {number} x - The node to find the parent for. + * @returns {number} The parent of the given node. + */ + find(x) { + if (this.parent[x] === -1) { + return x; + } + this.parent[x] = this.find(this.parent[x]); // Path compression + return this.parent[x]; + } + + /** + * Union two disjoint sets by rank. + * Uses union by rank to optimize the merge operation. + * @param {number} x - The first node to union. + * @param {number} y - The second node to union. + */ + union(x, y) { + let xRoot = this.find(x); + let yRoot = this.find(y); + + if (this.rank[xRoot] < this.rank[yRoot]) { + this.parent[xRoot] = yRoot; + } else if (this.rank[xRoot] > this.rank[yRoot]) { + this.parent[yRoot] = xRoot; + } else { + this.parent[yRoot] = xRoot; + this.rank[xRoot]++; + } + } +} + +/** + * Function to implement Kruskal's Algorithm for finding the Minimum Spanning Tree (MST). + * @param {number} n - The number of vertices in the graph. + * @param {Array} edges - The edges of the graph represented as an adjacency list. + * @returns {Array} The edges of the Minimum Spanning Tree. + */ +function kruskalsAlgorithm(n, edges) { + // Sort edges in non-decreasing order by weight + edges.sort((a, b) => a[2] - b[2]); + + const mst = []; // Minimum Spanning Tree + const disjointSet = new DisjointSet(n); // Create a disjoint set for tracking sets + + for (let [src, dest, weight] of edges) { + let srcRoot = disjointSet.find(src); + let destRoot = disjointSet.find(dest); + + // If adding the edge does not create a cycle, add it to the MST + if (srcRoot !== destRoot) { + mst.push([src, dest, weight]); + disjointSet.union(srcRoot, destRoot); + } + } + + return mst; +} + +// Example usage +const numVertices = 5; +const graphEdges = [ + [0, 1, 2], + [1, 2, 3], + [0, 3, 6], + [1, 3, 8], + [1, 4, 5], + [2, 4, 7], + [3, 4, 9], +]; + +const minimumSpanningTree = kruskalsAlgorithm(numVertices, graphEdges); +console.log("Minimum Spanning Tree:", minimumSpanningTree); From 7a863d8bae1e01117db5b5c09fcf8066e5924cf9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:26:33 +0530 Subject: [PATCH 1180/1894] add is_symmetric in c++ --- Trees/Binary Trees/is_symmetric.c++ | 63 +++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Trees/Binary Trees/is_symmetric.c++ diff --git a/Trees/Binary Trees/is_symmetric.c++ b/Trees/Binary Trees/is_symmetric.c++ new file mode 100644 index 00000000..d0d0437f --- /dev/null +++ b/Trees/Binary Trees/is_symmetric.c++ @@ -0,0 +1,63 @@ +#include + +using namespace std; + +// This is an input class. Do not edit. +class BinaryTree { +public: + int Value; + BinaryTree* Left; + BinaryTree* Right; +}; + +// SymmetricalTree checks if a binary tree is symmetrical. +bool SymmetricalTree(BinaryTree* tree) { + // Call the helper function to check if the left and right subtrees are mirrored. + return treesAreMirrored(tree->Left, tree->Right); +} + +// treesAreMirrored checks if two binary trees are mirrored. +bool treesAreMirrored(BinaryTree* left, BinaryTree* right) { + // Base case: If both left and right trees are non-null and have the same value, + // recursively check if their subtrees are mirrored. + if (left != nullptr && right != nullptr && left->Value == right->Value) { + return treesAreMirrored(left->Left, right->Right) && treesAreMirrored(left->Right, right->Left); + } + + // If either left or right tree is null or their values are not equal, they are not mirrored. + // Also, if both left and right trees are null, they are considered mirrored. + return left == right; +} + +int main() { + // Create a binary tree for testing + BinaryTree* tree = new BinaryTree(); + tree->Value = 1; + tree->Left = new BinaryTree(); + tree->Left->Value = 2; + tree->Right = new BinaryTree(); + tree->Right->Value = 2; + tree->Left->Left = new BinaryTree(); + tree->Left->Left->Value = 3; + tree->Right->Right = new BinaryTree(); + tree->Right->Right->Value = 3; + + // Check if the tree is symmetrical + bool isSymmetrical = SymmetricalTree(tree); + + // Output the result + if (isSymmetrical) { + cout << "The binary tree is symmetrical." << endl; + } else { + cout << "The binary tree is not symmetrical." << endl; + } + + // Clean up the allocated memory + delete tree->Left->Left; + delete tree->Right->Right; + delete tree->Left; + delete tree->Right; + delete tree; + + return 0; +} From 4a8152fa75dee334cea535547fb5213e3c19e163 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:28:00 +0530 Subject: [PATCH 1181/1894] add question and explanation --- Trees/Binary Trees/is_symmetric.c++ | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Trees/Binary Trees/is_symmetric.c++ b/Trees/Binary Trees/is_symmetric.c++ index d0d0437f..9bedebc6 100644 --- a/Trees/Binary Trees/is_symmetric.c++ +++ b/Trees/Binary Trees/is_symmetric.c++ @@ -1,3 +1,26 @@ +/* + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical + if the left and right subtrees are mirror images of each other. + + Explanation: + + 1. The code defines a class `BinaryTree` representing a binary tree node. It has an `int` value and pointers + to its left and right children. + 2. The `SymmetricalTree` function is the main entry point. It calls the helper function `treesAreMirrored` + to check if the left and right subtrees are mirrored. + 3. The `treesAreMirrored` function checks if two binary trees are mirrored. It uses recursion to compare + corresponding nodes in the left and right subtrees. + 4. In the `treesAreMirrored` function, the base case checks if both the left and right trees are non-null + and have the same value. If so, it recursively checks if their subtrees are mirrored. + 5. If either the left or right tree is null or their values are not equal, they are not mirrored. + If both the left and right trees are null, they are considered mirrored. + 6. In the `main` function, a binary tree is created for testing purposes. + 7. The `SymmetricalTree` function is called to check if the binary tree is symmetrical. + 8. The result is printed to the console. + 9. Memory cleanup is performed by deleting the dynamically allocated nodes. + +Note: This code snippet assumes the use of a C++ compiler and standard library. +*/ #include using namespace std; From 33452711674152dc14c1a3721fef1c67d88abfeb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:28:56 +0530 Subject: [PATCH 1182/1894] add time and space --- Trees/Binary Trees/is_symmetric.c++ | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/Trees/Binary Trees/is_symmetric.c++ b/Trees/Binary Trees/is_symmetric.c++ index 9bedebc6..1b7916db 100644 --- a/Trees/Binary Trees/is_symmetric.c++ +++ b/Trees/Binary Trees/is_symmetric.c++ @@ -3,7 +3,7 @@ if the left and right subtrees are mirror images of each other. Explanation: - + 1. The code defines a class `BinaryTree` representing a binary tree node. It has an `int` value and pointers to its left and right children. 2. The `SymmetricalTree` function is the main entry point. It calls the helper function `treesAreMirrored` @@ -19,7 +19,19 @@ 8. The result is printed to the console. 9. Memory cleanup is performed by deleting the dynamically allocated nodes. -Note: This code snippet assumes the use of a C++ compiler and standard library. + The time and space complexity of the given code snippet can be analyzed as follows: + + 1. Time Complexity: + - The `SymmetricalTree` function calls the `treesAreMirrored` function, which performs a recursive traversal of the binary tree. + - In the worst case, the recursion visits each node once, so the time complexity is O(N), where N is the number of nodes in the tree. + + 2. Space Complexity: + - The space complexity is determined by the maximum depth of the recursion stack. + - In the worst case, the binary tree is linear, resulting in a recursion depth of N, where N is the number of nodes in the tree. + - Therefore, the space complexity is O(N) due to the recursion stack usage. + + It's important to note that the space complexity can be optimized by using an iterative approach instead of recursion. By using an iterative algorithm that leverages a stack or queue to perform a level-order traversal, we can achieve a space complexity of O(W), where W is the maximum width (number of nodes at the same level) of the binary tree. + */ #include From c95d2e7dd8eb9252a5f85fb71cb03cc31700df1f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:32:46 +0530 Subject: [PATCH 1183/1894] add iterative appraoch --- Trees/Binary Trees/is_symmetric.c++ | 53 +++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/Trees/Binary Trees/is_symmetric.c++ b/Trees/Binary Trees/is_symmetric.c++ index 1b7916db..c3730e1e 100644 --- a/Trees/Binary Trees/is_symmetric.c++ +++ b/Trees/Binary Trees/is_symmetric.c++ @@ -31,7 +31,7 @@ - Therefore, the space complexity is O(N) due to the recursion stack usage. It's important to note that the space complexity can be optimized by using an iterative approach instead of recursion. By using an iterative algorithm that leverages a stack or queue to perform a level-order traversal, we can achieve a space complexity of O(W), where W is the maximum width (number of nodes at the same level) of the binary tree. - + */ #include @@ -46,7 +46,7 @@ public: }; // SymmetricalTree checks if a binary tree is symmetrical. -bool SymmetricalTree(BinaryTree* tree) { +bool SymmetricalTreeRecursive(BinaryTree* tree) { // Call the helper function to check if the left and right subtrees are mirrored. return treesAreMirrored(tree->Left, tree->Right); } @@ -64,6 +64,55 @@ bool treesAreMirrored(BinaryTree* left, BinaryTree* right) { return left == right; } +// Approach 2: Iterative Approach using Stack +/* + In this iterative approach, we use two stacks (stackLeft and stackRight) to perform a mirror traversal of the + left and right subtrees. The process is similar to the original code snippet but implemented iteratively + using a while loop and stacks. The stacks are initialized with the left and right children of the root node, + and in each iteration, we compare the corresponding nodes from both stacks and check for asymmetry. + The children of the left and right nodes are pushed onto their respective stacks in reverse order to + maintain the mirror traversal. The loop continues until both stacks are empty or an asymmetry is detected. + Finally, the function returns whether the tree is symmetric or not. + +*/ +struct BinaryTree { + int value; + BinaryTree* left; + BinaryTree* right; +}; + +bool SymmetricalTreeIterative(BinaryTree* tree) { + std::stack stackLeft; + std::stack stackRight; + stackLeft.push(tree->left); // Initialize stackLeft with the left child of the root node + stackRight.push(tree->right); // Initialize stackRight with the right child of the root node + + // Perform mirror traversal of the left and right subtrees + while (!stackLeft.empty()) { + BinaryTree* left = stackLeft.top(); + BinaryTree* right = stackRight.top(); + stackLeft.pop(); + stackRight.pop(); + + if (left == nullptr && right == nullptr) { + continue; // Both left and right subtrees are symmetric, continue to the next iteration + } + + if (left == nullptr || right == nullptr || left->value != right->value) { + return false; // Asymmetry detected, tree is not symmetric + } + + // Push the children of left and right onto the respective stacks in reverse order + stackLeft.push(left->left); + stackLeft.push(left->right); + stackRight.push(right->right); + stackRight.push(right->left); + } + + return true; // Tree is symmetric +} + + int main() { // Create a binary tree for testing BinaryTree* tree = new BinaryTree(); From 704e14a28511dcba2de10844bcbd0915f1e487d8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:33:01 +0530 Subject: [PATCH 1184/1894] change file extension --- Trees/Binary Trees/{is_symmetric.c++ => is_symmetric.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trees/Binary Trees/{is_symmetric.c++ => is_symmetric.cpp} (100%) diff --git a/Trees/Binary Trees/is_symmetric.c++ b/Trees/Binary Trees/is_symmetric.cpp similarity index 100% rename from Trees/Binary Trees/is_symmetric.c++ rename to Trees/Binary Trees/is_symmetric.cpp From 709a1bc918c4f6b8b1209d60dd11ae11a8a7cb11 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 23 May 2023 22:33:38 +0530 Subject: [PATCH 1185/1894] add time and space --- Trees/Binary Trees/is_symmetric.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Trees/Binary Trees/is_symmetric.cpp b/Trees/Binary Trees/is_symmetric.cpp index c3730e1e..ed9fa410 100644 --- a/Trees/Binary Trees/is_symmetric.cpp +++ b/Trees/Binary Trees/is_symmetric.cpp @@ -74,6 +74,12 @@ bool treesAreMirrored(BinaryTree* left, BinaryTree* right) { maintain the mirror traversal. The loop continues until both stacks are empty or an asymmetry is detected. Finally, the function returns whether the tree is symmetric or not. + The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree, as + it traverses each node once. The space complexity is O(max(d, h)), where d is the maximum width of + the tree (number of nodes at the widest level) and h is the height of the tree. The space complexity + depends on the maximum number of nodes stored in the stacks during the traversal. + + */ struct BinaryTree { int value; From a9c8deb52e0d359aeee1fc2ec172f1d36739e63d Mon Sep 17 00:00:00 2001 From: Abhisek Sahoo <110292494+abhisek-1221@users.noreply.github.com> Date: Tue, 23 May 2023 23:07:24 +0530 Subject: [PATCH 1186/1894] Knuth Morris Pratt Algorithm implemented in JS --- Strings/Knuth_Morris_Pratt_Algorithm.js | 117 ++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Strings/Knuth_Morris_Pratt_Algorithm.js diff --git a/Strings/Knuth_Morris_Pratt_Algorithm.js b/Strings/Knuth_Morris_Pratt_Algorithm.js new file mode 100644 index 00000000..dcfe50c6 --- /dev/null +++ b/Strings/Knuth_Morris_Pratt_Algorithm.js @@ -0,0 +1,117 @@ +/**The Knuth-Morris-Pratt (KMP) algorithm is a string matching algorithm that efficiently finds occurrences of a pattern within a text. It was developed by Donald Knuth and Vaughan Pratt in 1977. + +The key idea behind the KMP algorithm is to take advantage of the information present in the pattern itself to avoid unnecessary character comparisons during the search process. It achieves this by utilizing a preprocessed array called the Longest Proper Prefix which is also Suffix (LPS) array or failure function. + +Here's a step-by-step explanation of the KMP algorithm: + +1. Preprocessing (Compute LPS Array): + - Given a pattern of length m, the first step is to compute the LPS array, which holds information about the longest proper prefix that is also a suffix for each position in the pattern. + - The LPS array is initialized with the first element as 0 and then iteratively calculated for each position of the pattern using the following rules: + - If the characters at the current position and the previous longest proper prefix suffix match, increment the length of the prefix and store it in the LPS array. + - If the characters don't match: + - If the length of the prefix is not zero, move to the previous longest proper prefix suffix and continue the comparison. + - If the length of the prefix is zero, store 0 in the LPS array for the current position. + - This preprocessing step is done in O(m) time complexity. + +2. Search (Pattern Matching): + - With the LPS array computed, the search process begins by comparing characters of the text and pattern. + - Initialize two pointers, i for the text and j for the pattern, both starting from 0. + - Iterate over the text from left to right until i reaches the end of the text: + - If the characters at the current positions i and j match, increment both i and j. + - If j reaches the end of the pattern, a match is found: + - Store the index (i - j) as an occurrence of the pattern in the text. + - Move j to the previous longest proper prefix suffix using the LPS array. + - If the characters at the current positions i and j don't match: + - If j is not at the beginning of the pattern, move j to the previous longest proper prefix suffix using the LPS array. + - If j is at the beginning of the pattern, increment i and continue the search. + - The search process iterates over the text once and performs comparisons using the LPS array, resulting in a time complexity of O(n), where n is the length of the text. + +The KMP algorithm provides an efficient way to search for patterns within a text by avoiding redundant comparisons. It achieves this by utilizing the LPS array, which stores information about the pattern's structure. This makes the KMP algorithm more efficient than naive approaches such as the brute-force method, especially when the pattern has repeated characters or subsequences. */ + +/** + * Computes the Longest Proper Prefix which is also Suffix (LPS) array for the given pattern. + * The LPS array is used to determine the longest prefix of the pattern that is also a suffix. + * + * @param {string} pattern - The pattern string. + * @returns {number[]} - The LPS array. + */ + function computeLPSArray(pattern) { + const lps = [0]; // Initialize LPS array with the first element as 0. + let len = 0; // Length of the previous longest prefix suffix. + let i = 1; // Current index in the pattern string. + + while (i < pattern.length) { + if (pattern[i] === pattern[len]) { + len++; + lps[i] = len; + i++; + } else { + if (len !== 0) { + // Move len to the previous longest prefix suffix value. + len = lps[len - 1]; + } else { + lps[i] = 0; + i++; + } + } + } + + return lps; + } + + /** + * Performs the Knuth-Morris-Pratt (KMP) algorithm to find all occurrences of a pattern within a text. + * + * @param {string} text - The text string. + * @param {string} pattern - The pattern string. + * @returns {number[]} - An array of indices where the pattern is found within the text. + */ + function KMP(text, pattern) { + const m = pattern.length; // Length of the pattern. + const n = text.length; // Length of the text. + const lps = computeLPSArray(pattern); // Compute the LPS array for the pattern. + const indices = []; // Array to store the indices where the pattern is found. + + let i = 0; // Current index in the text string. + let j = 0; // Current index in the pattern string. + + while (i < n) { + if (pattern[j] === text[i]) { + i++; + j++; + } + + if (j === m) { + // Pattern found at index i - j. + indices.push(i - j); + j = lps[j - 1]; // Move j to the previous longest prefix suffix value. + } else if (i < n && pattern[j] !== text[i]) { + if (j !== 0) { + j = lps[j - 1]; // Move j to the previous longest prefix suffix value. + } else { + i++; + } + } + } + + return indices; + } + + // Example usage: + const text = "ABABDABACDABABCABAB"; + const pattern = "ABABCABAB"; + + const indices = KMP(text, pattern); + console.log("Pattern found at indices:", indices); + + // Pattern found at indices: [10] + + /** + +Time Complexity: + +The KMP algorithm has a time complexity of O(m + n), where m is the length of the pattern and n is the length of the text. It computes the LPS array in O(m) time and performs a single pass over the text in O(n) time. + +Space Complexity: + +The space complexity of the KMP algorithm is O(m), where m is the length of the pattern. It is due to the LPS array, which requires O(m) space to store the longest prefix suffix values for each index in the pattern. The additional space used by the algorithm is minimal and does not depend on the input size */ \ No newline at end of file From ef1e6f26d4a092777873b03d4e142b1f33ac51da Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Wed, 24 May 2023 00:52:06 +0530 Subject: [PATCH 1187/1894] File renamed --- sorting/{Heap_Sort.py => Heap_sort_implementation.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename sorting/{Heap_Sort.py => Heap_sort_implementation.py} (100%) diff --git a/sorting/Heap_Sort.py b/sorting/Heap_sort_implementation.py similarity index 100% rename from sorting/Heap_Sort.py rename to sorting/Heap_sort_implementation.py From 3ac32bb187e9179f0b37b8eb78c032bf7a391f29 Mon Sep 17 00:00:00 2001 From: Akshay Magar Date: Wed, 24 May 2023 01:11:55 +0530 Subject: [PATCH 1188/1894] Doubly Linked List Implemented in java --- .../Doubly_linked_list_implementation.java | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Linked List/Doubly_linked_list_implementation.java diff --git a/Linked List/Doubly_linked_list_implementation.java b/Linked List/Doubly_linked_list_implementation.java new file mode 100644 index 00000000..c709b4b8 --- /dev/null +++ b/Linked List/Doubly_linked_list_implementation.java @@ -0,0 +1,107 @@ +/*A Doubly Linked List is a data structure in which each node contains a reference to the previous node and the next node in the sequence. It extends the functionality of a Singly Linked List by allowing traversal in both forward and backward directions.The first node of the list is referred to as the head, and the last node is referred to as the tail. In this implementation, the Node class represents a node in the doubly linked list. Each node has a data field to store the value, and prev and next fields to maintain references to the previous and next nodes in the list.*/ + +class Node { + int data; + Node prev; + Node next; + + public Node(int data) { + this.data = data; + this.prev = null; + this.next = null; + } +} + +class DoublyLinkedList { + Node head; + + public DoublyLinkedList() { + this.head = null; + } + + // Insert a new node at the end of the list + public void insert(int data) { + Node newNode = new Node(data); + + if (head == null) { + // If the list is empty, make the new node the head + head = newNode; + } else { + Node current = head; + + // Traverse to the end of the list + while (current.next != null) { + current = current.next; + } + + // Link the new node to the last node + current.next = newNode; + newNode.prev = current; + } + } + + // Delete a node with the given data value + public void delete(int data) { + Node current = head; + + while (current != null) { + if (current.data == data) { + if (current.prev != null) { + // If the node to be deleted is not the first node + + // Update the previous node's next reference + current.prev.next = current.next; + } else { + // If the node to be deleted is the first node + + // Update the head reference to the next node + head = current.next; + } + + if (current.next != null) { + // If the node to be deleted is not the last node + + // Update the next node's previous reference + current.next.prev = current.prev; + } + + break; + } + + current = current.next; + } + } + + // Display the elements of the list + public void display() { + Node current = head; + + while (current != null) { + System.out.print(current.data + " "); + current = current.next; + } + + System.out.println(); + } +} + +public class Main { + public static void main(String[] args) { + DoublyLinkedList list = new DoublyLinkedList(); + + list.insert(10); + list.insert(20); + list.insert(30); + list.insert(40); + + list.display(); // Output: 10 20 30 40 + + list.delete(20); + list.delete(40); + + list.display(); // Output: 10 30 + } +} + +/* Time complexity: O(n) for insertions and deletions, and O(1) for display. +Space complexity: O(1) for all operations */ From d8e322b4513d64f1471e0a4c413f343ddb04bdfc Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Wed, 24 May 2023 13:24:53 +0000 Subject: [PATCH 1189/1894] Linked-List-Component Solution added --- Linked List/Linked_List_Component.java | 72 ++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Linked List/Linked_List_Component.java diff --git a/Linked List/Linked_List_Component.java b/Linked List/Linked_List_Component.java new file mode 100644 index 00000000..6bb8c763 --- /dev/null +++ b/Linked List/Linked_List_Component.java @@ -0,0 +1,72 @@ + + + +/**PROBLEM + * You are given the head of a linked list containing unique integer values and an integer array nums + *that is a subset of the linked list values. + +*Return the number of connected components in nums where two values are connected if + *they appear consecutively in the linked list. +*/ + +// SAMPLE I/O +// Input: head = [0,1,2,3], nums = [0,1,3] +// Output: 2 +// Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components. + +// Approach +/** + * Creating a HashMap to store all the values of nums[] + * Iterating list and if current node(head) we check if the hashmap contains the value] + * if yes the we increment the ans by one and setting the flag to false + * + * + * + * Time Complexity: O(N) + * Space Complexity : O(N) + */ + + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int numComponents(ListNode head, int[] nums) { + // Create a HashMap to store the values from nums as keys and their indices as values + HashMap hm = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + hm.put(nums[i], i); + } + + boolean flag = true; // Flag to track if a connected component is found + int ans = 0; // Variable to store the number of connected components + + // Traverse the linked list + while (head != null) { + // Check if the current node's value is present in the HashMap + while (head != null && hm.containsKey(head.val)) { + head = head.next; // Move to the next node + + // If this is the start of a new connected component, increment the answer + if (flag) { + ans += 1; + flag = false; + } + } + flag = true; // Reset the flag + + if (head != null) { + head = head.next; // Move to the next node + } + } + + return ans; + } +} From 1fff537ddea7133691a9adb7ea6633db3f7a1f19 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Wed, 24 May 2023 22:36:44 +0530 Subject: [PATCH 1190/1894] Added Kuskal algo in python --- Graphs/Kruskal_Algo.py | 53 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Graphs/Kruskal_Algo.py diff --git a/Graphs/Kruskal_Algo.py b/Graphs/Kruskal_Algo.py new file mode 100644 index 00000000..05db5699 --- /dev/null +++ b/Graphs/Kruskal_Algo.py @@ -0,0 +1,53 @@ +class UnionFind: + def __init__(self, n): + self.parent = list(range(n)) + self.rank = [0] * n + + def find(self, x): + if self.parent[x] != x: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + root_x = self.find(x) + root_y = self.find(y) + + if root_x != root_y: + if self.rank[root_x] < self.rank[root_y]: + self.parent[root_x] = root_y + elif self.rank[root_x] > self.rank[root_y]: + self.parent[root_y] = root_x + else: + self.parent[root_y] = root_x + self.rank[root_x] += 1 + + +def kruskal(graph): + edges = [] + for u in range(len(graph)): + for v, weight in graph[u]: + edges.append((weight, u, v)) + + edges.sort() + mst = [] + uf = UnionFind(len(graph)) + + for weight, u, v in edges: + if uf.find(u) != uf.find(v): + uf.union(u, v) + mst.append((u, v, weight)) + + return mst + + +# Example usage: +graph = [ + [(1, 1), (2, 2)], # Node 0 + [(0, 1), (2, 3), (3, 4)], # Node 1 + [(0, 2), (1, 3), (3, 5)], # Node 2 + [(1, 4), (2, 5)] # Node 3 +] + +mst = kruskal(graph) +for u, v, weight in mst: + print(f"Edge ({u}, {v}) with weight {weight}") From e77a0226564eebc3070b4ee44bdf7641e1c1f598 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <94506000+AbhishekCS3459@users.noreply.github.com> Date: Thu, 25 May 2023 00:19:41 +0530 Subject: [PATCH 1191/1894] Update Kruskal_Algo.py Added Proper Comments,Question to it --- Graphs/Kruskal_Algo.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/Graphs/Kruskal_Algo.py b/Graphs/Kruskal_Algo.py index 05db5699..b6b155ec 100644 --- a/Graphs/Kruskal_Algo.py +++ b/Graphs/Kruskal_Algo.py @@ -1,14 +1,29 @@ +#Question: Implement Kruskal's algorithm in Python to find the minimum spanning tree of a given graph. +#Intuition: +# Kruskal's algorithm is a greedy algorithm that aims to find the minimum spanning tree (MST) of a connected, weighted graph. +# The MST is a subset of the graph's edges that connects all the vertices with the minimum total weight. +# The algorithm works by iteratively selecting the edges in ascending order of their weights, while ensuring that adding an edge to the growing MST does not create a cycle. +#It uses a disjoint set data structure, typically implemented with the Union-Find algorithm, to efficiently keep track of the connected components and +# detect cycles. + +#Implementing Kruskal's algorithm with the help of a Union-Find data structure allows for efficient detection of cycles and union operations, +#resulting in a time complexity of O(E log E), where E is the number of edges in the graph. + +# Initialize a Union-Find data structure to keep track of the connected components. class UnionFind: def __init__(self, n): + # Initialize the parent and rank lists self.parent = list(range(n)) self.rank = [0] * n def find(self, x): + # Find the root of the set to which x belongs if self.parent[x] != x: - self.parent[x] = self.find(self.parent[x]) + self.parent[x] = self.find(self.parent[x]) # Path compression return self.parent[x] def union(self, x, y): + # Perform the union of two sets root_x = self.find(x) root_y = self.find(y) @@ -21,7 +36,7 @@ def union(self, x, y): self.parent[root_y] = root_x self.rank[root_x] += 1 - +# Define the Kruskal function def kruskal(graph): edges = [] for u in range(len(graph)): @@ -29,6 +44,7 @@ def kruskal(graph): edges.append((weight, u, v)) edges.sort() + # Create an empty list to store the MST mst = [] uf = UnionFind(len(graph)) @@ -39,15 +55,14 @@ def kruskal(graph): return mst - -# Example usage: +# Example usage: Create a list of all the edges in the graph, along with their weights. graph = [ [(1, 1), (2, 2)], # Node 0 [(0, 1), (2, 3), (3, 4)], # Node 1 [(0, 2), (1, 3), (3, 5)], # Node 2 [(1, 4), (2, 5)] # Node 3 ] - +#Sort the edges in ascending order based on their weights. mst = kruskal(graph) for u, v, weight in mst: print(f"Edge ({u}, {v}) with weight {weight}") From 1e824f61e03889fa55af3afd38466f0ef33acf27 Mon Sep 17 00:00:00 2001 From: SNEHA CHAUHAN Date: Thu, 25 May 2023 07:20:50 +0000 Subject: [PATCH 1192/1894] String: Implement KMP Algorithm in Python --- Strings/KnuthMorrisPratt Algorithm.py | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Strings/KnuthMorrisPratt Algorithm.py diff --git a/Strings/KnuthMorrisPratt Algorithm.py b/Strings/KnuthMorrisPratt Algorithm.py new file mode 100644 index 00000000..ab92c741 --- /dev/null +++ b/Strings/KnuthMorrisPratt Algorithm.py @@ -0,0 +1,44 @@ +# Implementation of KMP Algorithm. Program Author : SNEHA CHAUHAN +''' problem: Given a text txt and a pattern pat, write a function search(char pat[], char txt[]) + that prints all occurrences of pat[] in txt[]. + + KMP algorithm is used to find the pattern in the given string. This is naive approach to find + the pattern in the given string. + + Time Complexity: O(n*m) + Space Complexity: O(1) + + Example: + input: txt = “AAAABAAABA” pat = “AAAA” + output: Pattern found at index 0 + + Algorithm: + 1. Start from the leftmost character of txt and one by one compare it with each character of pat. + 2. If a character matches, then move both txt and pat ahead and compare the next character. + 3. If a mismatch occurs, then move pat to the index where the mismatch occurs and compare again. + 4. If pat reaches its end without any mismatch, then pattern found. + + ''' + +def search(pat, txt): + M = len(pat) + N = len(txt) + + # A loop to slide pat[] one by one + for i in range(N - M + 1): + j = 0 + + # For current index i, check for pattern match + for j in range(0, M): + if (txt[i + j] != pat[j]): + break + + if (j == M - 1): + print("Pattern found at index ", i) + + +# Driver Code +if __name__ == '__main__': + txt = "AABAACAADAABAAABAA" + pat = "AABA" + search(pat, txt) \ No newline at end of file From 4345f148511d0738e36e91a04e60d72a07cc7809 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:40:27 +0530 Subject: [PATCH 1193/1894] add binary tree diameter --- Trees/Binary Trees/binary_tree_diameter.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Trees/Binary Trees/binary_tree_diameter.go diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/binary_tree_diameter.go new file mode 100644 index 00000000..e69de29b From b2927e6e44b85451e52e98d6a140a4ce226022cf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:41:13 +0530 Subject: [PATCH 1194/1894] add question --- Trees/Binary Trees/binary_tree_diameter.go | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/binary_tree_diameter.go index e69de29b..03c310d4 100644 --- a/Trees/Binary Trees/binary_tree_diameter.go +++ b/Trees/Binary Trees/binary_tree_diameter.go @@ -0,0 +1,58 @@ +/* + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. +*/ +package main + +// This is an input class. Do not edit. +type BinaryTree struct { + Value int + + Left *BinaryTree + Right *BinaryTree +} + +type TreeInfo struct { + height int + diameter int +} + +// Calculates the diameter of a binary tree. +func BinaryTreeDiameter(tree *BinaryTree) int { + return getTreeInfo(tree).diameter +} + +// Recursively calculates the height and diameter of the binary tree. +func getTreeInfo(tree *BinaryTree) TreeInfo { + // Base case: If the tree is nil, return height 0 and diameter 0. + if tree == nil { + return TreeInfo{0, 0} + } + + // Recursively calculate the height and diameter of the left and right subtrees. + leftTreeInfo := getTreeInfo(tree.Left) + rightTreeInfo := getTreeInfo(tree.Right) + + // Calculate the longest path passing through the root node. + longestPathThroughRoot := leftTreeInfo.height + rightTreeInfo.height + + // Calculate the maximum diameter seen so far. + maxDiameterSoFar := max(leftTreeInfo.diameter, rightTreeInfo.diameter) + + // Calculate the current diameter, which is the maximum among the longest path through root and max diameter so far. + currentDiameter := max(longestPathThroughRoot, maxDiameterSoFar) + + // Calculate the current height, which is the maximum height among the left and right subtrees plus 1. + currentHeight := 1 + max(leftTreeInfo.height, rightTreeInfo.height) + + // Return the current height and diameter as the tree information. + return TreeInfo{currentHeight, currentDiameter} +} + +// Returns the maximum of two integers. +func max(a, b int) int { + if a > b { + return a + } + return b +} From 849f2a5f7bd7556af31eddece2c689558532f0ea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:42:13 +0530 Subject: [PATCH 1195/1894] add sample io --- Trees/Binary Trees/binary_tree_diameter.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/binary_tree_diameter.go index 03c310d4..ca707bba 100644 --- a/Trees/Binary Trees/binary_tree_diameter.go +++ b/Trees/Binary Trees/binary_tree_diameter.go @@ -1,6 +1,19 @@ /* - Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. + + Sample Input : + 1 + / \ + 3 2 + / \ + 7 4 + / \ + 8 5 + / \ + 9 6 + Output: 6 + Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 */ package main From 1f8f5f07a8b5359b8cedebf6f083e35e7cb4d66a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:42:56 +0530 Subject: [PATCH 1196/1894] add explanation --- Trees/Binary Trees/binary_tree_diameter.go | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/binary_tree_diameter.go index ca707bba..5b6e5969 100644 --- a/Trees/Binary Trees/binary_tree_diameter.go +++ b/Trees/Binary Trees/binary_tree_diameter.go @@ -14,6 +14,36 @@ 9 6 Output: 6 Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 + + Explanation: + This code calculates the diameter of a binary tree, which is defined as the length of the longest path between any two + nodes in the tree. The BinaryTreeDiameter function takes the root of the binary tree as input and returns the diameter. + + The getTreeInfo function is a helper function that recursively calculates the height and diameter of the binary tree. + It takes a node of the binary tree as input and returns a TreeInfo struct containing the height and diameter of the tree. + + In the getTreeInfo function: + + The base case is when the tree is nil, indicating an empty tree. In this case, it returns a TreeInfo with height 0 and + diameter 0. + + The height and diameter of the left and right subtrees are calculated recursively by calling getTreeInfo on the left + and right child nodes. + + The longest path passing through the root node is determined by adding the heights of the left and right subtrees. + + The maximum diameter seen so far is calculated by taking the maximum of the diameters of the left and right subtrees. + + The current diameter is determined by taking the maximum among the longest path through the root and the maximum + diameter seen so far. + + The current height is calculated by taking the maximum height among the left and right subtrees and adding 1. + + Finally, the function returns a TreeInfo struct with the current height and diameter. + The max function is a helper function that returns the maximum of two integers. + + Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and + diameter of the tree and considering the longest path passing through the root. */ package main From 194d1ff6dfef2c121d1c604611d1029f0cc471bb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:43:53 +0530 Subject: [PATCH 1197/1894] add time and space complexity --- Trees/Binary Trees/binary_tree_diameter.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/binary_tree_diameter.go index 5b6e5969..af749bdb 100644 --- a/Trees/Binary Trees/binary_tree_diameter.go +++ b/Trees/Binary Trees/binary_tree_diameter.go @@ -44,6 +44,10 @@ Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and diameter of the tree and considering the longest path passing through the root. + + Average case: + Time Complexity O(n) when the tree is balanced + Space complexity: O(h) where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree */ package main From 15b1e4613fad6c9e350b6f2e8bbaecb049c6b1db Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:48:54 +0530 Subject: [PATCH 1198/1894] add binary tree diameter in cpp --- Trees/Binary Trees/binary_tree_diameter.cpp | 120 ++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_diameter.cpp diff --git a/Trees/Binary Trees/binary_tree_diameter.cpp b/Trees/Binary Trees/binary_tree_diameter.cpp new file mode 100644 index 00000000..e58b4a78 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_diameter.cpp @@ -0,0 +1,120 @@ +/* + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. + + Sample Input : + 1 + / \ + 3 2 + / \ + 7 4 + / \ + 8 5 + / \ + 9 6 + Output: 6 + Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 + + Explanation: + This code calculates the diameter of a binary tree, which is defined as the length of the longest path between any two + nodes in the tree. The BinaryTreeDiameter function takes the root of the binary tree as input and returns the diameter. + + The getTreeInfo function is a helper function that recursively calculates the height and diameter of the binary tree. + It takes a node of the binary tree as input and returns a TreeInfo struct containing the height and diameter of the tree. + + In the getTreeInfo function: + + The base case is when the tree is nil, indicating an empty tree. In this case, it returns a TreeInfo with height 0 and + diameter 0. + + The height and diameter of the left and right subtrees are calculated recursively by calling getTreeInfo on the left + and right child nodes. + + The longest path passing through the root node is determined by adding the heights of the left and right subtrees. + + The maximum diameter seen so far is calculated by taking the maximum of the diameters of the left and right subtrees. + + The current diameter is determined by taking the maximum among the longest path through the root and the maximum + diameter seen so far. + + The current height is calculated by taking the maximum height among the left and right subtrees and adding 1. + + Finally, the function returns a TreeInfo struct with the current height and diameter. + The max function is a helper function that returns the maximum of two integers. + + Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and + diameter of the tree and considering the longest path passing through the root. + + Average case: + Time Complexity O(n) when the tree is balanced + Space complexity: O(h) where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree +*/ +#include + +struct BinaryTree { + int value; + BinaryTree* left; + BinaryTree* right; +}; + +struct TreeInfo { + int height; + int diameter; +}; + +// Calculates the diameter of a binary tree. +int BinaryTreeDiameter(BinaryTree* tree) { + return getTreeInfo(tree).diameter; +} + +// Recursively calculates the height and diameter of the binary tree. +TreeInfo getTreeInfo(BinaryTree* tree) { + // Base case: If the tree is nullptr, return height 0 and diameter 0. + if (tree == nullptr) { + return {0, 0}; + } + + // Recursively calculate the height and diameter of the left and right subtrees. + TreeInfo leftTreeInfo = getTreeInfo(tree->left); + TreeInfo rightTreeInfo = getTreeInfo(tree->right); + + // Calculate the longest path passing through the root node. + int longestPathThroughRoot = leftTreeInfo.height + rightTreeInfo.height; + + // Calculate the maximum diameter seen so far. + int maxDiameterSoFar = std::max(leftTreeInfo.diameter, rightTreeInfo.diameter); + + // Calculate the current diameter, which is the maximum among the longest path through root and max diameter so far. + int currentDiameter = std::max(longestPathThroughRoot, maxDiameterSoFar); + + // Calculate the current height, which is the maximum height among the left and right subtrees plus 1. + int currentHeight = 1 + std::max(leftTreeInfo.height, rightTreeInfo.height); + + // Return the current height and diameter as the tree information. + return {currentHeight, currentDiameter}; +} + +// Returns the maximum of two integers. +int max(int a, int b) { + return (a > b) ? a : b; +} + +int main() { + // Test the BinaryTreeDiameter function with a sample binary tree + BinaryTree* tree = new BinaryTree{1, + new BinaryTree{2, + new BinaryTree{4, nullptr, nullptr}, + new BinaryTree{5, nullptr, nullptr}}, + new BinaryTree{3, + nullptr, + new BinaryTree{6, + new BinaryTree{7, nullptr, nullptr}, + nullptr}}}; + + int diameter = BinaryTreeDiameter(tree); + std::cout << "Diameter of the binary tree: " << diameter << std::endl; + + delete tree; + + return 0; +} From f64f3fdbfbef54f185dc25afd8ff65c2d019a261 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:50:32 +0530 Subject: [PATCH 1199/1894] add binary tree diameter in java --- Trees/Binary Trees/binary_tree_diameter.java | 118 +++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_diameter.java diff --git a/Trees/Binary Trees/binary_tree_diameter.java b/Trees/Binary Trees/binary_tree_diameter.java new file mode 100644 index 00000000..6e0addb2 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_diameter.java @@ -0,0 +1,118 @@ +/* + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. + + Sample Input : + 1 + / \ + 3 2 + / \ + 7 4 + / \ + 8 5 + / \ + 9 6 + Output: 6 + Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 + + Explanation: + This code calculates the diameter of a binary tree, which is defined as the length of the longest path between any two + nodes in the tree. The BinaryTreeDiameter function takes the root of the binary tree as input and returns the diameter. + + The getTreeInfo function is a helper function that recursively calculates the height and diameter of the binary tree. + It takes a node of the binary tree as input and returns a TreeInfo struct containing the height and diameter of the tree. + + In the getTreeInfo function: + + The base case is when the tree is nil, indicating an empty tree. In this case, it returns a TreeInfo with height 0 and + diameter 0. + + The height and diameter of the left and right subtrees are calculated recursively by calling getTreeInfo on the left + and right child nodes. + + The longest path passing through the root node is determined by adding the heights of the left and right subtrees. + + The maximum diameter seen so far is calculated by taking the maximum of the diameters of the left and right subtrees. + + The current diameter is determined by taking the maximum among the longest path through the root and the maximum + diameter seen so far. + + The current height is calculated by taking the maximum height among the left and right subtrees and adding 1. + + Finally, the function returns a TreeInfo struct with the current height and diameter. + The max function is a helper function that returns the maximum of two integers. + + Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and + diameter of the tree and considering the longest path passing through the root. + + Average case: + Time Complexity O(n) when the tree is balanced + Space complexity: O(h) where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree +*/ +public class BinaryTree { + int value; + BinaryTree left; + BinaryTree right; + + public BinaryTree(int value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +class TreeInfo { + int height; + int diameter; + + public TreeInfo(int height, int diameter) { + this.height = height; + this.diameter = diameter; + } +} + +public class Main { + // Calculates the diameter of a binary tree. + public static int binaryTreeDiameter(BinaryTree tree) { + return getTreeInfo(tree).diameter; + } + + // Recursively calculates the height and diameter of the binary tree. + private static TreeInfo getTreeInfo(BinaryTree tree) { + // Base case: If the tree is null, return height 0 and diameter 0. + if (tree == null) { + return new TreeInfo(0, 0); + } + + // Recursively calculate the height and diameter of the left and right subtrees. + TreeInfo leftTreeInfo = getTreeInfo(tree.left); + TreeInfo rightTreeInfo = getTreeInfo(tree.right); + + // Calculate the longest path passing through the root node. + int longestPathThroughRoot = leftTreeInfo.height + rightTreeInfo.height; + + // Calculate the maximum diameter seen so far. + int maxDiameterSoFar = Math.max(leftTreeInfo.diameter, rightTreeInfo.diameter); + + // Calculate the current diameter, which is the maximum among the longest path through root and max diameter so far. + int currentDiameter = Math.max(longestPathThroughRoot, maxDiameterSoFar); + + // Calculate the current height, which is the maximum height among the left and right subtrees plus 1. + int currentHeight = Math.max(leftTreeInfo.height, rightTreeInfo.height) + 1; + + // Return the current height and diameter as the tree information. + return new TreeInfo(currentHeight, currentDiameter); + } + + public static void main(String[] args) { + // Example usage + BinaryTree tree = new BinaryTree(1); + tree.left = new BinaryTree(2); + tree.right = new BinaryTree(3); + tree.left.left = new BinaryTree(4); + tree.left.right = new BinaryTree(5); + + int diameter = binaryTreeDiameter(tree); + System.out.println("Diameter of the binary tree: " + diameter); + } +} From b52e8cefd8d0c569f19bbec147f46021093b221a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:51:42 +0530 Subject: [PATCH 1200/1894] add binary tree diameter in python --- Trees/Binary Trees/binary_tree_diameter.py | 98 ++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_diameter.py diff --git a/Trees/Binary Trees/binary_tree_diameter.py b/Trees/Binary Trees/binary_tree_diameter.py new file mode 100644 index 00000000..49def1bd --- /dev/null +++ b/Trees/Binary Trees/binary_tree_diameter.py @@ -0,0 +1,98 @@ +''' + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. + + Sample Input : + 1 + / \ + 3 2 + / \ + 7 4 + / \ + 8 5 + / \ + 9 6 + Output: 6 + Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 + + Explanation: + This code calculates the diameter of a binary tree, which is defined as the length of the longest path between any two + nodes in the tree. The BinaryTreeDiameter function takes the root of the binary tree as input and returns the diameter. + + The getTreeInfo function is a helper function that recursively calculates the height and diameter of the binary tree. + It takes a node of the binary tree as input and returns a TreeInfo struct containing the height and diameter of the tree. + + In the getTreeInfo function: + + The base case is when the tree is nil, indicating an empty tree. In this case, it returns a TreeInfo with height 0 and + diameter 0. + + The height and diameter of the left and right subtrees are calculated recursively by calling getTreeInfo on the left + and right child nodes. + + The longest path passing through the root node is determined by adding the heights of the left and right subtrees. + + The maximum diameter seen so far is calculated by taking the maximum of the diameters of the left and right subtrees. + + The current diameter is determined by taking the maximum among the longest path through the root and the maximum + diameter seen so far. + + The current height is calculated by taking the maximum height among the left and right subtrees and adding 1. + + Finally, the function returns a TreeInfo struct with the current height and diameter. + The max function is a helper function that returns the maximum of two integers. + + Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and + diameter of the tree and considering the longest path passing through the root. + + Average case: + Time Complexity O(n) when the tree is balanced + Space complexity: O(h) where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree +''' +class BinaryTree: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + +class TreeInfo: + def __init__(self, height, diameter): + self.height = height + self.diameter = diameter + +def binary_tree_diameter(tree): + return get_tree_info(tree).diameter + +def get_tree_info(tree): + # Base case: If the tree is None, return height 0 and diameter 0. + if tree is None: + return TreeInfo(0, 0) + + # Recursively calculate the height and diameter of the left and right subtrees. + left_tree_info = get_tree_info(tree.left) + right_tree_info = get_tree_info(tree.right) + + # Calculate the longest path passing through the root node. + longest_path_through_root = left_tree_info.height + right_tree_info.height + + # Calculate the maximum diameter seen so far. + max_diameter_so_far = max(left_tree_info.diameter, right_tree_info.diameter) + + # Calculate the current diameter, which is the maximum among the longest path through root and max diameter so far. + current_diameter = max(longest_path_through_root, max_diameter_so_far) + + # Calculate the current height, which is the maximum height among the left and right subtrees plus 1. + current_height = max(left_tree_info.height, right_tree_info.height) + 1 + + # Return the current height and diameter as the tree information. + return TreeInfo(current_height, current_diameter) + +# Example usage +tree = BinaryTree(1) +tree.left = BinaryTree(2) +tree.right = BinaryTree(3) +tree.left.left = BinaryTree(4) +tree.left.right = BinaryTree(5) + +diameter = binary_tree_diameter(tree) +print("Diameter of the binary tree:", diameter) From 81029192d22dbb4385c6c1fa620a2d994004dd92 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:52:48 +0530 Subject: [PATCH 1201/1894] add binary tree diameter in javascript --- Trees/Binary Trees/binary_tree_diameter.js | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Trees/Binary Trees/binary_tree_diameter.js diff --git a/Trees/Binary Trees/binary_tree_diameter.js b/Trees/Binary Trees/binary_tree_diameter.js new file mode 100644 index 00000000..934f4097 --- /dev/null +++ b/Trees/Binary Trees/binary_tree_diameter.js @@ -0,0 +1,108 @@ +/* + Write a function that takes in a Binary Tree and returns its diameter. The diameter of a binary tree + is defined as the length of its longest path, even if that path doesn't pass through the root of the tree. + + Sample Input : + 1 + / \ + 3 2 + / \ + 7 4 + / \ + 8 5 + / \ + 9 6 + Output: 6 + Diameter being 9 -> 8 -> 7 -> 3 -> 4 -> 5 -> 6 + + Explanation: + This code calculates the diameter of a binary tree, which is defined as the length of the longest path between any two + nodes in the tree. The BinaryTreeDiameter function takes the root of the binary tree as input and returns the diameter. + + The getTreeInfo function is a helper function that recursively calculates the height and diameter of the binary tree. + It takes a node of the binary tree as input and returns a TreeInfo struct containing the height and diameter of the tree. + + In the getTreeInfo function: + + The base case is when the tree is nil, indicating an empty tree. In this case, it returns a TreeInfo with height 0 and + diameter 0. + + The height and diameter of the left and right subtrees are calculated recursively by calling getTreeInfo on the left + and right child nodes. + + The longest path passing through the root node is determined by adding the heights of the left and right subtrees. + + The maximum diameter seen so far is calculated by taking the maximum of the diameters of the left and right subtrees. + + The current diameter is determined by taking the maximum among the longest path through the root and the maximum + diameter seen so far. + + The current height is calculated by taking the maximum height among the left and right subtrees and adding 1. + + Finally, the function returns a TreeInfo struct with the current height and diameter. + The max function is a helper function that returns the maximum of two integers. + + Overall, the code effectively calculates the diameter of a binary tree by recursively calculating the height and + diameter of the tree and considering the longest path passing through the root. + + Average case: + Time Complexity O(n) when the tree is balanced + Space complexity: O(h) where n is the number of nodes in the Binary Tree and h is the height of the Binary Tree +*/ +class BinaryTree { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +class TreeInfo { + constructor(height, diameter) { + this.height = height; + this.diameter = diameter; + } +} + +function binaryTreeDiameter(tree) { + return getTreeInfo(tree).diameter; +} + +function getTreeInfo(tree) { + // Base case: If the tree is null, return height 0 and diameter 0. + if (tree === null) { + return new TreeInfo(0, 0); + } + + // Recursively calculate the height and diameter of the left and right subtrees. + const leftTreeInfo = getTreeInfo(tree.left); + const rightTreeInfo = getTreeInfo(tree.right); + + // Calculate the longest path passing through the root node. + const longestPathThroughRoot = leftTreeInfo.height + rightTreeInfo.height; + + // Calculate the maximum diameter seen so far. + const maxDiameterSoFar = Math.max( + leftTreeInfo.diameter, + rightTreeInfo.diameter + ); + + // Calculate the current diameter, which is the maximum among the longest path through root and max diameter so far. + const currentDiameter = Math.max(longestPathThroughRoot, maxDiameterSoFar); + + // Calculate the current height, which is the maximum height among the left and right subtrees plus 1. + const currentHeight = Math.max(leftTreeInfo.height, rightTreeInfo.height) + 1; + + // Return the current height and diameter as the tree information. + return new TreeInfo(currentHeight, currentDiameter); +} + +// Example usage +const tree = new BinaryTree(1); +tree.left = new BinaryTree(2); +tree.right = new BinaryTree(3); +tree.left.left = new BinaryTree(4); +tree.left.right = new BinaryTree(5); + +const diameter = binaryTreeDiameter(tree); +console.log("Diameter of the binary tree:", diameter); From 6d8347f441b0210245ccb1a93abb7ae134eec73c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 25 May 2023 22:54:52 +0530 Subject: [PATCH 1202/1894] remove duplicates --- .../binary_tree_diameter_of_a_tree.cpp | 69 ------------------- ...binary_tree_diameter_of_a_tree_optimal.cpp | 68 ------------------ 2 files changed, 137 deletions(-) delete mode 100644 Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp delete mode 100644 Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp diff --git a/Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp b/Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp deleted file mode 100644 index 896e21f8..00000000 --- a/Trees/Binary Trees/binary_tree_diameter_of_a_tree.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// Binary Tree : Diameter of tree O(n^2) -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : 7 -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} -int calculate_height(Node* root){ - if(root == NULL) - return 0; - int left_height = calculate_height(root->left); - int right_height = calculate_height(root->right); - return max(left_height, right_height) + 1; - -} - -int calculate_diameter_of_tree(Node* root){ - if(root == NULL) - return 0; - int left_height = calculate_height(root->left); - int right_height = calculate_height(root->right); - int option1 = left_height + right_height; // if diameter passes through root - int option2 = calculate_diameter_of_tree(root->left); // if diameter lies in left subtree - int option3 = calculate_diameter_of_tree(root->right); // if diameter lies in right subtree - return max(option1, max(option2, option3)); -} - - -int main(){ - Node* root = build_binary_tree(); - int diameter = calculate_diameter_of_tree(root); - cout << "Diameter of tree is : " << diameter << endl; - return 0; -} diff --git a/Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp b/Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp deleted file mode 100644 index 683e1254..00000000 --- a/Trees/Binary Trees/binary_tree_diameter_of_a_tree_optimal.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// Binary Tree : Diameter of tree O(n) -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : Height : 5 - Diameter : 7 -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -class Pair{ - public: - int height; - int diameter; -}; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} -Pair compute_diameter(Node* root){ - Pair p; - if(root == NULL){ - p.height = 0; - p.diameter = 0; - return p; - } - Pair left = compute_diameter(root->left); - Pair right = compute_diameter(root->right); - p.height = max(left.height, right.height) + 1; - p.diameter = max(left.height + right.height, max(left.diameter, right.diameter)); - return p; -} -int main(){ - Node* root = build_binary_tree(); - Pair p = compute_diameter(root); - cout << p.height << endl; - cout << p.diameter << endl; - return 0; -} \ No newline at end of file From 877c51951ffd52072ea4c6b28d1c6fdaa5f7e888 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 26 May 2023 00:47:45 +0530 Subject: [PATCH 1203/1894] add dfs in c++ --- Trees/Binary Trees/dfs.cpp | 87 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Trees/Binary Trees/dfs.cpp diff --git a/Trees/Binary Trees/dfs.cpp b/Trees/Binary Trees/dfs.cpp new file mode 100644 index 00000000..8732fb28 --- /dev/null +++ b/Trees/Binary Trees/dfs.cpp @@ -0,0 +1,87 @@ +// Implementation of Depth First Search +/* + This code demonstrates a basic implementation of Depth-First Search (DFS) on a graph represented by nodes. + It uses a recursive approach to traverse the graph in a depth-first manner, printing the values of the visited nodes. + The algorithm maintains a set of visited nodes to avoid visiting the same node multiple times. + The DFS function serves as the entry point to start the DFS traversal, and the dfsHelper + function recursively visits each node and its children. + Sample Input : + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Output : 1 2 4 5 3 6 7 + + The time complexity of Depth-First Search (DFS) on a graph is O(V + E), where V represents the number of vertices (nodes) + in the graph and E represents the number of edges. In the worst case, DFS may visit all vertices and edges of the graph. + + The space complexity of DFS is determined by the maximum depth of the recursion stack. In the case of a tree-like + structure, where each node has only one child, the maximum depth is equal to the height of the tree. + Therefore, the space complexity of DFS on such a tree-like structure is O(H), where H represents the height of the tree. + In the worst case, where the graph is a linear structure, the height of the tree is equal to the number of vertices, + so the space complexity becomes O(V). +*/ +#include +#include +#include + +using namespace std; + +// Node represents a node in a graph. +struct Node { + int value; + vector children; +}; + +// DFS traverses the graph using Depth-First Search starting from the given node. +void DFS(Node* node) { + // Create a set to keep track of visited nodes. + unordered_map visited; + + // Call the recursive helper function to perform DFS. + dfsHelper(node, visited); +} + +// dfsHelper is a recursive function that performs Depth-First Search on the graph. +void dfsHelper(Node* node, unordered_map& visited) { + // Mark the current node as visited. + visited[node] = true; + + // Process the current node (print its value in this case). + cout << node->value << endl; + + // Traverse the children of the current node. + for (Node* child : node->children) { + // If the child node has not been visited, recursively call dfsHelper on it. + if (!visited[child]) { + dfsHelper(child, visited); + } + } +} + +int main() { + // Create a sample graph. + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Node node1{1}; + Node node2{2}; + Node node3{3}; + Node node4{4}; + Node node5{5}; + Node node6{6}; + Node node7{7}; + + node1.children = {&node2, &node3}; + node2.children = {&node4, &node5}; + node3.children = {&node6, &node7}; + + // Perform DFS starting from node1. + cout << "Depth-First Search:" << endl; + DFS(&node1); + + return 0; +} From d8ed12ed43dba234b2d8939e5a55e3957e51b4b0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 26 May 2023 00:49:25 +0530 Subject: [PATCH 1204/1894] add dfs in java --- Trees/Binary Trees/dfs.java | 96 +++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Trees/Binary Trees/dfs.java diff --git a/Trees/Binary Trees/dfs.java b/Trees/Binary Trees/dfs.java new file mode 100644 index 00000000..acf9a7ff --- /dev/null +++ b/Trees/Binary Trees/dfs.java @@ -0,0 +1,96 @@ +// Implementation of Depth First Search +/* + This code demonstrates a basic implementation of Depth-First Search (DFS) on a graph represented by nodes. + It uses a recursive approach to traverse the graph in a depth-first manner, printing the values of the visited nodes. + The algorithm maintains a set of visited nodes to avoid visiting the same node multiple times. + The DFS function serves as the entry point to start the DFS traversal, and the dfsHelper + function recursively visits each node and its children. + Sample Input : + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Output : 1 2 4 5 3 6 7 + + The time complexity of Depth-First Search (DFS) on a graph is O(V + E), where V represents the number of vertices (nodes) + in the graph and E represents the number of edges. In the worst case, DFS may visit all vertices and edges of the graph. + + The space complexity of DFS is determined by the maximum depth of the recursion stack. In the case of a tree-like + structure, where each node has only one child, the maximum depth is equal to the height of the tree. + Therefore, the space complexity of DFS on such a tree-like structure is O(H), where H represents the height of the tree. + In the worst case, where the graph is a linear structure, the height of the tree is equal to the number of vertices, + so the space complexity becomes O(V). +*/ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +// Node represents a node in a graph. +class Node { + int value; + List children; + + public Node(int value) { + this.value = value; + this.children = new ArrayList<>(); + } +} + +// DFS traverses the graph using Depth-First Search starting from the given node. +class DepthFirstSearch { + public static void DFS(Node node) { + // Create a set to keep track of visited nodes. + Set visited = new HashSet<>(); + + // Call the recursive helper function to perform DFS. + dfsHelper(node, visited); + } + + // dfsHelper is a recursive function that performs Depth-First Search on the graph. + private static void dfsHelper(Node node, Set visited) { + // Mark the current node as visited. + visited.add(node); + + // Process the current node (print its value in this case). + System.out.println(node.value); + + // Traverse the children of the current node. + for (Node child : node.children) { + // If the child node has not been visited, recursively call dfsHelper on it. + if (!visited.contains(child)) { + dfsHelper(child, visited); + } + } + } +} + +public class Main { + public static void main(String[] args) { + // Create a sample graph. + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Node node1 = new Node(1); + Node node2 = new Node(2); + Node node3 = new Node(3); + Node node4 = new Node(4); + Node node5 = new Node(5); + Node node6 = new Node(6); + Node node7 = new Node(7); + + node1.children.add(node2); + node1.children.add(node3); + node2.children.add(node4); + node2.children.add(node5); + node3.children.add(node6); + node3.children.add(node7); + + // Perform DFS starting from node1. + System.out.println("Depth-First Search:"); + DepthFirstSearch.DFS(node1); + } +} From db48ae5a363670e154c3d2781272c62c74540d76 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 26 May 2023 00:51:22 +0530 Subject: [PATCH 1205/1894] add dfs in python --- Trees/Binary Trees/dfs.py | 74 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Trees/Binary Trees/dfs.py diff --git a/Trees/Binary Trees/dfs.py b/Trees/Binary Trees/dfs.py new file mode 100644 index 00000000..8a8014ec --- /dev/null +++ b/Trees/Binary Trees/dfs.py @@ -0,0 +1,74 @@ +''' + Implementation of Depth First Search + + This code demonstrates a basic implementation of Depth-First Search (DFS) on a graph represented by nodes. + It uses a recursive approach to traverse the graph in a depth-first manner, printing the values of the visited nodes. + The algorithm maintains a set of visited nodes to avoid visiting the same node multiple times. + The DFS function serves as the entry point to start the DFS traversal, and the dfsHelper + function recursively visits each node and its children. + Sample Input : + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Output : 1 2 4 5 3 6 7 + + The time complexity of Depth-First Search (DFS) on a graph is O(V + E), where V represents the number of vertices (nodes) + in the graph and E represents the number of edges. In the worst case, DFS may visit all vertices and edges of the graph. + + The space complexity of DFS is determined by the maximum depth of the recursion stack. In the case of a tree-like + structure, where each node has only one child, the maximum depth is equal to the height of the tree. + Therefore, the space complexity of DFS on such a tree-like structure is O(H), where H represents the height of the tree. + In the worst case, where the graph is a linear structure, the height of the tree is equal to the number of vertices, + so the space complexity becomes O(V). +''' +# Node represents a node in a graph. +class Node: + def __init__(self, value): + self.value = value + self.children = [] + +# DFS traverses the graph using Depth-First Search starting from the given node. +def DFS(node): + # Create a set to keep track of visited nodes. + visited = set() + + # Call the recursive helper function to perform DFS. + dfsHelper(node, visited) + +# dfsHelper is a recursive function that performs Depth-First Search on the graph. +def dfsHelper(node, visited): + # Mark the current node as visited. + visited.add(node) + + # Process the current node (print its value in this case). + print(node.value) + + # Traverse the children of the current node. + for child in node.children: + # If the child node has not been visited, recursively call dfsHelper on it. + if child not in visited: + dfsHelper(child, visited) + +# Create a sample graph. +# 1 +# / \ +# 2 3 +# / \ / \ +# 4 5 6 7 +node1 = Node(1) +node2 = Node(2) +node3 = Node(3) +node4 = Node(4) +node5 = Node(5) +node6 = Node(6) +node7 = Node(7) + +node1.children = [node2, node3] +node2.children = [node4, node5] +node3.children = [node6, node7] + +# Perform DFS starting from node1. +print("Depth-First Search:") +DFS(node1) From 2b67e34f2b55bcd0e85e73cb53ed9ceaf8ab3136 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 26 May 2023 00:52:59 +0530 Subject: [PATCH 1206/1894] add dfs in javascript --- Trees/Binary Trees/dfs.js | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Trees/Binary Trees/dfs.js diff --git a/Trees/Binary Trees/dfs.js b/Trees/Binary Trees/dfs.js new file mode 100644 index 00000000..ffcb6027 --- /dev/null +++ b/Trees/Binary Trees/dfs.js @@ -0,0 +1,79 @@ +// Implementation of Depth First Search +/* + This code demonstrates a basic implementation of Depth-First Search (DFS) on a graph represented by nodes. + It uses a recursive approach to traverse the graph in a depth-first manner, printing the values of the visited nodes. + The algorithm maintains a set of visited nodes to avoid visiting the same node multiple times. + The DFS function serves as the entry point to start the DFS traversal, and the dfsHelper + function recursively visits each node and its children. + Sample Input : + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + Output : 1 2 4 5 3 6 7 + + The time complexity of Depth-First Search (DFS) on a graph is O(V + E), where V represents the number of vertices (nodes) + in the graph and E represents the number of edges. In the worst case, DFS may visit all vertices and edges of the graph. + + The space complexity of DFS is determined by the maximum depth of the recursion stack. In the case of a tree-like + structure, where each node has only one child, the maximum depth is equal to the height of the tree. + Therefore, the space complexity of DFS on such a tree-like structure is O(H), where H represents the height of the tree. + In the worst case, where the graph is a linear structure, the height of the tree is equal to the number of vertices, + so the space complexity becomes O(V). +*/ +// Node represents a node in a graph. +class Node { + constructor(value) { + this.value = value; + this.children = []; + } +} + +// DFS traverses the graph using Depth-First Search starting from the given node. +function DFS(node) { + // Create a set to keep track of visited nodes. + let visited = new Set(); + + // Call the recursive helper function to perform DFS. + dfsHelper(node, visited); +} + +// dfsHelper is a recursive function that performs Depth-First Search on the graph. +function dfsHelper(node, visited) { + // Mark the current node as visited. + visited.add(node); + + // Process the current node (print its value in this case). + console.log(node.value); + + // Traverse the children of the current node. + for (let child of node.children) { + // If the child node has not been visited, recursively call dfsHelper on it. + if (!visited.has(child)) { + dfsHelper(child, visited); + } + } +} + +// Create a sample graph. +// 1 +// / \ +// 2 3 +// / \ / \ +// 4 5 6 7 +let node1 = new Node(1); +let node2 = new Node(2); +let node3 = new Node(3); +let node4 = new Node(4); +let node5 = new Node(5); +let node6 = new Node(6); +let node7 = new Node(7); + +node1.children = [node2, node3]; +node2.children = [node4, node5]; +node3.children = [node6, node7]; + +// Perform DFS starting from node1. +console.log("Depth-First Search:"); +DFS(node1); From 172e7fcbf6d48b2def77e61d0b54e8d451e1c52f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Fri, 26 May 2023 00:58:47 +0530 Subject: [PATCH 1207/1894] Rename Merge_Intervals.py to merge_intervals.py --- Arrays/{Merge_Intervals.py => merge_intervals.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{Merge_Intervals.py => merge_intervals.py} (100%) diff --git a/Arrays/Merge_Intervals.py b/Arrays/merge_intervals.py similarity index 100% rename from Arrays/Merge_Intervals.py rename to Arrays/merge_intervals.py From 4746a24e63681e19c45b39beeb6c7b43ca49fb3f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 26 May 2023 01:01:40 +0530 Subject: [PATCH 1208/1894] update links for merge intervals --- Arrays/{Merge_Intervals.py => merge_intervals.py} | 0 README.md | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename Arrays/{Merge_Intervals.py => merge_intervals.py} (100%) diff --git a/Arrays/Merge_Intervals.py b/Arrays/merge_intervals.py similarity index 100% rename from Arrays/Merge_Intervals.py rename to Arrays/merge_intervals.py diff --git a/README.md b/README.md index 6daf1a29..95260da8 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ Many problems in the real world use the merge intervals pattern. Let’s look at ## Practice problems for merge intervals -- Merge Intervals +- Merge Intervals [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.py) [Javacript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.js) - Insert Interval - Interval List Intersections - Employee Free Time From db96d99edf3f0031809f36101545967617a8fdae Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 27 May 2023 07:24:35 +0530 Subject: [PATCH 1209/1894] Create Validate_BST.cpp added the code --- Graphs/Validate_BST.cpp | 105 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Graphs/Validate_BST.cpp diff --git a/Graphs/Validate_BST.cpp b/Graphs/Validate_BST.cpp new file mode 100644 index 00000000..30d6fb81 --- /dev/null +++ b/Graphs/Validate_BST.cpp @@ -0,0 +1,105 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Validate BST in C++ +Issue Number : #1187 +Problem statement : + +Explanation of the below C++ code : + +First, we define the TreeNode structure, which represents a node in the BST. It has three members: val to store the node's value, and left and right pointers to the left and right child nodes, respectively. + +The isValidBSTHelper function is a recursive helper function that takes a TreeNode* as input along with the minimum and maximum values that the node's value should fall between. It performs the following checks: + +If the node is nullptr, it means we have reached the end of a subtree, so we return true (since an empty subtree is considered a valid BST). +If the node's value is less than or equal to the minimum value or greater than or equal to the maximum value, it violates the BST property, so we return false. +We recursively call isValidBSTHelper for the left and right subtrees, updating the minimum and maximum values accordingly. If both subtrees return true, the current subtree is a valid BST, so we return true. +The isValidBST function is the main function that calls the isValidBSTHelper function with the root node of the BST and the minimum and maximum values (LLONG_MIN and LLONG_MAX) as initial bounds. + +The insert function is used to dynamically construct the BST based on the user's input. It takes the root node and the value to be inserted as parameters. If the root node is nullptr, it means the tree is empty, so a new node is created with the given value and returned. Otherwise, based on the value being less than or greater than the root node's value, the function is recursively called on the left or right subtree, respectively. The function then updates the left or right child pointer of the root node accordingly. + +The deleteTree function is a recursive function that deallocates the memory allocated for the BST nodes. It takes the root node as input and performs a post-order traversal to delete the nodes. First, it recursively calls deleteTree for the left and right subtrees, and then it deletes the current node. + +In the main function, we start by declaring the root node as nullptr and a variable value to store the user's input. We prompt the user to enter values to construct the BST, and the input loop continues until the user enters -1. Inside the loop, we call the insert function to insert the entered value into the BST. + +After constructing the BST, we call the isValidBST function to check if the BST is valid. If it is, we print a message indicating that the BST is valid; otherwise, we print a message indicating that it's not valid. + +Finally, we clean up the memory allocated for the BST by calling the deleteTree function, passing the root node as the parameter. + +*/ + +-------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------- + +#include +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +bool isValidBSTHelper(TreeNode* node, long long minVal, long long maxVal) { + if (node == nullptr) + return true; + + if (node->val <= minVal || node->val >= maxVal) + return false; + + return isValidBSTHelper(node->left, minVal, node->val) && + isValidBSTHelper(node->right, node->val, maxVal); +} + +bool isValidBST(TreeNode* root) { + return isValidBSTHelper(root, LLONG_MIN, LLONG_MAX); +} + +TreeNode* insert(TreeNode* root, int value) { + if (root == nullptr) + return new TreeNode(value); + + if (value < root->val) + root->left = insert(root->left, value); + else + root->right = insert(root->right, value); + + return root; +} + +void deleteTree(TreeNode* root) { + if (root == nullptr) + return; + + deleteTree(root->left); + deleteTree(root->right); + + delete root; +} + +int main() { + TreeNode* root = nullptr; + int value; + + std::cout << "Enter values to construct the BST (enter -1 to stop):" << std::endl; + + while (true) { + std::cin >> value; + + if (value == -1) + break; + + root = insert(root, value); + } + + // Check if the BST is valid + if (isValidBST(root)) + std::cout << "The BST is valid." << std::endl; + else + std::cout << "The BST is not valid." << std::endl; + + // Clean up memory + deleteTree(root); + + return 0; +} From 97b37e43a1d09bc1d8121be8a90ad5624f9fbfc9 Mon Sep 17 00:00:00 2001 From: Sulabh Jha <66020896+sulabh007@users.noreply.github.com> Date: Sat, 27 May 2023 13:29:24 +0530 Subject: [PATCH 1210/1894] Add files via upload comments explaining wave sort using dry run of an example --- sorting/wave_sort.cpp | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/sorting/wave_sort.cpp b/sorting/wave_sort.cpp index 77ae2b82..4f744ad4 100644 --- a/sorting/wave_sort.cpp +++ b/sorting/wave_sort.cpp @@ -1,6 +1,9 @@ #include /* +Wave sort, also known as "odd-even sort," is a simple sorting algorithm that works by repeatedly +comparing and swapping adjacent elements in an array until the array is sorted. +The algorithm gets its name from the pattern of element swaps, which resembles a wave-like motion. In this sorting method we arrange array in Arr[0] >=arr[1]<=arr[2]>=arr[3]<=arr[4]………. Like a wave */ @@ -45,4 +48,55 @@ elements are greater than their adjacent odd elements, we don’t need to worry - Traverse all even positioned elements of the input array, and do the following. - If the current element is smaller than the previous odd element, swap the previous and current. - If the current element is smaller than the next odd element, swap next and current. +*/ + +/* +Dry-Run +Consider the array: [7, 2, 5, 1, 8, 3] + +Step 1: + +Start with the initial array: [7, 2, 5, 1, 8, 3] +In the first iteration, we compare and swap adjacent elements at even indices (0, 2, 4). +Compare 7 and 2: 7 > 2, so we swap them. Array becomes: [2, 7, 5, 1, 8, 3] +Compare 7 and 8: 7 < 8, so no swap is needed. +After the first phase, the array becomes: [2, 7, 5, 1, 8, 3] +Step 2: + +In the second iteration, we compare and swap adjacent elements at odd indices (1, 3, 5). +Compare 7 and 5: 7 > 5, so we swap them. Array becomes: [2, 5, 7, 1, 8, 3] +Compare 7 and 1: 7 > 1, so we swap them. Array becomes: [2, 5, 1, 7, 8, 3] +Compare 7 and 3: 7 > 3, so we swap them. Array becomes: [2, 5, 1, 3, 8, 7] +After the second phase, the array becomes: [2, 5, 1, 3, 8, 7] +Step 3: + +In the third iteration, we again compare and swap adjacent elements at even indices (0, 2, 4). +Compare 2 and 5: 2 < 5, so no swap is needed. +Compare 5 and 1: 5 > 1, so we swap them. Array becomes: [1, 5, 2, 3, 8, 7] +Compare 5 and 3: 5 > 3, so we swap them. Array becomes: [1, 3, 2, 5, 8, 7] +After the third phase, the array becomes: [1, 3, 2, 5, 8, 7] +Step 4: + +In the fourth iteration, we compare and swap adjacent elements at odd indices (1, 3, 5). +Compare 3 and 2: 3 > 2, so we swap them. Array becomes: [1, 2, 3, 5, 8, 7] +Compare 3 and 5: 3 < 5, so no swap is needed. +Compare 5 and 8: 5 < 8, so no swap is needed. +After the fourth phase, the array remains the same: [1, 2, 3, 5, 8, 7] +Step 5: + +In the fifth iteration, we again compare and swap adjacent elements at even indices (0, 2, 4). +Compare 1 and 2: 1 < 2, so no swap is needed. +Compare 2 and 3: 2 < 3, so no swap is needed. +Compare 3 and 5: 3 < 5, so no swap is needed. +After the fifth phase, the array remains the same: [1, 2, 3, 5, 8, 7] +Step 6: + +In the sixth iteration, we compare and swap adjacent elements at odd indices (1, 3, 5). +Compare 2 and 3: 2 < 3, so no swap is needed. +Compare 3 and 5: 3 < 5, so no swap is needed. +Compare 5 and 7: 5 < 7, so no swap is needed. +After the sixth phase, the array remains the same: [1, 2, 3, 5, 8, 7] +Since no more swaps occur in the array, the algorithm terminates, and the array is considered sorted. + +Final sorted array: [1, 2, 3, 5, 7, 8] */ \ No newline at end of file From 6d5014a60e960effbf3ddf11ca4b0b43dad0b8d9 Mon Sep 17 00:00:00 2001 From: Neelesh Aggarwal <86107529+AggarwalNeelesh@users.noreply.github.com> Date: Sat, 27 May 2023 15:22:44 +0530 Subject: [PATCH 1211/1894] Correcting the Constraints --- Dynamic Programming/distance_of_nearest_0.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Dynamic Programming/distance_of_nearest_0.cpp b/Dynamic Programming/distance_of_nearest_0.cpp index 9c6465fd..0f51b913 100644 --- a/Dynamic Programming/distance_of_nearest_0.cpp +++ b/Dynamic Programming/distance_of_nearest_0.cpp @@ -20,8 +20,8 @@ Output: [[0,0,0],[0,1,0],[1,2,1]] m == mat.length n == mat[i].length -1 <= m, n <= 104 -1 <= m * n <= 104 +1 <= m, n <= 10^4 +1 <= m * n <= 10^4 mat[i][j] is either 0 or 1. There is at least one 0 in mat. From 6b691945890b1bc78e716d450348ded406552705 Mon Sep 17 00:00:00 2001 From: tapan0p Date: Sat, 27 May 2023 22:58:00 +0530 Subject: [PATCH 1212/1894] solved Find first duplicate value in Javascript #1083 --- Arrays/find_first_duplicate_value.js | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Arrays/find_first_duplicate_value.js diff --git a/Arrays/find_first_duplicate_value.js b/Arrays/find_first_duplicate_value.js new file mode 100644 index 00000000..b0aa4df7 --- /dev/null +++ b/Arrays/find_first_duplicate_value.js @@ -0,0 +1,51 @@ +/* + Given an array of integers between 1 and n, inclusive, where n is the length of the array, write a function + that returns the first integer that appears more than once (when the array is read from left to right). + + Sample Input = [2, 1, 5, 2, 3, 3, 4] + Output : 2 + + +*/ + +// O(n) time and O(1) space solution. +// Approach: The approach utilizes the fact that the array contains integers between 1 and n, +// where n is the length of the array. By negating the values at specific indices, +// we can track which numbers have appeared before. If a number has appeared before, +// its corresponding index will have a negative value. +// This allows us to identify the first duplicate encountered during the iteration. +function findFirstDuplicate(nums){ + let n=nums.length; + for(let i=0;i Date: Sat, 27 May 2023 23:39:59 +0530 Subject: [PATCH 1213/1894] add height balanced binary tree in go --- .../height_balanced_binary_tree.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Trees/Binary Trees/height_balanced_binary_tree.go diff --git a/Trees/Binary Trees/height_balanced_binary_tree.go b/Trees/Binary Trees/height_balanced_binary_tree.go new file mode 100644 index 00000000..9756ba77 --- /dev/null +++ b/Trees/Binary Trees/height_balanced_binary_tree.go @@ -0,0 +1,64 @@ +package main + +// This is an input class. Do not edit. +type BinaryTree struct { + Value int + + Left *BinaryTree + Right *BinaryTree +} + +type TreeeInfo struct { + isBalanced bool + height int +} + +// HeightBalancedBinaryTree checks if a binary tree is height-balanced. +func HeightBalancedBinaryTree(tree *BinaryTree) bool { + // Retrieve the tree information using the helper function. + treeInfo := getTreeInfo(tree) + + // Return the balance status of the tree. + return treeInfo.isBalanced +} + +// getTreeInfo retrieves the information of a binary tree, including its balance status and height. +func getTreeInfo(tree *BinaryTree) TreeeInfo { + // Base case: If the tree is nil, it is considered balanced with height -1. + if tree == nil { + return TreeeInfo{isBalanced: true, height: -1} + } + + // Recursively calculate the tree information of the left and right subtrees. + leftSubtreeInfo := getTreeInfo(tree.Left) + rightSubtreeInfo := getTreeInfo(tree.Right) + + // Check if both left and right subtrees are balanced and their height difference is at most 1. + isBalanced := leftSubtreeInfo.isBalanced && rightSubtreeInfo.isBalanced && + abs(leftSubtreeInfo.height - rightSubtreeInfo.height) <= 1 + + // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1. + height := max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1 + + // Create and return the tree information. + return TreeeInfo{ + isBalanced: isBalanced, + height: height, + } +} + +// max returns the maximum of two integers. +func max(a, b int) int { + if a > b { + return a + } + return b +} + +// abs returns the absolute value of an integer. +func abs(a int) int { + if a < 0 { + return -a + } + return a +} From d3eec1d394e2200b532c9a9582e9928450c91935 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 27 May 2023 23:40:45 +0530 Subject: [PATCH 1214/1894] add question --- Trees/Binary Trees/height_balanced_binary_tree.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Trees/Binary Trees/height_balanced_binary_tree.go b/Trees/Binary Trees/height_balanced_binary_tree.go index 9756ba77..aa5af400 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.go +++ b/Trees/Binary Trees/height_balanced_binary_tree.go @@ -1,3 +1,8 @@ +/* + You're given the root node of a Binary Tree. Write a function that returns true + if this Binary Tree is height balanced and false if it isn't. + +*/ package main // This is an input class. Do not edit. From 97387f948662b891e76b9df78d0ed69ad41798b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 27 May 2023 23:42:57 +0530 Subject: [PATCH 1215/1894] add explanation --- .../height_balanced_binary_tree.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Trees/Binary Trees/height_balanced_binary_tree.go b/Trees/Binary Trees/height_balanced_binary_tree.go index aa5af400..fa36f924 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.go +++ b/Trees/Binary Trees/height_balanced_binary_tree.go @@ -1,6 +1,42 @@ /* You're given the root node of a Binary Tree. Write a function that returns true if this Binary Tree is height balanced and false if it isn't. + + Explanation: + + The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: + + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + pointers to its left and right child nodes. + + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + the height of the tree. + + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + It takes the root of the tree as input and returns a boolean value indicating the balance status. + + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + of the tree. + + - In the `getTreeInfo` function, there are two base cases: + - If the current tree node is `nil`, it is considered balanced with height -1. + - If the current tree node is not `nil`, the function recursively calculates the tree information of its + left and right subtrees. + + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + balanced. + + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + adding 1. + + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + the absolute value of an integer. + + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. */ package main From 7b711ff07203bc0ea2eeb8aec3770193a3c8cc89 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 27 May 2023 23:43:37 +0530 Subject: [PATCH 1216/1894] add time and space complexity --- .../height_balanced_binary_tree.go | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/Trees/Binary Trees/height_balanced_binary_tree.go b/Trees/Binary Trees/height_balanced_binary_tree.go index fa36f924..f1468081 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.go +++ b/Trees/Binary Trees/height_balanced_binary_tree.go @@ -6,38 +6,50 @@ The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: - - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and pointers to its left and right child nodes. - - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean - field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing the height of the tree. - - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. It takes the root of the tree as input and returns a boolean value indicating the balance status. - - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. - It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height of the tree. - In the `getTreeInfo` function, there are two base cases: - If the current tree node is `nil`, it is considered balanced with height -1. - - If the current tree node is not `nil`, the function recursively calculates the tree information of its + - If the current tree node is not `nil`, the function recursively calculates the tree information of its left and right subtrees. - - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced - (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered balanced. - - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and adding 1. - - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get the absolute value of an integer. - To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. - + + The time complexity of the `HeightBalancedBinaryTree` function is O(N), where N is the number of nodes in the + binary tree. This is because the function needs to traverse each node of the tree once to calculate the tree + information. + + The space complexity of the `HeightBalancedBinaryTree` function is O(H), where H is the height of the binary tree. + This is because the recursive calls to the `getTreeInfo` function will utilize the call stack, and the maximum + depth of the recursive calls is equal to the height of the tree. Additionally, the space complexity of the + `getTreeInfo` function itself is O(1) as it uses a constant amount of space for the `TreeeInfo` struct. + + Overall, the space complexity is determined by the height of the binary tree, and the time complexity is + determined by the number of nodes in the binary tree. + */ package main From 65599e1839696274e792a145880f1258f17d152f Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Sun, 28 May 2023 08:19:34 +0000 Subject: [PATCH 1217/1894] resolved the issue #479 --- ...ast_position_ofELement_inSorted_array.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Arrays/First_last_position_ofELement_inSorted_array.java diff --git a/Arrays/First_last_position_ofELement_inSorted_array.java b/Arrays/First_last_position_ofELement_inSorted_array.java new file mode 100644 index 00000000..5a6bbecd --- /dev/null +++ b/Arrays/First_last_position_ofELement_inSorted_array.java @@ -0,0 +1,95 @@ + +/** + * Problem :- Find First and Last Position of Element in Sorted Array + https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ + + * Problem Statement:- + + Given an array of integers nums sorted in non-decreasing order, + find the starting and ending position of a given target value. + + If target is not found in the array, return [-1, -1]. + + You must write an algorithm with O(log n) runtime complexity. + + * SAMPLE I/O + Input: nums = [5,7,7,8,8,10], target = 8 + Output: [3,4] + + * + */ + +/** + * APPROACH :- Binary Search + + 1. We make a function 'BS' that takes the input [nums,target,indexfirst] , + where if indexfirst=true i.e we want the first element else the last element, + ans return an integer + + 2. For the first index: + In this function 'BS' it will Apply Binary Search, pass the Argument 'indexfirst'=true. + And if(nums[mid]==target),then we save the indx in a variable 'ans' and make end=mid-1; + this will happen till we reach the first occurence of the element + when the loop is over, + return the 'ans' at last, and store this in "arr[0]" + + + + 3. For the Last index: + Apply Binary Search, + pass the Argument 'indexfirst'=false. + And if(nums[mid]==target),then we save the indx in a variable 'ans' and make start=mid+1; + this will happen till we reach the last occurence of the element + when the loop is over + return the 'ans' at last, and store this in "arr[1]" + + Time Complexity :- O(log n) + Because of the application of binary search. + + Space Complexity :- O(1) + There is no extra space is used. + (the arr we return at last is always- arr.length==2, Hence Constant space ) + + */ + + + + +class Solution { + public int[] searchRange(int[] nums, int target) { + + int [] arr= {-1,-1};//return this if target is not found + arr[0]=BS(nums, target, true); + if(arr[0]==1) return arr; //means the target doesn't exist hence return {-1,-1} + + arr[1]=BS(nums, target, false); + + return arr; +} +static int BS(int []nums,int target,boolean indexfirst) { + int ans=-1;//potential ans + int start=0,end=nums.length-1; + while(start<=end) { + int mid=start+(end-start)/2; + + if(target>nums[mid]) { + start=mid+1; + } + + else if(target Date: Sun, 28 May 2023 16:06:32 +0530 Subject: [PATCH 1218/1894] Create check panagram.java --- Strings/check panagram.java | 85 +++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Strings/check panagram.java diff --git a/Strings/check panagram.java b/Strings/check panagram.java new file mode 100644 index 00000000..c854bc24 --- /dev/null +++ b/Strings/check panagram.java @@ -0,0 +1,85 @@ +/* + Check whether a string is a Panagram or not. + + Note that a string is a Panagram if it contains all the character of the alphabets ignoring the case of the alphabets + + For example, str = “Abcdefghijklmnopqrstuvwxyz” + Output: Yes + Explanation: The given string contains all the letters from a to z (ignoring case). + + str = "AbhayChetri" + Output: No + Explaination: The given string doesn't contain all the letters from a to z. +*/ + +class Abhay { + + static int size = 26; + + // Function to check if ch is a letter + static boolean isLetter(char ch) + { + if (!Character.isLetter(ch)) + return false; + + return true; + } + + // Function to check if a string + // contains all the letters from + // a to z + static boolean allLetter(String str, + int len) + { + // Convert the given string + // into lowercase + str = str.toLowerCase(); + + // Create a frequency array to + // mark the present letters + boolean[] present = new boolean[size]; + + // Traverse for each character + // of the string + for (int i = 0; i < len; i++) { + + // If the current character + // is a letter + if (isLetter(str.charAt(i))) { + + // Mark current letter as present + int letter = str.charAt(i) - 'a'; + present[letter] = true; + } + } + + // Traverse for every letter + // from a to z + for (int i = 0; i < size; i++) { + + // If the current character + // is not present in string + // then return false, + // otherwise return true + if (!present[i]) + return false; + } + return true; + } + + // Driver Code + public static void main(String args[]) + { + + // Given string str + String str = "Abcdefghijklmnopqrstuvwxyz"; + int len = str.length(); + + // Function Call + if (allLetter(str, len)) + System.out.println("Yes"); + else + System.out.println("No"); + } +} + From 54240dca1d129febb8545f20faab40c2040ba633 Mon Sep 17 00:00:00 2001 From: Kunal3Jadon Date: Sun, 28 May 2023 16:59:30 +0530 Subject: [PATCH 1219/1894] completed --- Hash Table/group_anagrams.class | Bin 0 -> 1697 bytes Hash Table/group_anagrams.java | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 Hash Table/group_anagrams.class diff --git a/Hash Table/group_anagrams.class b/Hash Table/group_anagrams.class new file mode 100644 index 0000000000000000000000000000000000000000..a43f6db1e9233ae988f5f38dc005485d74a94290 GIT binary patch literal 1697 zcma)7-*XdH6#i~Do4ZZ6P*Q>o*jkW6(xyZUEtr%*i6YoEpj%tgpm>w6>6T=-v)Q1$ z`%mbjFFZKRs1Gf%BjdAwhR^;5J`m5{B-0k+jFXwWckiC_o$ot8ZvK4r+e-jBIAH{! za0GRz2r-Ooizgyo7j`Xuud;1cJ%-StWm{g3K}jUnI5dV6zER7w>ghY8xwRs8!r)NC zh(PBU)^QBSk3booYuPo1i09OMwO~)k~ zYNDJ^uE`j0Nv^R7;yBH5M#tM2XBa-Ld6n=*M()18yxR2j2<}p z5ert+3u6L`3~)}zyEsqMcUnZ@+5nURxNjaws0%tSB0*3!lb|jPfJ(mU$T7`u?0}&p z7eNv!9kWukA~rWAcv{DMc%N$ZMATa*C2cIxL-SLacj|SjrRCUJDebaM;1z~=kHqUX zvdjw66Hg>yPc9fOkQfvO3`<9e1c^L&GJlFc#g|(>WIv{y>qf& zL6PI0j{EqOA$pL&z6k^063wFdE!BehdP8~`I#%&HHJt4qpX_5FnuhEU*71O&q+rvCTeIliVC1G3Ap#Skb{afS@5Mulp*xHw_Gy%G# z00lJu2+>-hw{dzhdaBcVV876Yp-QX#3>pO{+l(Bg>E8%qh@RiNpxife6*1@Hq#X}gaJf|zXMtb%p_ z(^LR|AQ=y}F%!W0cPe|<`AJ%(+PK89hq<3AbigM!jWF%Up<$Bd?;NJ+TA9XqQg{(J zk)SqBk=-OL8skl}ybPs77h{NHp2Osb)5=KSE95vL95q@y7?U@5&w!jPKioDcevCTh zL1y4NWgtY)hx?c(`d14hq2EcN61`@Wg3*joQlpDTDHP2aB_6$Ll(gtAV`V0_iw}#l zZQNnV1mnRr3Jl-lwA_8hr09(LE7s!bE*?JX{3UD9l{rCw1HcuMd6fiZFo)|TEr$oV efiek|(#{~zp--x>t4lt~Y5MRF>1Sy8VD`UB`h~jy literal 0 HcmV?d00001 diff --git a/Hash Table/group_anagrams.java b/Hash Table/group_anagrams.java index c6523e35..8114e97f 100644 --- a/Hash Table/group_anagrams.java +++ b/Hash Table/group_anagrams.java @@ -22,7 +22,7 @@ The space complexity of this implementation is O(n * k), as we need to store eac */ import java.util.*; -public class GroupAnagrams { +public class group_anagrams{ public List> groupAnagrams(String[] strs) { // Create a HashMap to store the groups of anagrams @@ -49,7 +49,7 @@ public List> groupAnagrams(String[] strs) { } public static void main(String[] args) { - GroupAnagrams ga = new GroupAnagrams(); + group_anagrams ga = new group_anagrams(); // Example input String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; From 499f75c83bf83ae2dc6de7afed4a0b4333c7bd25 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 28 May 2023 20:02:24 +0530 Subject: [PATCH 1220/1894] remove duplicate --- .../height_balanced_binary_tree.go | 37 +++++ Trees/Binary Trees/is_balanced.go | 154 ------------------ 2 files changed, 37 insertions(+), 154 deletions(-) delete mode 100644 Trees/Binary Trees/is_balanced.go diff --git a/Trees/Binary Trees/height_balanced_binary_tree.go b/Trees/Binary Trees/height_balanced_binary_tree.go index f1468081..ecf82710 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.go +++ b/Trees/Binary Trees/height_balanced_binary_tree.go @@ -53,6 +53,8 @@ */ package main +import "fmt" + // This is an input class. Do not edit. type BinaryTree struct { Value int @@ -115,3 +117,38 @@ func abs(a int) int { } return a } + +func main() { + // Create a binary tree + tree := &BinaryTree{ + Value: 1, + Left: &BinaryTree{ + Value: 2, + Left: &BinaryTree{ + Value: 4, + }, + Right: &BinaryTree{ + Value: 5, + }, + }, + Right: &BinaryTree{ + Value: 3, + Right: &BinaryTree{ + Value: 6, + Left: &BinaryTree{ + Value: 7, + }, + }, + }, + } + + // Check if the binary tree is height-balanced + isBalanced := HeightBalancedBinaryTree(tree) + + // Output the result + if isBalanced { + fmt.Println("The binary tree is height-balanced.") + } else { + fmt.Println("The binary tree is not height-balanced.") + } +} diff --git a/Trees/Binary Trees/is_balanced.go b/Trees/Binary Trees/is_balanced.go deleted file mode 100644 index 83cc4942..00000000 --- a/Trees/Binary Trees/is_balanced.go +++ /dev/null @@ -1,154 +0,0 @@ -/* - You're given the root node of a Binary Tree. Write a function that returns true if this Binary Tree is height balanced and - false if it isn't. - Sample Input: - 1 - / \ - 2 3 - / \ \ - 4 5 6 - / - 7 - Output: False - - Explanation: - - The code checks whether a given binary tree is height-balanced or not. A binary tree is height-balanced if - the heights of its left and right subtrees differ by at most 1, and both the left and right subtrees - are themselves height-balanced. - - The HeightBalancedBinaryTree function is the entry point of the code. It calls the getTreeInfo helper - function to retrieve the tree information, including the balance status and height. - - The getTreeInfo function recursively calculates the tree information of the current node by - obtaining the tree information of its left and right subtrees. It checks if both subtrees are - balanced and calculates the height of the current tree. - - The balance status is determined by checking if the left and right subtrees are balanced and if their - height difference is at most 1. - - The height of the current tree is the maximum height between the left and right subtrees plus 1. - - The max function returns the maximum of two integers, and the abs function returns the absolute value of an integer. - These helper functions are used in the main logic of the code. - - Overall, the code efficiently determines whether a binary tree is height-balanced by recursively calculating the tree information and checking the balance status based on height differences. - - The time complexity of the `HeightBalancedBinaryTree` function, which calls the `getTreeInfo` helper function, is O(n), where n is the number of nodes in the binary tree. - This is because the function traverses each node once in a depth-first manner, calculating the tree information for each node. - - The space complexity is O(h), where h is the height of the binary tree. This is because the recursive calls consume memory on the call - stack proportional to the height of the tree. In the worst case, for a skewed tree where the height is equal to the number of nodes, - the space complexity would be O(n). - - However, in a balanced binary tree, the height is logarithmic in the number of nodes, resulting in a space complexity of O(log n). - - Additionally, the `max` and `abs` helper functions have constant time complexity as they perform simple - mathematical operations on two integers. They do not depend on the size of the tree. - - Overall, the time complexity is O(n) and the space complexity is O(h) or O(log n) in the case of a - balanced binary tree. - -*/ - -package main - -import "fmt" - -// This is an input class. Do not edit. -type BinaryTree struct { - Value int - - Left *BinaryTree - Right *BinaryTree -} - -type TreeeInfo struct { - isBalanced bool - height int -} - -// HeightBalancedBinaryTree checks if a binary tree is height-balanced. -func HeightBalancedBinaryTree(tree *BinaryTree) bool { - // Retrieve the tree information using the helper function. - treeInfo := getTreeInfo(tree) - - // Return the balance status of the tree. - return treeInfo.isBalanced -} - -// getTreeInfo retrieves the information of a binary tree, including its balance status and height. -func getTreeInfo(tree *BinaryTree) TreeeInfo { - // Base case: If the tree is nil, it is considered balanced with height -1. - if tree == nil { - return TreeeInfo{isBalanced: true, height: -1} - } - - // Recursively calculate the tree information of the left and right subtrees. - leftSubtreeInfo := getTreeInfo(tree.Left) - rightSubtreeInfo := getTreeInfo(tree.Right) - - // Check if both left and right subtrees are balanced and their height difference is at most 1. - isBalanced := leftSubtreeInfo.isBalanced && rightSubtreeInfo.isBalanced && - abs(leftSubtreeInfo.height-rightSubtreeInfo.height) <= 1 - - // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1. - height := max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1 - - // Create and return the tree information. - return TreeeInfo{ - isBalanced: isBalanced, - height: height, - } -} - -// max returns the maximum of two integers. -func max(a, b int) int { - if a > b { - return a - } - return b -} - -// abs returns the absolute value of an integer. -func abs(a int) int { - if a < 0 { - return -a - } - return a -} - -func main() { - // Create a binary tree - tree := &BinaryTree{ - Value: 1, - Left: &BinaryTree{ - Value: 2, - Left: &BinaryTree{ - Value: 4, - }, - Right: &BinaryTree{ - Value: 5, - }, - }, - Right: &BinaryTree{ - Value: 3, - Right: &BinaryTree{ - Value: 6, - Left: &BinaryTree{ - Value: 7, - }, - }, - }, - } - - // Check if the binary tree is height-balanced - isBalanced := HeightBalancedBinaryTree(tree) - - // Output the result - if isBalanced { - fmt.Println("The binary tree is height-balanced.") - } else { - fmt.Println("The binary tree is not height-balanced.") - } -} From 2dd5bf41fa9359f2784a6c62ae2bfba279df6b34 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 28 May 2023 20:04:12 +0530 Subject: [PATCH 1221/1894] rename file --- Trees/Binary Trees/{binary_tree_diameter.cpp => diameter.cpp} | 0 Trees/Binary Trees/{binary_tree_diameter.go => diameter.go} | 0 Trees/Binary Trees/{binary_tree_diameter.java => diameter.java} | 0 Trees/Binary Trees/{binary_tree_diameter.js => diameter.js} | 0 .../{binary_tree_inorder_traversal.cpp => inorder_traversal.cpp} | 0 ...y_tree_level_order_traversal.cpp => level_order_traversal.cpp} | 0 .../{binary_tree_level_order.go => level_order_traversal.go} | 0 ...inary_tree_postorder_traversal.cpp => postorder_traversal.cpp} | 0 ...{binary_tree_preorder_traversal.cpp => preorder_traversal.cpp} | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename Trees/Binary Trees/{binary_tree_diameter.cpp => diameter.cpp} (100%) rename Trees/Binary Trees/{binary_tree_diameter.go => diameter.go} (100%) rename Trees/Binary Trees/{binary_tree_diameter.java => diameter.java} (100%) rename Trees/Binary Trees/{binary_tree_diameter.js => diameter.js} (100%) rename Trees/Binary Trees/{binary_tree_inorder_traversal.cpp => inorder_traversal.cpp} (100%) rename Trees/Binary Trees/{binary_tree_level_order_traversal.cpp => level_order_traversal.cpp} (100%) rename Trees/Binary Trees/{binary_tree_level_order.go => level_order_traversal.go} (100%) rename Trees/Binary Trees/{binary_tree_postorder_traversal.cpp => postorder_traversal.cpp} (100%) rename Trees/Binary Trees/{binary_tree_preorder_traversal.cpp => preorder_traversal.cpp} (100%) diff --git a/Trees/Binary Trees/binary_tree_diameter.cpp b/Trees/Binary Trees/diameter.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_diameter.cpp rename to Trees/Binary Trees/diameter.cpp diff --git a/Trees/Binary Trees/binary_tree_diameter.go b/Trees/Binary Trees/diameter.go similarity index 100% rename from Trees/Binary Trees/binary_tree_diameter.go rename to Trees/Binary Trees/diameter.go diff --git a/Trees/Binary Trees/binary_tree_diameter.java b/Trees/Binary Trees/diameter.java similarity index 100% rename from Trees/Binary Trees/binary_tree_diameter.java rename to Trees/Binary Trees/diameter.java diff --git a/Trees/Binary Trees/binary_tree_diameter.js b/Trees/Binary Trees/diameter.js similarity index 100% rename from Trees/Binary Trees/binary_tree_diameter.js rename to Trees/Binary Trees/diameter.js diff --git a/Trees/Binary Trees/binary_tree_inorder_traversal.cpp b/Trees/Binary Trees/inorder_traversal.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_inorder_traversal.cpp rename to Trees/Binary Trees/inorder_traversal.cpp diff --git a/Trees/Binary Trees/binary_tree_level_order_traversal.cpp b/Trees/Binary Trees/level_order_traversal.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_level_order_traversal.cpp rename to Trees/Binary Trees/level_order_traversal.cpp diff --git a/Trees/Binary Trees/binary_tree_level_order.go b/Trees/Binary Trees/level_order_traversal.go similarity index 100% rename from Trees/Binary Trees/binary_tree_level_order.go rename to Trees/Binary Trees/level_order_traversal.go diff --git a/Trees/Binary Trees/binary_tree_postorder_traversal.cpp b/Trees/Binary Trees/postorder_traversal.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_postorder_traversal.cpp rename to Trees/Binary Trees/postorder_traversal.cpp diff --git a/Trees/Binary Trees/binary_tree_preorder_traversal.cpp b/Trees/Binary Trees/preorder_traversal.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_preorder_traversal.cpp rename to Trees/Binary Trees/preorder_traversal.cpp From c759108c1cdd3f79a6fd46956949050d444ea673 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 28 May 2023 20:04:21 +0530 Subject: [PATCH 1222/1894] rename file --- Trees/Binary Trees/{binary_tree_diameter.py => diameter.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Trees/Binary Trees/{binary_tree_diameter.py => diameter.py} (100%) diff --git a/Trees/Binary Trees/binary_tree_diameter.py b/Trees/Binary Trees/diameter.py similarity index 100% rename from Trees/Binary Trees/binary_tree_diameter.py rename to Trees/Binary Trees/diameter.py From c8c85b07c3264f3175b9ab0e896bf7f549cba510 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 28 May 2023 20:07:39 +0530 Subject: [PATCH 1223/1894] rename file --- .../{binary_tree_bfs.cpp => bfs.cpp} | 0 ..._create_tree_from_preorder_and_inorder.cpp | 88 --------------- ..._tree_replace_parent_with_sum_of_child.cpp | 100 ------------------ ...e_preorder.cpp => build_tree_preorder.cpp} | 0 ...ee_calculate_size.go => calculate_size.go} | 0 ...y_tree_count_nodes.cpp => count_nodes.cpp} | 0 .../{binary_tree_delete.go => delete.go} | 0 ..._find_branch_sum.go => find_branch_sum.go} | 0 .../{binary_tree_find_max.go => find_max.go} | 0 ...ary_tree_compute_height.cpp => height.cpp} | 0 .../{binary_tree_height.go => height.go} | 0 ...ed.cpp => height_balanced_binary_tree.cpp} | 0 .../{binary_tree_invert.go => invert.go} | 0 ..._level_by_level.cpp => level_by_level.cpp} | 0 ...inary_tree_node_depth.go => node_depth.go} | 0 ...ove_leaf_nodes.go => remove_leaf_nodes.go} | 0 ...rch_an_element.go => search_an_element.go} | 0 ..._of_all_nodes.cpp => sum_of_all_nodes.cpp} | 0 18 files changed, 188 deletions(-) rename Trees/Binary Trees/{binary_tree_bfs.cpp => bfs.cpp} (100%) delete mode 100644 Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp delete mode 100644 Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp rename Trees/Binary Trees/{binary_tree_build_tree_preorder.cpp => build_tree_preorder.cpp} (100%) rename Trees/Binary Trees/{binary_tree_calculate_size.go => calculate_size.go} (100%) rename Trees/Binary Trees/{binary_tree_count_nodes.cpp => count_nodes.cpp} (100%) rename Trees/Binary Trees/{binary_tree_delete.go => delete.go} (100%) rename Trees/Binary Trees/{binary_tree_find_branch_sum.go => find_branch_sum.go} (100%) rename Trees/Binary Trees/{binary_tree_find_max.go => find_max.go} (100%) rename Trees/Binary Trees/{binary_tree_compute_height.cpp => height.cpp} (100%) rename Trees/Binary Trees/{binary_tree_height.go => height.go} (100%) rename Trees/Binary Trees/{binary_tree_is_height_balanced.cpp => height_balanced_binary_tree.cpp} (100%) rename Trees/Binary Trees/{binary_tree_invert.go => invert.go} (100%) rename Trees/Binary Trees/{binary_tree_bfs_print_level_by_level.cpp => level_by_level.cpp} (100%) rename Trees/Binary Trees/{binary_tree_node_depth.go => node_depth.go} (100%) rename Trees/Binary Trees/{binary_tree_remove_leaf_nodes.go => remove_leaf_nodes.go} (100%) rename Trees/Binary Trees/{binary_tree_search_an_element.go => search_an_element.go} (100%) rename Trees/Binary Trees/{binary_tree_sum_of_all_nodes.cpp => sum_of_all_nodes.cpp} (100%) diff --git a/Trees/Binary Trees/binary_tree_bfs.cpp b/Trees/Binary Trees/bfs.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_bfs.cpp rename to Trees/Binary Trees/bfs.cpp diff --git a/Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp b/Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp deleted file mode 100644 index 7bbba478..00000000 --- a/Trees/Binary Trees/binary_tree_create_tree_from_preorder_and_inorder.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// Binary Tree : Create binary tree from preorder and inorder traversal -// Program Author : Abhisek Kumar Gupta -/* - Input : No of elements : 8 - Inorder : 4 8 2 5 1 6 3 7 - Preorder : 1 2 4 8 5 3 6 7 - Output : - 1 - / \ - 2 3 - / \ / \ - 4 5 6 7 - / - 8 -*/ -#include -using namespace std; -const int some_number = 1004; -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - } -}; -void bfs(Node* root){ - queue q; - q.push(root); - q.push(NULL); - while (!q.empty()){ - Node* element = q.front(); - if(element == NULL){ - cout << "\n"; - q.pop(); - if(!q.empty()){ - q.push(NULL); - } - } - else{ - q.pop(); - cout << element->data << "->"; - if(element->left != NULL){ - q.push(element->left); - } - if(element->right != NULL){ - q.push(element->right); - } - } - } - return; -} -Node* create_tree_from_preorder_and_inorder(int *Inorder, int *Preorder, int start, int end){ - static int i = 0; - if(start > end){ - return NULL; - } - int index = -1; - Node* root = new Node(Preorder[i]); - for(int j = start; j <= end; j++){ - if(Preorder[i] == Inorder[j]){ - index = j; - break; - } - } - i++; - root->left = create_tree_from_preorder_and_inorder(Inorder, Preorder, start, index - 1); - root->right = create_tree_from_preorder_and_inorder(Inorder, Preorder, index + 1, end); - return root; - -} -int main(){ - int In[some_number]; - int Pre[some_number]; - int no_of_elements; - cin >> no_of_elements; - int end = no_of_elements - 1; - int start = 0; - for(int i = 0; i < no_of_elements; i++) - cin >> Pre[i]; - for(int i = 0; i < no_of_elements; i++) - cin >> In[i]; - Node* root = create_tree_from_preorder_and_inorder(In, Pre, start, end); - bfs(root); - return 0; -} \ No newline at end of file diff --git a/Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp b/Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp deleted file mode 100644 index cfff790e..00000000 --- a/Trees/Binary Trees/binary_tree_replace_parent_with_sum_of_child.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// Binary Tree : Replace parent with sum of child nodes -// Program Author : Abhisek Kumar Gupta -/* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : Tree before replacing parent with sum of child nodes - 40-> - 10->30-> - 5->28-> - 1->15->20-> - 1-> - Tree after replacing parent with sum of child nodes - 110-> - 7->63-> - 2->35-> - 1->15->20-> - 1-> - -*/ - -#include -using namespace std; -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -void bfs(Node* root){ - queue q; - q.push(root); - q.push(NULL); - while(!q.empty()){ - Node* element = q.front(); - if(element == NULL){ - cout << "\n"; - q.pop(); - if(!q.empty()){ - q.push(NULL); - } - } - else{ - q.pop(); - cout << element->data << "->"; - if(element->left != NULL){ - q.push(element->left); - } - if(element->right != NULL){ - q.push(element->right); - } - } - } -} -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} - -int replace_parent_with_sum_of_child(Node* root){ - if(root == NULL){ - return 0; - } - if(root->left == NULL && root->right == NULL){ - return root->data; - } - int left_sum = replace_parent_with_sum_of_child(root->left); - int right_sum = replace_parent_with_sum_of_child(root->right); - int temp = root->data; - root->data = left_sum + right_sum; - return root->data + temp; -} -int main(){ - Node* root = build_binary_tree(); - bfs(root); - replace_parent_with_sum_of_child(root); - cout << endl; - bfs(root); -} \ No newline at end of file diff --git a/Trees/Binary Trees/binary_tree_build_tree_preorder.cpp b/Trees/Binary Trees/build_tree_preorder.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_build_tree_preorder.cpp rename to Trees/Binary Trees/build_tree_preorder.cpp diff --git a/Trees/Binary Trees/binary_tree_calculate_size.go b/Trees/Binary Trees/calculate_size.go similarity index 100% rename from Trees/Binary Trees/binary_tree_calculate_size.go rename to Trees/Binary Trees/calculate_size.go diff --git a/Trees/Binary Trees/binary_tree_count_nodes.cpp b/Trees/Binary Trees/count_nodes.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_count_nodes.cpp rename to Trees/Binary Trees/count_nodes.cpp diff --git a/Trees/Binary Trees/binary_tree_delete.go b/Trees/Binary Trees/delete.go similarity index 100% rename from Trees/Binary Trees/binary_tree_delete.go rename to Trees/Binary Trees/delete.go diff --git a/Trees/Binary Trees/binary_tree_find_branch_sum.go b/Trees/Binary Trees/find_branch_sum.go similarity index 100% rename from Trees/Binary Trees/binary_tree_find_branch_sum.go rename to Trees/Binary Trees/find_branch_sum.go diff --git a/Trees/Binary Trees/binary_tree_find_max.go b/Trees/Binary Trees/find_max.go similarity index 100% rename from Trees/Binary Trees/binary_tree_find_max.go rename to Trees/Binary Trees/find_max.go diff --git a/Trees/Binary Trees/binary_tree_compute_height.cpp b/Trees/Binary Trees/height.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_compute_height.cpp rename to Trees/Binary Trees/height.cpp diff --git a/Trees/Binary Trees/binary_tree_height.go b/Trees/Binary Trees/height.go similarity index 100% rename from Trees/Binary Trees/binary_tree_height.go rename to Trees/Binary Trees/height.go diff --git a/Trees/Binary Trees/binary_tree_is_height_balanced.cpp b/Trees/Binary Trees/height_balanced_binary_tree.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_is_height_balanced.cpp rename to Trees/Binary Trees/height_balanced_binary_tree.cpp diff --git a/Trees/Binary Trees/binary_tree_invert.go b/Trees/Binary Trees/invert.go similarity index 100% rename from Trees/Binary Trees/binary_tree_invert.go rename to Trees/Binary Trees/invert.go diff --git a/Trees/Binary Trees/binary_tree_bfs_print_level_by_level.cpp b/Trees/Binary Trees/level_by_level.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_bfs_print_level_by_level.cpp rename to Trees/Binary Trees/level_by_level.cpp diff --git a/Trees/Binary Trees/binary_tree_node_depth.go b/Trees/Binary Trees/node_depth.go similarity index 100% rename from Trees/Binary Trees/binary_tree_node_depth.go rename to Trees/Binary Trees/node_depth.go diff --git a/Trees/Binary Trees/binary_tree_remove_leaf_nodes.go b/Trees/Binary Trees/remove_leaf_nodes.go similarity index 100% rename from Trees/Binary Trees/binary_tree_remove_leaf_nodes.go rename to Trees/Binary Trees/remove_leaf_nodes.go diff --git a/Trees/Binary Trees/binary_tree_search_an_element.go b/Trees/Binary Trees/search_an_element.go similarity index 100% rename from Trees/Binary Trees/binary_tree_search_an_element.go rename to Trees/Binary Trees/search_an_element.go diff --git a/Trees/Binary Trees/binary_tree_sum_of_all_nodes.cpp b/Trees/Binary Trees/sum_of_all_nodes.cpp similarity index 100% rename from Trees/Binary Trees/binary_tree_sum_of_all_nodes.cpp rename to Trees/Binary Trees/sum_of_all_nodes.cpp From 2790efb31e284df344e52664b842e9c5f793f24e Mon Sep 17 00:00:00 2001 From: abhayy143 Date: Sun, 28 May 2023 20:26:29 +0530 Subject: [PATCH 1224/1894] Update check panagram.java --- Strings/check panagram.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Strings/check panagram.java b/Strings/check panagram.java index c854bc24..cea8a9ec 100644 --- a/Strings/check panagram.java +++ b/Strings/check panagram.java @@ -10,6 +10,14 @@ str = "AbhayChetri" Output: No Explaination: The given string doesn't contain all the letters from a to z. + +Approach:- 1.Convert each letter of the string to the lower or upper case. + 2.Create a frequency array to mark the frequency of each letter from a to z. + 3.Then, traverse the frequency array and if there is any letter that is not present in the given string then print "No", otherwise print "Yes". + + Time Complexity: O(N) + Auxiliary Space: O(26) + */ class Abhay { From d145dca92db0e0350cfb6a92f814fedfb0d0e432 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 29 May 2023 08:22:50 +0530 Subject: [PATCH 1225/1894] Create reverse_words.java added the code of java --- Strings/reverse_words.java | 58 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Strings/reverse_words.java diff --git a/Strings/reverse_words.java b/Strings/reverse_words.java new file mode 100644 index 00000000..e19be5dc --- /dev/null +++ b/Strings/reverse_words.java @@ -0,0 +1,58 @@ +/*Name : Abhinav kumar +Github username : Abhinavcode13 +Repository name : data-structures-and-algorithms +Problem : Add Reverse Words in a String in Java +Issue Number : #349 +Problem statement : + +Explanation of the below Java code : + +First, we import the java.util.Scanner class, which allows us to take input from the user. + +We define a class called ReverseWordsInString. + +Inside the main method, we create a new Scanner object named scanner to read user input. + +We prompt the user to enter a string by using System.out.print("Enter a string: ") and then call scanner.nextLine() to read the user's input and store it in the input variable. + +Next, we call the reverseWords method and pass the input string as an argument. The reverseWords method takes the input string, splits it into an array of words using the split("\\s+") method (which splits the string based on whitespace), and stores the words in the words array. + +We create a StringBuilder named reversed to build the reversed string. + +Using a loop, we iterate over the words array in reverse order (starting from the last word) and append each word, followed by a space, to the reversed string. + +Finally, we return the reversed string by calling reversed.toString().trim(), which converts the StringBuilder to a String and trims any leading or trailing whitespace. + +The reversed string is then printed to the console using System.out.println("Reversed String: " + reversed). + +Finally, we close the Scanner object to release system resources by calling scanner.close(). + + + +*/ + +-------------------------------------------------------------------------//Java code begins here------------------------------------------------------------- + +import java.util.Scanner; + +public class ReverseWordsInString { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter a string: "); + String input = scanner.nextLine(); + String reversed = reverseWords(input); + System.out.println("Reversed String: " + reversed); + scanner.close(); + } + + public static String reverseWords(String input) { + String[] words = input.split("\\s+"); + StringBuilder reversed = new StringBuilder(); + + for (int i = words.length - 1; i >= 0; i--) { + reversed.append(words[i]).append(" "); + } + + return reversed.toString().trim(); + } +} From f034e7a4ed1b811856dfd4c3fbca8a9dc4f14a0a Mon Sep 17 00:00:00 2001 From: tapan0p Date: Mon, 29 May 2023 12:10:55 +0530 Subject: [PATCH 1226/1894] Hash Table: Roman to Integer in Javascript #394 added --- Hash Table/roman_to_integer.js | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hash Table/roman_to_integer.js diff --git a/Hash Table/roman_to_integer.js b/Hash Table/roman_to_integer.js new file mode 100644 index 00000000..20ea0479 --- /dev/null +++ b/Hash Table/roman_to_integer.js @@ -0,0 +1,35 @@ +// Approach: In case of symbols like IV, CM, XC, etc., the first value is less than the second value. +// So we have to subtract the first value from the second value to get the exact value. +// Example: CM --> C=100, M=1000, so CM=1000-100=900. +// Therefore, we can conclude that in such cases, we have to subtract the first value from the whole result. + +var romanToInt = function(s) { + let map = new Map(); // Create a hashmap to store (symbol, value) pairs. + map['I'] = 1; + map['V'] = 5; + map['X'] = 10; + map['L'] = 50; + map['C'] = 100; + map['D'] = 500; + map['M'] = 1000; + + let arr = []; + for (let i = 0; i < s.length; i++) { // Store the value of each symbol in arr from left to right. + arr[i] = map[s.charAt(i)]; + } + + let ans = 0; + for (let i = 0; i < arr.length - 1; i++) { // Traverse from 0 to last-1. + // If the i-th element is less than the i+1-th element, then subtract the i-th element. + if (arr[i] < arr[i + 1]) { + ans = ans - arr[i]; + } + // Otherwise, add the i-th element. + else { + ans = ans + arr[i]; + } + } + // Add the last element because there is no further element to compare. + ans = ans + arr[arr.length - 1]; + return ans; +}; From 2794605ca0ef5bd55742c3ba2367ea4051586fd8 Mon Sep 17 00:00:00 2001 From: Tapan_CS Date: Mon, 29 May 2023 16:54:54 +0530 Subject: [PATCH 1227/1894] Update roman_to_integer.js --- Hash Table/roman_to_integer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hash Table/roman_to_integer.js b/Hash Table/roman_to_integer.js index 20ea0479..f895aeba 100644 --- a/Hash Table/roman_to_integer.js +++ b/Hash Table/roman_to_integer.js @@ -2,7 +2,7 @@ // So we have to subtract the first value from the second value to get the exact value. // Example: CM --> C=100, M=1000, so CM=1000-100=900. // Therefore, we can conclude that in such cases, we have to subtract the first value from the whole result. - +// Time complexity O(1) and Space complexity O(1). var romanToInt = function(s) { let map = new Map(); // Create a hashmap to store (symbol, value) pairs. map['I'] = 1; From 89f9411e609ee8adbbbeb57a278693b9060d6fad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 29 May 2023 22:45:36 +0530 Subject: [PATCH 1228/1894] add height balanced binary tree in python --- .../height_balanced_binary_tree.py | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Trees/Binary Trees/height_balanced_binary_tree.py diff --git a/Trees/Binary Trees/height_balanced_binary_tree.py b/Trees/Binary Trees/height_balanced_binary_tree.py new file mode 100644 index 00000000..6ef13e42 --- /dev/null +++ b/Trees/Binary Trees/height_balanced_binary_tree.py @@ -0,0 +1,102 @@ +''' + You're given the root node of a Binary Tree. Write a function that returns true + if this Binary Tree is height balanced and false if it isn't. + + Explanation: + + The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: + + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + pointers to its left and right child nodes. + + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + the height of the tree. + + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + It takes the root of the tree as input and returns a boolean value indicating the balance status. + + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + of the tree. + + - In the `getTreeInfo` function, there are two base cases: + - If the current tree node is `nil`, it is considered balanced with height -1. + - If the current tree node is not `nil`, the function recursively calculates the tree information of its + left and right subtrees. + + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + balanced. + + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + adding 1. + + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + the absolute value of an integer. + + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. + + The time complexity of the `HeightBalancedBinaryTree` function is O(N), where N is the number of nodes in the + binary tree. This is because the function needs to traverse each node of the tree once to calculate the tree + information. + + The space complexity of the `HeightBalancedBinaryTree` function is O(H), where H is the height of the binary tree. + This is because the recursive calls to the `getTreeInfo` function will utilize the call stack, and the maximum + depth of the recursive calls is equal to the height of the tree. Additionally, the space complexity of the + `getTreeInfo` function itself is O(1) as it uses a constant amount of space for the `TreeeInfo` struct. + + Overall, the space complexity is determined by the height of the binary tree, and the time complexity is + determined by the number of nodes in the binary tree. + +''' + +# This is an input class. Do not edit. +class BinaryTree: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + +class TreeInfo: + def __init__(self, is_balanced, height): + self.is_balanced = is_balanced + self.height = height + +# Checks if a binary tree is height-balanced. +def height_balanced_binary_tree(tree): + # Retrieve the tree information using the helper function. + tree_info = get_tree_info(tree) + + # Return the balance status of the tree. + return tree_info.is_balanced + +# Retrieves the information of a binary tree, including its balance status and height. +def get_tree_info(tree): + # Base case: If the tree is None, it is considered balanced with height -1. + if tree is None: + return TreeInfo(True, -1) + + # Recursively calculate the tree information of the left and right subtrees. + left_subtree_info = get_tree_info(tree.left) + right_subtree_info = get_tree_info(tree.right) + + # Check if both left and right subtrees are balanced and their height difference is at most 1. + is_balanced = left_subtree_info.is_balanced and right_subtree_info.is_balanced and \ + abs(left_subtree_info.height - right_subtree_info.height) <= 1 + + # Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1. + height = max(left_subtree_info.height, right_subtree_info.height) + 1 + + # Create and return the tree information. + return TreeInfo(is_balanced, height) + +# Returns the maximum of two integers. +def max(a, b): + return a if a > b else b + +# Returns the absolute value of an integer. +def abs(a): + return -a if a < 0 else a + From 1a6de5dda4cefce621611559688adba2d07605fc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 29 May 2023 22:45:59 +0530 Subject: [PATCH 1229/1894] add main func --- .../height_balanced_binary_tree.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Trees/Binary Trees/height_balanced_binary_tree.py b/Trees/Binary Trees/height_balanced_binary_tree.py index 6ef13e42..c84809fd 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.py +++ b/Trees/Binary Trees/height_balanced_binary_tree.py @@ -100,3 +100,38 @@ def max(a, b): def abs(a): return -a if a < 0 else a +# Main function +def main(): + # Create a sample binary tree + # 1 + # / \ + # 2 3 + # / \ / + # 4 5 6 + node1 = BinaryTree(1) + node2 = BinaryTree(2) + node3 = BinaryTree(3) + node4 = BinaryTree(4) + node5 = BinaryTree(5) + node6 = BinaryTree(6) + + node1.left = node2 + node1.right = node3 + node2.left = node4 + node2.right = node5 + node3.left = node6 + + # Check if the binary tree is height-balanced + is_balanced = height_balanced_binary_tree(node1) + + # Print the result + if is_balanced: + print("The binary tree is height-balanced.") + else: + print("The binary tree is not height-balanced.") + +# Call the main function +if __name__ == "__main__": + main() + + From ffc249d7dd2b10845f70d50ed5216b7de9e02f15 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 29 May 2023 22:50:31 +0530 Subject: [PATCH 1230/1894] add height balanced binary tree in js --- .../height_balanced_binary_tree.js | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 Trees/Binary Trees/height_balanced_binary_tree.js diff --git a/Trees/Binary Trees/height_balanced_binary_tree.js b/Trees/Binary Trees/height_balanced_binary_tree.js new file mode 100644 index 00000000..66d1b308 --- /dev/null +++ b/Trees/Binary Trees/height_balanced_binary_tree.js @@ -0,0 +1,142 @@ +/* + You're given the root node of a Binary Tree. Write a function that returns true + if this Binary Tree is height balanced and false if it isn't. + + Explanation: + + The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: + + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + pointers to its left and right child nodes. + + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + the height of the tree. + + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + It takes the root of the tree as input and returns a boolean value indicating the balance status. + + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + of the tree. + + - In the `getTreeInfo` function, there are two base cases: + - If the current tree node is `nil`, it is considered balanced with height -1. + - If the current tree node is not `nil`, the function recursively calculates the tree information of its + left and right subtrees. + + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + balanced. + + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + adding 1. + + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + the absolute value of an integer. + + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. + + The time complexity of the `HeightBalancedBinaryTree` function is O(N), where N is the number of nodes in the + binary tree. This is because the function needs to traverse each node of the tree once to calculate the tree + information. + + The space complexity of the `HeightBalancedBinaryTree` function is O(H), where H is the height of the binary tree. + This is because the recursive calls to the `getTreeInfo` function will utilize the call stack, and the maximum + depth of the recursive calls is equal to the height of the tree. Additionally, the space complexity of the + `getTreeInfo` function itself is O(1) as it uses a constant amount of space for the `TreeeInfo` struct. + + Overall, the space complexity is determined by the height of the binary tree, and the time complexity is + determined by the number of nodes in the binary tree. + +*/ +// Node class represents a node in a binary tree +class BinaryTree { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +// TreeInfo class represents the information of a binary tree, including its balance status and height +class TreeInfo { + constructor(isBalanced, height) { + this.isBalanced = isBalanced; + this.height = height; + } +} + +// heightBalancedBinaryTree checks if a binary tree is height-balanced +function heightBalancedBinaryTree(tree) { + // Retrieve the tree information using the helper function + const treeInfo = getTreeInfo(tree); + + // Return the balance status of the tree + return treeInfo.isBalanced; +} + +// getTreeInfo retrieves the information of a binary tree, including its balance status and height +function getTreeInfo(tree) { + // Base case: If the tree is null, it is considered balanced with height -1 + if (tree === null) { + return new TreeInfo(true, -1); + } + + // Recursively calculate the tree information of the left and right subtrees + const leftSubtreeInfo = getTreeInfo(tree.left); + const rightSubtreeInfo = getTreeInfo(tree.right); + + // Check if both left and right subtrees are balanced and their height difference is at most 1 + const isBalanced = + leftSubtreeInfo.isBalanced && + rightSubtreeInfo.isBalanced && + Math.abs(leftSubtreeInfo.height - rightSubtreeInfo.height) <= 1; + + // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1 + const height = Math.max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1; + + // Create and return the tree information + return new TreeInfo(isBalanced, height); +} + +// Helper function to create a binary tree +function createBinaryTree(value) { + return new BinaryTree(value); +} + +// Main function +function main() { + // Create a sample binary tree + // 1 + // / \ + // 2 3 + // / \ / + // 4 5 6 + const node1 = createBinaryTree(1); + const node2 = createBinaryTree(2); + const node3 = createBinaryTree(3); + const node4 = createBinaryTree(4); + const node5 = createBinaryTree(5); + const node6 = createBinaryTree(6); + + node1.left = node2; + node1.right = node3; + node2.left = node4; + node2.right = node5; + node3.left = node6; + + // Check if the binary tree is height-balanced + const isBalanced = heightBalancedBinaryTree(node1); + + // Print the result + if (isBalanced) { + console.log("The binary tree is height-balanced."); + } else { + console.log("The binary tree is not height-balanced."); + } +} + +// Call the main function +main(); From 880e178515ff6e4bc7ad816e676ecfd74fdb4c53 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 29 May 2023 22:52:37 +0530 Subject: [PATCH 1231/1894] add height balanced binary tree in java --- .../height_balanced_binary_tree.java | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 Trees/Binary Trees/height_balanced_binary_tree.java diff --git a/Trees/Binary Trees/height_balanced_binary_tree.java b/Trees/Binary Trees/height_balanced_binary_tree.java new file mode 100644 index 00000000..da82efce --- /dev/null +++ b/Trees/Binary Trees/height_balanced_binary_tree.java @@ -0,0 +1,146 @@ +/* + You're given the root node of a Binary Tree. Write a function that returns true + if this Binary Tree is height balanced and false if it isn't. + + Explanation: + + The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: + + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + pointers to its left and right child nodes. + + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + the height of the tree. + + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + It takes the root of the tree as input and returns a boolean value indicating the balance status. + + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + of the tree. + + - In the `getTreeInfo` function, there are two base cases: + - If the current tree node is `nil`, it is considered balanced with height -1. + - If the current tree node is not `nil`, the function recursively calculates the tree information of its + left and right subtrees. + + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + balanced. + + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + adding 1. + + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + the absolute value of an integer. + + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. + + The time complexity of the `HeightBalancedBinaryTree` function is O(N), where N is the number of nodes in the + binary tree. This is because the function needs to traverse each node of the tree once to calculate the tree + information. + + The space complexity of the `HeightBalancedBinaryTree` function is O(H), where H is the height of the binary tree. + This is because the recursive calls to the `getTreeInfo` function will utilize the call stack, and the maximum + depth of the recursive calls is equal to the height of the tree. Additionally, the space complexity of the + `getTreeInfo` function itself is O(1) as it uses a constant amount of space for the `TreeeInfo` struct. + + Overall, the space complexity is determined by the height of the binary tree, and the time complexity is + determined by the number of nodes in the binary tree. + +*/ +// Node class represents a node in a binary tree +class BinaryTree { + int value; + BinaryTree left; + BinaryTree right; + + BinaryTree(int value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +// TreeInfo class represents the information of a binary tree, including its balance status and height +class TreeInfo { + boolean isBalanced; + int height; + + TreeInfo(boolean isBalanced, int height) { + this.isBalanced = isBalanced; + this.height = height; + } +} + +// heightBalancedBinaryTree checks if a binary tree is height-balanced +class HeightBalancedBinaryTree { + public static boolean heightBalancedBinaryTree(BinaryTree tree) { + // Retrieve the tree information using the helper function + TreeInfo treeInfo = getTreeInfo(tree); + + // Return the balance status of the tree + return treeInfo.isBalanced; + } + + // getTreeInfo retrieves the information of a binary tree, including its balance status and height + private static TreeInfo getTreeInfo(BinaryTree tree) { + // Base case: If the tree is null, it is considered balanced with height -1 + if (tree == null) { + return new TreeInfo(true, -1); + } + + // Recursively calculate the tree information of the left and right subtrees + TreeInfo leftSubtreeInfo = getTreeInfo(tree.left); + TreeInfo rightSubtreeInfo = getTreeInfo(tree.right); + + // Check if both left and right subtrees are balanced and their height difference is at most 1 + boolean isBalanced = leftSubtreeInfo.isBalanced && rightSubtreeInfo.isBalanced && + Math.abs(leftSubtreeInfo.height - rightSubtreeInfo.height) <= 1; + + // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1 + int height = Math.max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1; + + // Create and return the tree information + return new TreeInfo(isBalanced, height); + } + + // Helper function to create a binary tree + private static BinaryTree createBinaryTree(int value) { + return new BinaryTree(value); + } + + // Main function + public static void main(String[] args) { + // Create a sample binary tree + // 1 + // / \ + // 2 3 + // / \ / + // 4 5 6 + BinaryTree node1 = createBinaryTree(1); + BinaryTree node2 = createBinaryTree(2); + BinaryTree node3 = createBinaryTree(3); + BinaryTree node4 = createBinaryTree(4); + BinaryTree node5 = createBinaryTree(5); + BinaryTree node6 = createBinaryTree(6); + + node1.left = node2; + node1.right = node3; + node2.left = node4; + node2.right = node5; + node3.left = node6; + + // Check if the binary tree is height-balanced + boolean isBalanced = heightBalancedBinaryTree(node1); + + // Print the result + if (isBalanced) { + System.out.println("The binary tree is height-balanced."); + } else { + System.out.println("The binary tree is not height-balanced."); + } + } +} From e600720083e8ce9541eb646de6d4c767cd2e8850 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 29 May 2023 22:59:11 +0530 Subject: [PATCH 1232/1894] add height balanced binary tree in c++ --- .../height_balanced_binary_tree.cpp | 220 +++++++++++------- 1 file changed, 140 insertions(+), 80 deletions(-) diff --git a/Trees/Binary Trees/height_balanced_binary_tree.cpp b/Trees/Binary Trees/height_balanced_binary_tree.cpp index 9b5f8d8c..5a9a7a59 100644 --- a/Trees/Binary Trees/height_balanced_binary_tree.cpp +++ b/Trees/Binary Trees/height_balanced_binary_tree.cpp @@ -1,91 +1,151 @@ -// Binary Tree : Replace parent with sum of child nodes -// Program Author : Abhisek Kumar Gupta /* - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - -1 -1 -1 -1 - - Input : 40 10 5 -1 -1 -1 30 -1 28 -1 -1 - Output : Height : 3 - Yes it's Balanced - - 40 - / \ - 10 30 - / \ / \ - 5 -1 -1 28 - / \ / \ - 1 -1 15 20 - / \ /\ /\ - 1 -1 -1 -1 -1 -1 - /\ - -1 -1 - Input : 40 10 5 1 1 -1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 - Output : Height : 5 - No it's not Balanced - -*/ + You're given the root node of a Binary Tree. Write a function that returns true + if this Binary Tree is height balanced and false if it isn't. + + Explanation: + + The provided code is for checking whether a binary tree is height-balanced or not. Here's how it works: + + - The code defines a `BinaryTree` struct representing a node in a binary tree. Each node has a value and + pointers to its left and right child nodes. + + - The code also defines a `TreeeInfo` struct to store information about a binary tree. It includes a boolean + field `isBalanced` indicating whether the tree is balanced or not, and an integer field `height` representing + the height of the tree. + + - The `HeightBalancedBinaryTree` function is the main function that checks if a binary tree is height-balanced. + It takes the root of the tree as input and returns a boolean value indicating the balance status. + + - The `getTreeInfo` function is a helper function that recursively calculates the information of a binary tree. + It takes a binary tree node as input and returns the `TreeeInfo` struct containing the balance status and height + of the tree. + + - In the `getTreeInfo` function, there are two base cases: + - If the current tree node is `nil`, it is considered balanced with height -1. + - If the current tree node is not `nil`, the function recursively calculates the tree information of its + left and right subtrees. + + - After getting the information of the left and right subtrees, the code checks if both subtrees are balanced + (`isBalanced` field is `true`) and their height difference is at most 1. If so, the current tree is considered + balanced. + + - The height of the current tree is calculated by taking the maximum height of the left and right subtrees and + adding 1. -#include -using namespace std; + - Finally, the `max` function is used to get the maximum of two integers, and the `abs` function is used to get + the absolute value of an integer. -class Node{ - public: - int data; - Node* left; - Node* right; + To determine whether a binary tree is height-balanced, you can call the `HeightBalancedBinaryTree` function with + the root of the tree. It will return `true` if the tree is balanced and `false` otherwise. - Node(int x){ - data = x; - left = NULL; - right = NULL; - } + The time complexity of the `HeightBalancedBinaryTree` function is O(N), where N is the number of nodes in the + binary tree. This is because the function needs to traverse each node of the tree once to calculate the tree + information. + + The space complexity of the `HeightBalancedBinaryTree` function is O(H), where H is the height of the binary tree. + This is because the recursive calls to the `getTreeInfo` function will utilize the call stack, and the maximum + depth of the recursive calls is equal to the height of the tree. Additionally, the space complexity of the + `getTreeInfo` function itself is O(1) as it uses a constant amount of space for the `TreeeInfo` struct. + + Overall, the space complexity is determined by the height of the binary tree, and the time complexity is + determined by the number of nodes in the binary tree. + +*/ +#include +#include + +// Node class represents a node in a binary tree +class BinaryTree { +public: + int value; + BinaryTree* left; + BinaryTree* right; + + BinaryTree(int value) { + this->value = value; + this->left = nullptr; + this->right = nullptr; + } }; -class Height_Balanced{ - public: - int height; - bool balance; + +// TreeInfo class represents the information of a binary tree, including its balance status and height +class TreeInfo { +public: + bool isBalanced; + int height; + + TreeInfo(bool isBalanced, int height) { + this->isBalanced = isBalanced; + this->height = height; + } }; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1) - return NULL; - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; + +// heightBalancedBinaryTree checks if a binary tree is height-balanced +bool heightBalancedBinaryTree(BinaryTree* tree) { + // Retrieve the tree information using the helper function + TreeInfo treeInfo = getTreeInfo(tree); + + // Return the balance status of the tree + return treeInfo.isBalanced; } -Height_Balanced is_height_balanced(Node* root){ - Height_Balanced p; - if(root == NULL){ - p.height = 0; - p.balance = true; - return p; - } - Height_Balanced left = is_height_balanced(root->left); - Height_Balanced right = is_height_balanced(root->right); - p.height = max(left.height, right.height) + 1; - if(abs(left.height - right.height) <= 1 && left.balance && right.balance){ - p.balance = true; - } - else{ - p.balance = false; + +// getTreeInfo retrieves the information of a binary tree, including its balance status and height +TreeInfo getTreeInfo(BinaryTree* tree) { + // Base case: If the tree is nullptr, it is considered balanced with height -1 + if (tree == nullptr) { + return TreeInfo(true, -1); } - return p; + + // Recursively calculate the tree information of the left and right subtrees + TreeInfo leftSubtreeInfo = getTreeInfo(tree->left); + TreeInfo rightSubtreeInfo = getTreeInfo(tree->right); + + // Check if both left and right subtrees are balanced and their height difference is at most 1 + bool isBalanced = leftSubtreeInfo.isBalanced && rightSubtreeInfo.isBalanced && + std::abs(leftSubtreeInfo.height - rightSubtreeInfo.height) <= 1; + + // Calculate the height of the current tree by taking the maximum height of the left and right subtrees plus 1 + int height = std::max(leftSubtreeInfo.height, rightSubtreeInfo.height) + 1; + + // Create and return the tree information + return TreeInfo(isBalanced, height); } -int main(){ - Node* root = build_binary_tree(); - if(is_height_balanced(root).balance){ - cout << "Height : " << is_height_balanced(root).height << endl; - cout << "Yes it's Balanced" << endl; - } - else{ - cout << "Height : " << is_height_balanced(root).height << endl; - cout << "No its not Balanced" << endl; + +// Helper function to create a binary tree +BinaryTree* createBinaryTree(int value) { + return new BinaryTree(value); +} + +// Main function +int main() { + // Create a sample binary tree + // 1 + // / \ + // 2 3 + // / \ / + // 4 5 6 + BinaryTree* node1 = createBinaryTree(1); + BinaryTree* node2 = createBinaryTree(2); + BinaryTree* node3 = createBinaryTree(3); + BinaryTree* node4 = createBinaryTree(4); + BinaryTree* node5 = createBinaryTree(5); + BinaryTree* node6 = createBinaryTree(6); + + node1->left = node2; + node1->right = node3; + node2->left = node4; + node2->right = node5; + node3->left = node6; + + // Check if the binary tree is height-balanced + bool isBalanced = heightBalancedBinaryTree(node1); + + // Print the result + if (isBalanced) { + std::cout << "The binary tree is height-balanced." << std::endl; + } else { + std::cout << "The binary tree is not height-balanced." << std::endl; } + + return 0; } From f4662a724b96794af7e32447524039250af1f7a0 Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Tue, 30 May 2023 11:09:46 +0000 Subject: [PATCH 1233/1894] issue resolver #569 --- Arrays/Merge_sortedArrays.java | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Arrays/Merge_sortedArrays.java diff --git a/Arrays/Merge_sortedArrays.java b/Arrays/Merge_sortedArrays.java new file mode 100644 index 00000000..7181e64c --- /dev/null +++ b/Arrays/Merge_sortedArrays.java @@ -0,0 +1,73 @@ + +// PROBLEM:- MERGE SORTED ARRAY +// https://leetcode.com/problems/merge-sorted-array/description/ + +// Question: + +// You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, +// and two integers m and n, representing the number of elements in nums1 and nums2 respectively. + +// Merge nums1 and nums2 into a single array sorted in non-decreasing order. + +// The final sorted array should not be returned by the function, +// but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, +// where the first m elements denote the elements that should be merged, +// and the last n elements are set to 0 and should be ignored. nums2 has a length of n. +/**SAMPLE I/O + Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 + Output: [1,2,2,3,5,6] + +Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. +The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. + */ + + /** + APPROACH:- + 1. Use the 'm' and 'n' as the pointer of both the arrays. + 2. Loop through the array set the other pointer('shift') at last of nums1 to keep the track of empty array. + 3. Now compare nums1[m] to nums2[n], the bigger among them will be at nums1[shift](decrement the variables also). + 4. if m<0 or n<0 break. + 5. it is possible that there will be remaing element is nums2[] so copy them with the pointer 'shift'. + (The code is also well documented as well) + + + Time Complexity: O(N) because we iterate nums1[] which also contain the space for nums2[] + Space Complexity: O(1) Not extra array required, Hence constant space. + + */ + +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + if (n == 0) // If nums2 is empty, no merging required + return; + + if (m == 0) { // If nums1 is empty, simply copy nums2 to nums1 + int shift = nums1.length - 1; + for (int i = 0; i < n; i++) { + nums1[i] = nums2[i]; + } + return; + } + + int shift = m + n - 1; // Index to track the current position while merging + m -= 1; // Decrement m to access the last element in nums1 + n -= 1; // Decrement n to access the last element in nums2 + + while (n >= 0 && m >= 0) { // Merge elements from the end of both arrays + if (nums2[n] > nums1[m]) { // If current element in nums2 is greater + nums1[shift] = nums2[n]; // Place it in the current position in nums1 + shift -= 1; // Decrement the position index + n -= 1; // Decrement n to move to the previous element in nums2 + } else if (nums2[n] <= nums1[m]) { // If current element in nums2 is less than or equal to the current element in nums1 + nums1[shift] = nums1[m]; // Place the current element in nums1 in the current position in nums1 + nums1[m] = 0; // Set the current element in nums1 to 0 (to be ignored during merging) + shift -= 1; // Decrement the position index + m -= 1; // Decrement m to move to the previous element in nums1 + } + } + + while (n >= 0) { // If there are remaining elements in nums2 + nums1[shift--] = nums2[n--]; // Copy them to the beginning of nums1 + } + } +} From e099dcc414db058212673dfbd13ae6482b3687d2 Mon Sep 17 00:00:00 2001 From: Prabal Jain <95271035+jprabal29@users.noreply.github.com> Date: Wed, 31 May 2023 21:33:35 +0530 Subject: [PATCH 1234/1894] Create peak_index_in_array --- Binary Search/peak_index_in_array | 62 +++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Binary Search/peak_index_in_array diff --git a/Binary Search/peak_index_in_array b/Binary Search/peak_index_in_array new file mode 100644 index 00000000..8123bcb7 --- /dev/null +++ b/Binary Search/peak_index_in_array @@ -0,0 +1,62 @@ +/* +An array arr a mountain if the following properties hold: + +1.)arr.length >= 3 +2.)There exists some i with 0 < i < arr.length - 1 such that: + 1.)arr[0] < arr[1] < ... < arr[i - 1] < arr[i] + 2.)arr[i] > arr[i + 1] > ... > arr[arr.length - 1] +Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] +< arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. + +You must solve it in O(log(arr.length)) time complexity. + +Example 1: + +Input: arr = [0,1,0] +Output: 1 +Example 2: + +Input: arr = [0,2,1,0] +Output: 1 +Example 3: + +Input: arr = [0,10,5,2] +Output: 1 + + +Constraints: + +3 <= arr.length <= 105 +0 <= arr[i] <= 106 +arr is guaranteed to be a mountain array. +*/ + +class Solution { +public: + int peakIndexInMountainArray(vector& arr) { + int m=*max_element(arr.begin(),arr.end()); + int n=arr.size(); + int lo=0; + int hi=n-1; + while(lo<=hi){ + int mid=(lo+hi)/2; + if(arr[mid]>arr[mid+1]&&arr[mid]>arr[mid-1]){ + return mid; + } + if(mid-1<0&&arr[mid]n-1&&arr[mid]arr[mid+1]){ + hi=mid-1; + } + else if(arr[mid]>arr[mid-1]&&arr[mid] Date: Wed, 31 May 2023 22:28:29 +0530 Subject: [PATCH 1235/1894] Update and rename peak_index_in_array to peak_index_in_array.cpp --- ...index_in_array => peak_index_in_array.cpp} | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) rename Binary Search/{peak_index_in_array => peak_index_in_array.cpp} (53%) diff --git a/Binary Search/peak_index_in_array b/Binary Search/peak_index_in_array.cpp similarity index 53% rename from Binary Search/peak_index_in_array rename to Binary Search/peak_index_in_array.cpp index 8123bcb7..e8e3352c 100644 --- a/Binary Search/peak_index_in_array +++ b/Binary Search/peak_index_in_array.cpp @@ -1,14 +1,14 @@ /* -An array arr a mountain if the following properties hold: + Questions:- An array arr a mountain if the following properties hold: -1.)arr.length >= 3 -2.)There exists some i with 0 < i < arr.length - 1 such that: - 1.)arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - 2.)arr[i] > arr[i + 1] > ... > arr[arr.length - 1] -Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] -< arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. + 1.)arr.length >= 3 + 2.)There exists some i with 0 < i < arr.length - 1 such that: + 1.)arr[0] < arr[1] < ... < arr[i - 1] < arr[i] + 2.)arr[i] > arr[i + 1] > ... > arr[arr.length - 1] + Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] + < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. -You must solve it in O(log(arr.length)) time complexity. + You must solve it in O(log(arr.length)) time complexity. Example 1: @@ -31,13 +31,13 @@ Output: 1 arr is guaranteed to be a mountain array. */ -class Solution { -public: - int peakIndexInMountainArray(vector& arr) { - int m=*max_element(arr.begin(),arr.end()); - int n=arr.size(); - int lo=0; - int hi=n-1; + class Solution { + public: + int peakIndexInMountainArray(vector& arr) { + int m=*max_element(arr.begin(),arr.end()); + int n=arr.size(); + int lo=0; + int hi=n-1; while(lo<=hi){ int mid=(lo+hi)/2; if(arr[mid]>arr[mid+1]&&arr[mid]>arr[mid-1]){ From ef4c1614035d4bca1efc217c417eb3f9fcf60b4b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 22:52:29 +0530 Subject: [PATCH 1236/1894] rename file --- ...elete_from_bst.cpp => delete_from_bst.cpp} | 0 ...closest_value.go => find_closest_value.go} | 0 ...m_a_tree.cpp => flatten_a_linked_list.cpp} | 0 ...nsert_into_bst.cpp => insert_into_bst.cpp} | 0 ...{BST_is_valid_bst.cpp => is_valid_bst.cpp} | 0 .../{BST_search.cpp => search.cpp} | 0 sorting/heap_sort.py | 50 ------------------- 7 files changed, 50 deletions(-) rename Trees/Binary Search Trees/{BST_delete_from_bst.cpp => delete_from_bst.cpp} (100%) rename Trees/Binary Search Trees/{BST_find_closest_value.go => find_closest_value.go} (100%) rename Trees/Binary Search Trees/{BST_flatten_a_linked_list_from_a_tree.cpp => flatten_a_linked_list.cpp} (100%) rename Trees/Binary Search Trees/{BST_insert_into_bst.cpp => insert_into_bst.cpp} (100%) rename Trees/Binary Search Trees/{BST_is_valid_bst.cpp => is_valid_bst.cpp} (100%) rename Trees/Binary Search Trees/{BST_search.cpp => search.cpp} (100%) delete mode 100644 sorting/heap_sort.py diff --git a/Trees/Binary Search Trees/BST_delete_from_bst.cpp b/Trees/Binary Search Trees/delete_from_bst.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_delete_from_bst.cpp rename to Trees/Binary Search Trees/delete_from_bst.cpp diff --git a/Trees/Binary Search Trees/BST_find_closest_value.go b/Trees/Binary Search Trees/find_closest_value.go similarity index 100% rename from Trees/Binary Search Trees/BST_find_closest_value.go rename to Trees/Binary Search Trees/find_closest_value.go diff --git a/Trees/Binary Search Trees/BST_flatten_a_linked_list_from_a_tree.cpp b/Trees/Binary Search Trees/flatten_a_linked_list.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_flatten_a_linked_list_from_a_tree.cpp rename to Trees/Binary Search Trees/flatten_a_linked_list.cpp diff --git a/Trees/Binary Search Trees/BST_insert_into_bst.cpp b/Trees/Binary Search Trees/insert_into_bst.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_insert_into_bst.cpp rename to Trees/Binary Search Trees/insert_into_bst.cpp diff --git a/Trees/Binary Search Trees/BST_is_valid_bst.cpp b/Trees/Binary Search Trees/is_valid_bst.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_is_valid_bst.cpp rename to Trees/Binary Search Trees/is_valid_bst.cpp diff --git a/Trees/Binary Search Trees/BST_search.cpp b/Trees/Binary Search Trees/search.cpp similarity index 100% rename from Trees/Binary Search Trees/BST_search.cpp rename to Trees/Binary Search Trees/search.cpp diff --git a/sorting/heap_sort.py b/sorting/heap_sort.py deleted file mode 100644 index 75ef3f1b..00000000 --- a/sorting/heap_sort.py +++ /dev/null @@ -1,50 +0,0 @@ - -Heap sort is a sorting algorithm that works by transforming an unsorted list into a heap data structure, -which is a binary tree where each parent node is greater than or equal to its children if any. -then it repeatedly extracts the maximum element from the heap and puts it into its correct sorted position until the whole list is sorted. - -Sample_input : [5,16,8,14,20,1,26] -Sample_output : [1,5,8,14,16,20,26] - -def heap_sort(arr): - # Build the initial heap - n = len(arr) - for i in range(n // 2 - 1, -1, -1): - heapify(arr, n, i) - - # Extract the maximum element repeatedly - for i in range(n - 1, 0, -1): - arr[0], arr[i] = arr[i], arr[0] # Swap - heapify(arr, i, 0) - - return arr - -def heapify(arr, n, i): - largest = i - left = 2 * i + 1 - right = 2 * i + 2 - - # Check if left child is larger than root - if left < n and arr[left] > arr[largest]: - largest = left - - # Check if right child is larger than root - if right < n and arr[right] > arr[largest]: - largest = right - - # Swap if necessary and heapify the affected subtree - if largest != i: - arr[i], arr[largest] = arr[largest], arr[i] - heapify(arr, n, largest) -ere's how the algorithm works: - -The heap_sort function takes an unsorted list arr as input. -It starts by building the initial heap by calling the heapify function on each parent node in the tree. -It does this by iterating over the parent nodes in reverse order starting from the last parent node, -and calling heapify on each of them. This builds a heap where each parent node is greater than or equal to its children. -It then repeatedly extracts the maximum element from the heap and puts it into its correct sorted position. -It does this by swapping the maximum element which is always at the root of the heap with the last element in the heap, -and then calling heapify on the root node to restore the heap property. -Finally, it returns the sorted list. - - From fc159baa814bdbf2168b09b5c2e9c1c026c98da2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:00:29 +0530 Subject: [PATCH 1237/1894] add insert interval in go --- Arrays/insert_interval.go | 68 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Arrays/insert_interval.go diff --git a/Arrays/insert_interval.go b/Arrays/insert_interval.go new file mode 100644 index 00000000..99aaa209 --- /dev/null +++ b/Arrays/insert_interval.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" +) + +// Interval represents an interval with a start and end value. +type Interval struct { + Start int + End int +} + +// insert merges a new interval into a sorted list of intervals. +func insert(intervals []Interval, newInterval Interval) []Interval { + result := make([]Interval, 0) + i := 0 + + // Add intervals that end before the new interval starts + for i < len(intervals) && intervals[i].End < newInterval.Start { + result = append(result, intervals[i]) + i++ + } + + // Merge intervals that overlap with the new interval + for i < len(intervals) && intervals[i].Start <= newInterval.End { + newInterval.Start = min(newInterval.Start, intervals[i].Start) + newInterval.End = max(newInterval.End, intervals[i].End) + i++ + } + + // Add the merged new interval + result = append(result, newInterval) + + // Add remaining intervals + for i < len(intervals) { + result = append(result, intervals[i]) + i++ + } + + return result +} + +// min returns the minimum of two integers. +func min(a, b int) int { + if a < b { + return a + } + return b +} + +// max returns the maximum of two integers. +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func main() { + intervals := []Interval{ + {1, 3}, + {6, 9}, + } + newInterval := Interval{2, 5} + + result := insert(intervals, newInterval) + fmt.Println("Merged Intervals:", result) +} From 9ba0009587b61c213086be0f8a55aae13e68835d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:02:20 +0530 Subject: [PATCH 1238/1894] add explanation --- Arrays/insert_interval.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Arrays/insert_interval.go b/Arrays/insert_interval.go index 99aaa209..945ec6f6 100644 --- a/Arrays/insert_interval.go +++ b/Arrays/insert_interval.go @@ -1,3 +1,25 @@ +/* + + In this implementation, the `Interval` struct represents an interval with a start and end value. + The `insert` function takes a sorted list of intervals and a new interval as input and returns a new + list of intervals after merging the new interval with the existing intervals. + + Here's how the `insert` function works: + + 1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0. + 2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the + `result` slice. + 3. It merges intervals that overlap with the new interval by updating the start and end values of the new + interval accordingly. + 4. It adds the merged new interval to the `result` slice. + 5. It adds any remaining intervals from the original list to the `result` slice. + 6. Finally, it returns the `result` slice containing the merged intervals. + + The `min` and `max` functions are helper functions to find the minimum and maximum of two integers. + + In the `main` function, an example input is provided with a list of intervals and a new interval. + The `insert` function is called with these inputs, and the result is printed to the console. +*/ package main import ( From 9c1dbf2102b0df9a98c556e5e2c64b61423172b1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:05:33 +0530 Subject: [PATCH 1239/1894] add time and space complexity --- Arrays/insert_interval.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Arrays/insert_interval.go b/Arrays/insert_interval.go index 945ec6f6..8fb5282e 100644 --- a/Arrays/insert_interval.go +++ b/Arrays/insert_interval.go @@ -1,4 +1,5 @@ /* + Insert Interval In this implementation, the `Interval` struct represents an interval with a start and end value. The `insert` function takes a sorted list of intervals and a new interval as input and returns a new @@ -19,6 +20,20 @@ In the `main` function, an example input is provided with a list of intervals and a new interval. The `insert` function is called with these inputs, and the result is printed to the console. + + Time Complexity: + The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to + iterate through each interval in the list to merge and insert the new interval. In the worst case, we may + need to traverse all intervals in the list. + + Space Complexity: + The space complexity is O(n), where n is the number of intervals in the input list. This is because we + create a new result slice to store the merged intervals, which can potentially contain all the intervals + from the input list plus the merged new interval. Therefore, the space required is proportional to the + number of intervals in the input list. + + Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number + of intervals in the input list. */ package main From eabcdd5e25703e51d2a389a4d0d6119ca41df671 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:08:19 +0530 Subject: [PATCH 1240/1894] add insert interval in c++ --- Arrays/insert_interval.cpp | 105 +++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Arrays/insert_interval.cpp diff --git a/Arrays/insert_interval.cpp b/Arrays/insert_interval.cpp new file mode 100644 index 00000000..41fd59f1 --- /dev/null +++ b/Arrays/insert_interval.cpp @@ -0,0 +1,105 @@ +/* + Insert Interval + + In this implementation, the `Interval` struct represents an interval with a start and end value. + The `insert` function takes a sorted list of intervals and a new interval as input and returns a new + list of intervals after merging the new interval with the existing intervals. + + Here's how the `insert` function works: + + 1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0. + 2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the + `result` slice. + 3. It merges intervals that overlap with the new interval by updating the start and end values of the new + interval accordingly. + 4. It adds the merged new interval to the `result` slice. + 5. It adds any remaining intervals from the original list to the `result` slice. + 6. Finally, it returns the `result` slice containing the merged intervals. + + The `min` and `max` functions are helper functions to find the minimum and maximum of two integers. + + In the `main` function, an example input is provided with a list of intervals and a new interval. + The `insert` function is called with these inputs, and the result is printed to the console. + + Time Complexity: + The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to + iterate through each interval in the list to merge and insert the new interval. In the worst case, we may + need to traverse all intervals in the list. + + Space Complexity: + The space complexity is O(n), where n is the number of intervals in the input list. This is because we + create a new result slice to store the merged intervals, which can potentially contain all the intervals + from the input list plus the merged new interval. Therefore, the space required is proportional to the + number of intervals in the input list. + + Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number + of intervals in the input list. +*/ +#include +#include + +using namespace std; + +// Interval represents a closed interval [start, end]. +struct Interval { + int start; + int end; + + Interval(int s, int e) : start(s), end(e) {} +}; + +vector insertInterval(vector& intervals, Interval newInterval) { + vector result; + + // Traverse through each interval in the input list + // and perform the necessary merging and inserting. + for (const auto& interval : intervals) { + // If the current interval ends before the new interval starts, + // add it to the result as it does not overlap. + if (interval.end < newInterval.start) { + result.push_back(interval); + } + // If the current interval starts after the new interval ends, + // add the new interval and update it to the current interval + // as there won't be any more overlap with subsequent intervals. + else if (interval.start > newInterval.end) { + result.push_back(newInterval); + newInterval = interval; + } + // If there is an overlap between the current interval and the new interval, + // merge them by updating the new interval's start and end. + else { + newInterval.start = min(interval.start, newInterval.start); + newInterval.end = max(interval.end, newInterval.end); + } + } + + // Add the final merged or inserted interval to the result. + result.push_back(newInterval); + + return result; +} + +// Utility function to print the intervals. +void printIntervals(const vector& intervals) { + for (const auto& interval : intervals) { + cout << "[" << interval.start << ", " << interval.end << "] "; + } + cout << endl; +} + +int main() { + // Example usage + vector intervals = {Interval(1, 3), Interval(6, 9)}; + Interval newInterval(2, 5); + + cout << "Original intervals: "; + printIntervals(intervals); + + vector mergedIntervals = insertInterval(intervals, newInterval); + + cout << "Merged intervals: "; + printIntervals(mergedIntervals); + + return 0; +} From e7a9afa85dab5b85e5d3456b73a39e3c63343280 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:10:15 +0530 Subject: [PATCH 1241/1894] add insert interval in java --- Arrays/insert_interval.java | 122 ++++++++++++++++++++++++++++-------- 1 file changed, 97 insertions(+), 25 deletions(-) diff --git a/Arrays/insert_interval.java b/Arrays/insert_interval.java index 5a40b71a..3620a5b9 100644 --- a/Arrays/insert_interval.java +++ b/Arrays/insert_interval.java @@ -1,35 +1,107 @@ -/* You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. +/* + Insert Interval -Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). + In this implementation, the `Interval` struct represents an interval with a start and end value. + The `insert` function takes a sorted list of intervals and a new interval as input and returns a new + list of intervals after merging the new interval with the existing intervals. -Return intervals after the insertion. + Here's how the `insert` function works: -Example 1: + 1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0. + 2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the + `result` slice. + 3. It merges intervals that overlap with the new interval by updating the start and end values of the new + interval accordingly. + 4. It adds the merged new interval to the `result` slice. + 5. It adds any remaining intervals from the original list to the `result` slice. + 6. Finally, it returns the `result` slice containing the merged intervals. -Input: intervals = [[1,3],[6,9]], newInterval = [2,5] -Output: [[1,5],[6,9]] */ + The `min` and `max` functions are helper functions to find the minimum and maximum of two integers. -public int[][] insert(int[][] intervals, int[] newInterval) { // Define a method that takes in an array of intervals and a new interval to be inserted - List list = new ArrayList<>(); // Create a new ArrayList to store the merged intervals - for(int[] curr : intervals){ // Iterate through each interval in the input array - if(curr[0] > newInterval[1]){ // If the start time of the current interval is greater than the end time of the new interval, they do not overlap - list.add(newInterval); // Add the new interval to the output list - newInterval = curr; // Update the new interval to be the current interval + In the `main` function, an example input is provided with a list of intervals and a new interval. + The `insert` function is called with these inputs, and the result is printed to the console. + + Time Complexity: + The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to + iterate through each interval in the list to merge and insert the new interval. In the worst case, we may + need to traverse all intervals in the list. + + Space Complexity: + The space complexity is O(n), where n is the number of intervals in the input list. This is because we + create a new result slice to store the merged intervals, which can potentially contain all the intervals + from the input list plus the merged new interval. Therefore, the space required is proportional to the + number of intervals in the input list. + + Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number + of intervals in the input list. +*/ +import java.util.ArrayList; +import java.util.List; + +class Interval { + int start; + int end; + + Interval(int start, int end) { + this.start = start; + this.end = end; + } +} + +public class InsertInterval { + public static List insertInterval(List intervals, Interval newInterval) { + List result = new ArrayList<>(); + + // Traverse through each interval in the input list + // and perform the necessary merging and inserting. + for (Interval interval : intervals) { + // If the current interval ends before the new interval starts, + // add it to the result as it does not overlap. + if (interval.end < newInterval.start) { + result.add(interval); + } + // If the current interval starts after the new interval ends, + // add the new interval and update it to the current interval + // as there won't be any more overlap with subsequent intervals. + else if (interval.start > newInterval.end) { + result.add(newInterval); + newInterval = interval; + } + // If there is an overlap between the current interval and the new interval, + // merge them by updating the new interval's start and end. + else { + newInterval.start = Math.min(interval.start, newInterval.start); + newInterval.end = Math.max(interval.end, newInterval.end); + } } - else if(curr[1] < newInterval[0]){ // If the end time of the current interval is less than the start time of the new interval, they do not overlap - list.add(curr); // Add the current interval to the output list - }else{ // If the intervals overlap - int start = Math.min(curr[0], newInterval[0]); // Merge the start times of the intervals - int end = Math.max(curr[1], newInterval[1]); // Merge the end times of the intervals - newInterval[0] = start; // Update the start time of the new interval to be the merged start time - newInterval[1] = end; // Update the end time of the new interval to be the merged end time + + // Add the final merged or inserted interval to the result. + result.add(newInterval); + + return result; + } + + // Utility function to print the intervals. + public static void printIntervals(List intervals) { + for (Interval interval : intervals) { + System.out.print("[" + interval.start + ", " + interval.end + "] "); } + System.out.println(); } - list.add(newInterval); // Add the last merged interval to the output list - int[][] answer = new int[list.size()][]; // Create a new 2D array to store the merged intervals - for(int i=0;i intervals = new ArrayList<>(); + intervals.add(new Interval(1, 3)); + intervals.add(new Interval(6, 9)); + Interval newInterval = new Interval(2, 5); + + System.out.print("Original intervals: "); + printIntervals(intervals); + + List mergedIntervals = insertInterval(intervals, newInterval); + + System.out.print("Merged intervals: "); + printIntervals(mergedIntervals); } - return answer; // Return the merged intervals as a 2D array } - From b827164e60f1e9851234f78d9815c914846d808b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:11:22 +0530 Subject: [PATCH 1242/1894] add insert interval in js --- Arrays/insert_interval.js | 137 +++++++++++++++++++------------------- 1 file changed, 70 insertions(+), 67 deletions(-) diff --git a/Arrays/insert_interval.js b/Arrays/insert_interval.js index bbe2848c..562875c4 100644 --- a/Arrays/insert_interval.js +++ b/Arrays/insert_interval.js @@ -1,76 +1,79 @@ /* - Problem definition: - You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent - the start and the end of the ith interval and intervals is sorted in ascending order by starti. - You are also given an interval newInterval = [start, end] that represents the start and end of another interval. - - Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). - - Approach: - The approach used here is to first add all the intervals before the newInterval to the result array. - Then, we merge overlapping intervals by iterating through the intervals array and comparing the start and end times of the newInterval and the current interval. - After all overlapping intervals have been merged, we add the newInterval to the result array and then add all the remaining intervals after the newInterval. - The resulting array will be sorted in ascending order by start time. - - Complexity: - Time Complexity: O(n), where n is the length of intervals array. - We iterate through the intervals array only once in the worst case. - Space Complexity: O(n), where n is the length of intervals array. - We use an array to store the result, which could potentially contain all the intervals. - - Sample input/outputs: - Example 1: - Input: - intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] - newInterval = [4,8] - - Output: - [[1,2],[3,10],[12,16]] - - Example 2: - Input: - intervals = [[1,3],[6,9]] - newInterval = [2,5] - - Output: - [[1,5],[6,9]] - - Example 3: - Input: - intervals = [[1,5]] - newInterval = [2,3] - - Output: - [[1,5]] + Insert Interval + + In this implementation, the `Interval` struct represents an interval with a start and end value. + The `insert` function takes a sorted list of intervals and a new interval as input and returns a new + list of intervals after merging the new interval with the existing intervals. + + Here's how the `insert` function works: + + 1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0. + 2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the + `result` slice. + 3. It merges intervals that overlap with the new interval by updating the start and end values of the new + interval accordingly. + 4. It adds the merged new interval to the `result` slice. + 5. It adds any remaining intervals from the original list to the `result` slice. + 6. Finally, it returns the `result` slice containing the merged intervals. + + The `min` and `max` functions are helper functions to find the minimum and maximum of two integers. + + In the `main` function, an example input is provided with a list of intervals and a new interval. + The `insert` function is called with these inputs, and the result is printed to the console. + + Time Complexity: + The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to + iterate through each interval in the list to merge and insert the new interval. In the worst case, we may + need to traverse all intervals in the list. + + Space Complexity: + The space complexity is O(n), where n is the number of intervals in the input list. This is because we + create a new result slice to store the merged intervals, which can potentially contain all the intervals + from the input list plus the merged new interval. Therefore, the space required is proportional to the + number of intervals in the input list. + + Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number + of intervals in the input list. */ +class Interval { + constructor(start, end) { + this.start = start; + this.end = end; + } +} + +function insertInterval(intervals, newInterval) { + const mergedIntervals = []; + let i = 0; -const insert = function(intervals, newInterval) { - const result = []; - let i = 0; + // Skip all intervals that end before the new interval starts + while (i < intervals.length && intervals[i].end < newInterval.start) { + mergedIntervals.push(intervals[i]); + i++; + } - // Add all the intervals before the newInterval - while (i < intervals.length && intervals[i][1] < newInterval[0]) { - result.push(intervals[i]); - i++; - } + // Merge intervals that overlap with the new interval + while (i < intervals.length && intervals[i].start <= newInterval.end) { + newInterval.start = Math.min(intervals[i].start, newInterval.start); + newInterval.end = Math.max(intervals[i].end, newInterval.end); + i++; + } - // Merge overlapping intervals - while (i < intervals.length && intervals[i][0] <= newInterval[1]) { - newInterval[0] = Math.min(intervals[i][0], newInterval[0]); - newInterval[1] = Math.max(intervals[i][1], newInterval[1]); - i++; - } + mergedIntervals.push(newInterval); - result.push(newInterval); + // Add the remaining intervals to the merged intervals list + while (i < intervals.length) { + mergedIntervals.push(intervals[i]); + i++; + } - // Add all the intervals after the newInterval - while (i < intervals.length) { - result.push(intervals[i]); - i++; - } + return mergedIntervals; +} - return result; -}; +// Example usage +const intervals = [new Interval(1, 3), new Interval(6, 9)]; +const newInterval = new Interval(2, 5); -console.log("The resulting array of intervals is:"); -console.log(insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8])); +console.log("Original intervals:", intervals); +const mergedIntervals = insertInterval(intervals, newInterval); +console.log("Merged intervals:", mergedIntervals); From 0d6846c625ad694a7e5142684ffaacf75a5535f9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 31 May 2023 23:12:13 +0530 Subject: [PATCH 1243/1894] add insert interval in python --- Arrays/insert_interval.py | 136 +++++++++++++++++--------------------- 1 file changed, 61 insertions(+), 75 deletions(-) diff --git a/Arrays/insert_interval.py b/Arrays/insert_interval.py index 66155352..5efd0a1a 100644 --- a/Arrays/insert_interval.py +++ b/Arrays/insert_interval.py @@ -1,90 +1,76 @@ -# 57. Insert Interval -# You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. -# Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). -# Return intervals after the insertion. -# Example 1: -# Input: intervals = [[1,3],[6,9]], newInterval = [2,5] -# Output: [[1,5],[6,9]] -# Example 2: -# Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] -# Output: [[1,2],[3,10],[12,16]] -# Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. +''' + Insert Interval + + In this implementation, the `Interval` struct represents an interval with a start and end value. + The `insert` function takes a sorted list of intervals and a new interval as input and returns a new + list of intervals after merging the new interval with the existing intervals. -# CODE Explaination -# The function insert takes two arguments, intervals which is a list of non-overlapping intervals and newInterval which is another interval that needs to be inserted into intervals. -# The variable n holds newInterval. The variable j holds intervals. The variables m and m1 are initialized with the start and end points of newInterval, respectively. The variable i is used to iterate through the intervals in j. -# The while loop checks if newInterval overlaps with any interval in intervals. If there is an overlap, we update m and/or m1 to include all overlapping intervals. -# If there is an overlap, the overlapping interval is removed from j using the pop method. If an interval is removed, we decrement i by 1 so that we don't skip any intervals. -# If there is no overlap, we increment i by 1 so that we can move on to the next interval in j. -# Once all overlaps are handled, we create a new interval s1=[m,m1] which is the combination of all overlapping intervals and newInterval. We append this new combined interval to j and sort it in ascending order based on the start point of each interval. -# Finally, we return j, which is the updated list of non-overlapping intervals. + Here's how the `insert` function works: -# Now let's do a dry run of the first example: -# intervals = [[1,3], [6,9]] -# newInterval = [2,5] -# result = insert(intervals, newInterval) -# print(result) -# Initially, n = [2,5], j = [[1,3], [6,9]], i = 0, m = 2, and m1 = 5. + 1. It initializes an empty `result` slice to store the merged intervals and sets the index `i` to 0. + 2. It iterates over the existing intervals and adds intervals that end before the new interval starts to the + `result` slice. + 3. It merges intervals that overlap with the new interval by updating the start and end values of the new + interval accordingly. + 4. It adds the merged new interval to the `result` slice. + 5. It adds any remaining intervals from the original list to the `result` slice. + 6. Finally, it returns the `result` slice containing the merged intervals. -# First iteration of the while loop: + The `min` and `max` functions are helper functions to find the minimum and maximum of two integers. -# We check if n overlaps with [1,3]. Since there is an overlap, we update m to 1 and keep m1 as 5. -# We remove [1,3] from j using the pop method and append [1,5] to j, so j becomes [[6,9], [1,5]]. -# We decrement i to -1 since we removed an element from j. -# Second iteration of the while loop: + In the `main` function, an example input is provided with a list of intervals and a new interval. + The `insert` function is called with these inputs, and the result is printed to the console. -# We check if n overlaps with [6,9]. Since there is no overlap, we increment i to 0 to move on to the next interval in j. -# Third iteration of the while loop: + Time Complexity: + The time complexity is O(n), where n is the number of intervals in the input list. This is because we need to + iterate through each interval in the list to merge and insert the new interval. In the worst case, we may + need to traverse all intervals in the list. -# We check if n overlaps with [1,5]. Since there is an overlap, we update m to 1 and keep m1 as 5. -# We remove [1,5] from j using the pop method and append [1,5] to j, so j remains [[6,9], [1,5]]. -# We decrement i to 0 since we removed an element from j. -# Since we have checked all intervals in j, we exit the while loop. + Space Complexity: + The space complexity is O(n), where n is the number of intervals in the input list. This is because we + create a new result slice to store the merged intervals, which can potentially contain all the intervals + from the input list plus the merged new interval. Therefore, the space required is proportional to the + number of intervals in the input list. -# We create a new interval s1=[1,5] which is the combination of [1,3] and [2,5]. We append s1 to j so j becomes [[6,9], [1,5]]. + Overall, the algorithm has a linear time complexity and linear space complexity with respect to the number + of intervals in the input list. +''' +class Interval: + def __init__(self, start, end): + self.start = start + self.end = end -# Finally, we sort j in ascending order based on the start point of each interval. The sorted list is [[1,5], [6,9]]. -# We return j which is the updated list of non-overlapping intervals after inserting newInterval. Therefore, the output of this function for the input intervals = [[1,3], [6,9]], newInterval = [2,5] is [[1,5],[6,9]]. -# Code -from typing import List +def insertInterval(intervals, newInterval): + mergedIntervals = [] + i = 0 + # Skip all intervals that end before the new interval starts + while i < len(intervals) and intervals[i].end < newInterval.start: + mergedIntervals.append(intervals[i]) + i += 1 -def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: - # Assign variables for easier readability - n = newInterval - j = intervals - i = 0 - m = n[0] # Initialize starting point of the interval to be inserted - m1 = n[1] # Initialize ending point of the interval to be inserted + # Merge intervals that overlap with the new interval + while i < len(intervals) and intervals[i].start <= newInterval.end: + newInterval.start = min(intervals[i].start, newInterval.start) + newInterval.end = max(intervals[i].end, newInterval.end) + i += 1 - # Iterate over all existing intervals - while i < len(j): - # If any part of the new interval overlaps with the current interval - if n[0] in range(j[i][0], j[i][1]+1) or n[1] in range(j[i][0], j[i][1]+1) or (n[1] >= j[i][1] and n[0] <= j[i][0]): - # Expand the new interval to include the current interval - if j[i][0] < m: - m = j[i][0] - if j[i][1] > m1: - m1 = j[i][1] - # Remove the current interval from the list and adjust the index accordingly - j.pop(i) - if i <= 0: - i = 0 - else: - i -= 1 - else: - i += 1 # Move to the next interval if there is no overlap + mergedIntervals.append(newInterval) - # Create the final interval by combining all intervals that overlap with the new interval - s1 = [m, m1] - j.append(s1) - j.sort() # Sort the final list of intervals by their starting points - return j + # Add the remaining intervals to the merged intervals list + while i < len(intervals): + mergedIntervals.append(intervals[i]) + i += 1 + return mergedIntervals # Example usage -intervals = [[1, 3], [6, 9]] -newInterval = [2, 5] -result = insert(intervals, newInterval) -print(result) -# Output: [[1,5],[6,9]] +intervals = [ + Interval(1, 3), + Interval(6, 9) +] +newInterval = Interval(2, 5) + +print('Original intervals:', [(i.start, i.end) for i in intervals]) +mergedIntervals = insertInterval(intervals, newInterval) +print('Merged intervals:', [(i.start, i.end) for i in mergedIntervals]) From b9079a103322ebc7db47cf4e36c850a86bb3e7a8 Mon Sep 17 00:00:00 2001 From: Manmay Ghosh Date: Thu, 1 Jun 2023 16:16:41 +0530 Subject: [PATCH 1244/1894] Update Graphs_kruskals_algo.cpp --- Graphs/Graphs_kruskals_algo.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Graphs/Graphs_kruskals_algo.cpp b/Graphs/Graphs_kruskals_algo.cpp index f95733dc..5d2c4584 100644 --- a/Graphs/Graphs_kruskals_algo.cpp +++ b/Graphs/Graphs_kruskals_algo.cpp @@ -23,13 +23,14 @@ pseudosteps #include using namespace std; -// DS data structure +// DS data structure class will help in building graph class D_S { - int* parent; - int* child; - + int* parent; // to create a parent relationship b/w two nodes + int* child; // to create a child relationship b/w two nodes public: - D_S(int n) + + //This function will create a user defined data structure which will help to create a graph + D_S(int n) { parent = new int[n]; child = new int[n]; @@ -39,7 +40,7 @@ class D_S { } } - // Find function + // Find function to find edges b/w vertices int find(int i) { if (parent[i] == -1) @@ -47,7 +48,7 @@ class D_S { return parent[i] = find(parent[i]); } - // Union function + // Union function to joint two nodes via smallest possible weighted edge void unite(int x, int y) { int s1 = find(x); @@ -67,6 +68,8 @@ class D_S { }; class Graph { + //As we know for kruskal's algorithm we have to maintain a list for edges b/w two vertices + //from lowest weight to highest weight in increasing order vector> edgelist; int V; @@ -79,6 +82,8 @@ class Graph { edgelist.push_back({ w, x, y }); } + + //Kruskal's Algorithm void kruskals_mst() { // Arrange all edges in ascending order to find minimum weight edge From 6c2d3f51d0362dd82d82134dc6952ba11714dee5 Mon Sep 17 00:00:00 2001 From: Manmay Ghosh Date: Thu, 1 Jun 2023 17:04:56 +0530 Subject: [PATCH 1245/1894] Create Kth_Largest_Value_In_BST.py function will find k'th largest element in a tree. --- .../Kth_Largest_Value_In_BST.py | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Trees/Binary Search Trees/Kth_Largest_Value_In_BST.py diff --git a/Trees/Binary Search Trees/Kth_Largest_Value_In_BST.py b/Trees/Binary Search Trees/Kth_Largest_Value_In_BST.py new file mode 100644 index 00000000..d5254bad --- /dev/null +++ b/Trees/Binary Search Trees/Kth_Largest_Value_In_BST.py @@ -0,0 +1,88 @@ +# Name : Manmay Ghosh +# Github username : ManmayGhosh +# Repository name : data-structures-and-algorithms +# Problem : Kth Largest Value In BST in Python +# Issue Number : #1225 + +# Explanation of the below Python code : + +# 1. The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited. +# 2. The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively. +# 3. While doing the traversal, keep track of the count of nodes visited so far. +# 4. When the count becomes equal to k, stop the traversal and print the key. + +# -------------------------------------------------------------------------//Python code begins here------------------------------------------------------------------------ + +class Node: + # Constructor to create a new node + def __init__(self, val): + self.key = val + self.left = None + self.right = None + +# This function will find k'th largest element in a tree. +def kthLargestUtil(root, k, c): + + # Base cases, c[0] >= k is important to avoid unnecessary recursive calls + if root == None or c[0] >= k: + return + + # Follow reverse inorder traversal so that the largest element is visited first + kthLargestUtil(root.right, k, c) + + # Increment count of visited nodes + c[0] += 1 + + # If c becomes k now, then this is the k'th largest + if c[0] == k: + print("K'th largest element is",root.key) + return + + # Recurssion for left subtree + kthLargestUtil(root.left, k, c) + + +# Function to find k'th largest element +def kthLargest(root, k): + + # Initialize count of nodes visited as 0 + c = [0] + + # Note that c is passed by reference + kthLargestUtil(root, k, c) + + +# Function to insert a new node in BST */ +def insert(node, key): + + if node == None: + return Node(key) + + if key < node.key: + node.left = insert(node.left, key) + elif key > node.key: + node.right = insert(node.right, key) + + return node + +# Driver Code +if __name__ == '__main__': + root = None + root = insert(root, 50) + insert(root, 30) + insert(root, 20) + insert(root, 40) + insert(root, 70) + insert(root, 60) + insert(root, 80) + k = int(input("Enter the Kth element(should be greater than 1)")) + kthLargest(root, k) + + + + +# Complexity Analysis: +# Time Complexity: O(n). +# In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n). +# Auxiliary Space: O(h). +# Max recursion stack of height h at a given time. From 03319f305ec0dc14fe12e4ec1f79eb952513a6e2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:52:44 +0530 Subject: [PATCH 1246/1894] update links for insert interval --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 95260da8..f97d0b64 100644 --- a/README.md +++ b/README.md @@ -609,7 +609,7 @@ Many problems in the real world use the merge intervals pattern. Let’s look at ## Practice problems for merge intervals - Merge Intervals [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.py) [Javacript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.js) -- Insert Interval +- Insert Interval [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.js) - Interval List Intersections - Employee Free Time - Meeting Rooms From 5f611b3423bec8b1af16735072f3d0e4405ff3a5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:55:09 +0530 Subject: [PATCH 1247/1894] add merge interval in go --- Arrays/merge_intervals.go | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Arrays/merge_intervals.go diff --git a/Arrays/merge_intervals.go b/Arrays/merge_intervals.go new file mode 100644 index 00000000..aa780d86 --- /dev/null +++ b/Arrays/merge_intervals.go @@ -0,0 +1,60 @@ +package main + +import "sort" + +// function to merge overlapping intervals +func MergeOverlappingIntervals(intervals [][]int) [][]int { + + // make a copy of the input intervals to sort + sortedIntervals := make([][]int, len(intervals)) + copy(sortedIntervals, intervals) + + // sort the intervals by their start time + sort.Slice(sortedIntervals, func(i, j int) bool { + return sortedIntervals[i][0] < sortedIntervals[j][0] + }) + + // create an empty list to store the merged intervals + mergedIntervals := make([][]int, 0) + + // set the current interval to the first interval in the sorted list + currentInterval := sortedIntervals[0] + + // add the current interval to the merged intervals list + mergedIntervals = append(mergedIntervals, currentInterval) + + // loop through the sorted intervals starting from the second interval + for _, nextInterval := range sortedIntervals[1:] { + + // print the start and end time of the next interval (for debugging purposes) + print(nextInterval[0], " ", nextInterval[1], "-->") + + // get the end time of the current interval and the start and end time of the next interval + currentIntervalEnd := currentInterval[1] + nextIntervalStart, nextIntervalEnd := nextInterval[0], nextInterval[1] + + // if the end time of the current interval is greater than or equal to the start time of the next interval, + // then the two intervals overlap and should be merged + if currentIntervalEnd >= nextIntervalStart { + + // set the end time of the current interval to the maximum of its current end time and the end time of the next interval + currentInterval[1] = max(currentIntervalEnd, nextIntervalEnd) + + } else { + // if the two intervals do not overlap, then the next interval becomes the new current interval and is added to the merged intervals list + currentInterval = nextInterval + mergedIntervals = append(mergedIntervals, currentInterval) + } + } + + // return the list of merged intervals + return mergedIntervals +} + +// function to return the maximum of two integers +func max(a, b int) int { + if a > b { + return a + } + return b +} From 6db6167fa32684ce246b522416c1a4f8d989a835 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:55:51 +0530 Subject: [PATCH 1248/1894] add explanation --- Arrays/merge_intervals.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Arrays/merge_intervals.go b/Arrays/merge_intervals.go index aa780d86..e3a2ae5b 100644 --- a/Arrays/merge_intervals.go +++ b/Arrays/merge_intervals.go @@ -1,3 +1,20 @@ +/* + Explanation: + + The function takes an array of intervals as input. + First, a copy of the input intervals is made and sorted by the start time of each interval. This is stored in a + temporary variable called sortedIntervals. + A new array called mergedIntervals is created to store the merged intervals. The first interval in sortedIntervals + is added to mergedIntervals to start the merging process. + Next, a loop iterates through each interval in sortedIntervals. For each interval, the start and end times of + the current interval and the next interval are compared. If they overlap, the end time of the current interval + is updated to the maximum of the two end times. + If they don't overlap, the next interval becomes the current interval and is added to mergedIntervals. + The loop continues until all intervals have been compared and merged, and the final mergedIntervals array + is returned. + To find the maximum of two numbers, the function uses a helper function called max. This function simply + compares the two numbers and returns the greater one. +*/ package main import "sort" From ecba8fde0d5246d2c86cb0ed1b29209951bf93b1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:56:59 +0530 Subject: [PATCH 1249/1894] add question --- Arrays/merge_intervals.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Arrays/merge_intervals.go b/Arrays/merge_intervals.go index e3a2ae5b..6b59c0a4 100644 --- a/Arrays/merge_intervals.go +++ b/Arrays/merge_intervals.go @@ -1,4 +1,7 @@ /* + Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, + and return an array of the non-overlapping intervals that cover all the intervals in the input. + Explanation: The function takes an array of intervals as input. From 27481c54b97df25363bf9fad875a7b5dea0348a5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:57:50 +0530 Subject: [PATCH 1250/1894] add sample io --- Arrays/merge_intervals.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Arrays/merge_intervals.go b/Arrays/merge_intervals.go index 6b59c0a4..4607a702 100644 --- a/Arrays/merge_intervals.go +++ b/Arrays/merge_intervals.go @@ -2,6 +2,9 @@ Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. + Sample Input: [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]] + Output: [[1, 2], [3, 8], [9, 10]] + Explanation: The function takes an array of intervals as input. From 41c11c894b5ca3ef9ce77948eb117aef0ee7294f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:58:24 +0530 Subject: [PATCH 1251/1894] add time and space complexity --- Arrays/merge_intervals.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Arrays/merge_intervals.go b/Arrays/merge_intervals.go index 4607a702..18be93c5 100644 --- a/Arrays/merge_intervals.go +++ b/Arrays/merge_intervals.go @@ -4,7 +4,7 @@ Sample Input: [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]] Output: [[1, 2], [3, 8], [9, 10]] - + Explanation: The function takes an array of intervals as input. @@ -20,6 +20,9 @@ is returned. To find the maximum of two numbers, the function uses a helper function called max. This function simply compares the two numbers and returns the greater one. + + Time complexity O(nlog(n)) + Space complexity: | O(n) where n is the length of the input array */ package main From a8715dcc5ac59b40167f1658b2aa3f133b6e55e8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 1 Jun 2023 22:59:07 +0530 Subject: [PATCH 1252/1894] update link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f97d0b64..2261f459 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ Many problems in the real world use the merge intervals pattern. Let’s look at ## Practice problems for merge intervals -- Merge Intervals [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.py) [Javacript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.js) +- Merge Intervals [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.java) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.py) [Javacript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/merge_intervals.js) - Insert Interval [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.java) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Arrays/insert_interval.js) - Interval List Intersections - Employee Free Time From beec13da02fe604666176adf2d9ce833a41b1db2 Mon Sep 17 00:00:00 2001 From: Manmay Ghosh Date: Fri, 2 Jun 2023 00:23:24 +0530 Subject: [PATCH 1253/1894] Create Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp --- ...tring_of_the_partition_is_a_palindrome.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp diff --git a/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp b/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp new file mode 100644 index 00000000..d8a8098d --- /dev/null +++ b/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp @@ -0,0 +1,81 @@ +/* +Name : MAnmay Ghosh +Github username : ManmayGhosh +Repository name : data-structures-and-algorithms +Problem : Given a string s, partition s such that every substring of the partition is a palindrome in C++ +Issue Number : #1373 + +Explanation of the below C++ code : + +A string is given, then a partition of the string is a palindrome partitioning if every substring of the partition is a palindrome. +For example, “aba|b|bbabb|a|b|aba” is a palindrome partitioning of “ababbbabbababa”. +We have to find the minimum cuts needed for a palindrome partitioning of a given string. +For example, minimum of 3 cuts are needed for “ababbbabbababa”. The three cuts are “a|babbbab|b|ababa”. + +Edge Cases +If string is palindrome, then minimum 0 cuts are needed. +If string contain all different characters, then minimum n-1 cuts are needed as by atleast + +-------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ +*/ + +// Dynamic Programming Solution for Palindrome Partitioning Problem +#include +using namespace std; + +// This function returns the minimum number of cuts needed to partition a string such that every part is a palindrome +int minPalPartion(string str) +{ + int n = str.length(); + // C[i][j] = Minimum number of cuts needed for palindrome partitioning of substring str[i..j] + int C[n][n]; + + // P[i][j] = true if substring str[i..j] is palindrome, else false + bool P[n][n]; + + // Note that C[i][j] is 0 if P[i][j] is true + + // A string of length 1 will always be palindrome + for (int i = 0; i < n; i++) { + P[i][i] = true; + C[i][i] = 0; + } + + // L is substring length. Build the solution in bottom up manner by considering all substrings of length starting from 2 to n. + for (int L = 2; L <= n; L++) { + // For substring of length L, set different possible starting indexes + for (int i = 0; i < n - L + 1; i++) { + int j = i + L - 1; // Set ending index + + // If L is 2, then we just need tocompare two characters. + if (L == 2) + P[i][j] = (str[i] == str[j]); + // Else need to check two corner charactersand value of P[i+1][j-1] + else + P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1]; + + // IF str[i..j] is palindrome, then C[i][j] is 0 + if (P[i][j] == true) + C[i][j] = 0; + else { + // Make a cut at every possiblen location starting from i to j,n and get the minimum cost cut. + C[i][j] = INT_MAX; + for (int k = i; k <= j - 1; k++) + C[i][j] = min(C[i][j], C[i][k] + C[k + 1][j] + 1); + } + } + } + // Return the min cut value for complete string. ababbbabbababa + return C[0][n - 1]; +} + +// Driver code +int main() +{ + string str; + cout << "Enter String\t"; + cin >> str; + cout << "Min cuts needed for Palindrome Partitioning is "<< minPalPartion(str); + return 0; +} + From 92bb66148476b4bf51ab17b95b2d6f405b0ee961 Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Fri, 2 Jun 2023 11:35:59 +0000 Subject: [PATCH 1254/1894] Issue resolved #686 --- Linked List/Remove_nth_node_from_end.java | 73 +++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Linked List/Remove_nth_node_from_end.java diff --git a/Linked List/Remove_nth_node_from_end.java b/Linked List/Remove_nth_node_from_end.java new file mode 100644 index 00000000..32c108de --- /dev/null +++ b/Linked List/Remove_nth_node_from_end.java @@ -0,0 +1,73 @@ +/** + Problem :-Remove the nth node from end of the list + https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ + + Approach:- + 1. First find the length of the list and store it in a variable named 'len'. + 2. Then traverse the list (len-n) + 3. Now you are one node behind the node that we have to remove. + + 4. Now set the current node's next to the next.next i.e temp.next=temp.next.next. + + Time Complexity : O(N) + we traverse the list for calculating its length and removing the node.Hence O(N). + + Space Complexity : O(1) + No extra space is required + + Note :- The code is well documented. So take a look. + + + + */ + + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ + +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + if (head == null) return head; // If the head is null, return the head itself + if (head.next == null) { // If there is only one node in the list + if (n == 1) return null; // If n is 1, remove the node and return null + return head; // Otherwise, return the head itself + } + + ListNode temp = head; // Create a temporary node pointing to the head + + int len = size(head); // Get the length of the list + if (len - n == 0) { // If the node to be removed is the head itself + head = head.next; // Move the head to the next node + return head; + } + + len -= n; // Calculate the index of the previous node of the node to be removed + for (int i = 1; i < len; i++) { // Traverse to the previous node so we can remove the next node + temp = temp.next; + } + + if (temp != null && temp.next != null) { // If the previous node and the node to be removed exist + temp.next = temp.next.next; // Point the previous node to the node after the one to be removed + } + + return head; // Return the updated head + } + + int size(ListNode temp) { + ListNode s = temp; + int n = 0; + while (s != null) { // Traverse the list to count the number of nodes + s = s.next; + n += 1; + } + return n; // Return the size of the list + } +} From f205567078cf0166c99f67851a2ebfc05f8e67dd Mon Sep 17 00:00:00 2001 From: mehaksharma23 <91963080+mehaksharma23@users.noreply.github.com> Date: Fri, 2 Jun 2023 17:48:10 +0530 Subject: [PATCH 1255/1894] Update reverse_words_in_a_string.cpp reduced space complexity by removing the need for stack and reducing the number of variables as well. --- Strings/reverse_words_in_a_string.cpp | 46 +++++++++------------------ 1 file changed, 15 insertions(+), 31 deletions(-) diff --git a/Strings/reverse_words_in_a_string.cpp b/Strings/reverse_words_in_a_string.cpp index 3b9a169a..5520d9f9 100644 --- a/Strings/reverse_words_in_a_string.cpp +++ b/Strings/reverse_words_in_a_string.cpp @@ -25,36 +25,20 @@ class Solution { public: string reverseWords(string s) { - // Intitalize variables we will be needing - stack st; - string ans; - string curr_word=""; - - // Traverse through the string and push each word into the stack seperated by ' '. - for(int i=0;i=s.length()) break; // if pointer exceeds the length of the string break! + int j=i+1; // initialize another pointer just ahead of i + while(j Date: Fri, 2 Jun 2023 23:19:12 +0530 Subject: [PATCH 1256/1894] remove duplicate --- Trees/Binary Search Trees/is_valid_bst.cpp | 96 ---------------------- 1 file changed, 96 deletions(-) delete mode 100644 Trees/Binary Search Trees/is_valid_bst.cpp diff --git a/Trees/Binary Search Trees/is_valid_bst.cpp b/Trees/Binary Search Trees/is_valid_bst.cpp deleted file mode 100644 index 40fc0a26..00000000 --- a/Trees/Binary Search Trees/is_valid_bst.cpp +++ /dev/null @@ -1,96 +0,0 @@ -// Binary Search Tree : Is valid Binary Search Tree? -// Program Author : Abhisek Kumar Gupta -/* - Input : 7 3 9 2 4 8 10 -1 - - Output : YES - 7 - / \ - 3 9 - / \ / \ - 2 4 8 10 - -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -void bfs(Node* root){ - queue q; - q.push(root); - q.push(NULL); - while(!q.empty()){ - Node* element = q.front(); - if(element == NULL){ - cout << "\n"; - q.pop(); - if(!q.empty()){ - q.push(NULL); - } - } - else{ - cout << element->data << "->"; - q.pop(); - if(element->left != NULL){ - q.push(element->left); - } - if(element->right != NULL){ - q.push(element->right); - } - } - } - return; -} -Node* insert_into_binary_search_tree(Node* root, int data){ - if(root == NULL) - return new Node(data); - if(data <= root->data){ - root->left = insert_into_binary_search_tree(root->left, data); - } - else{ - root->right = insert_into_binary_search_tree(root->right, data); - } - return root; -} -Node* build_binary_search_tree(){ - int data; - cin >> data; - Node* root = NULL; - while(data != -1){ - root = insert_into_binary_search_tree(root, data); - cin >> data; - } - return root; -} -bool is_binary_search_tree(Node* root, int minimum = INT_MIN, int maximum = INT_MAX){ - if(root == NULL) - return true; - if(root->data >= minimum && root->data <= maximum && is_binary_search_tree(root->left, minimum, root->data) && is_binary_search_tree(root->right, root->data, maximum)) - return true; - return false; - -} -int main(){ - Node* root = build_binary_search_tree(); - cout << endl; - bfs(root); - cout << endl; - if(is_binary_search_tree(root)){ - cout << "YES\n"; - } - else{ - cout << "NO\n"; - } - return 0; -} \ No newline at end of file From 5b3ffa16166af35926edd8e605e3a70cb183a1c1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 2 Jun 2023 23:20:11 +0530 Subject: [PATCH 1257/1894] remove duplicate --- Trees/Binary Search Trees/delete_from_bst.cpp | 149 ------------------ 1 file changed, 149 deletions(-) delete mode 100644 Trees/Binary Search Trees/delete_from_bst.cpp diff --git a/Trees/Binary Search Trees/delete_from_bst.cpp b/Trees/Binary Search Trees/delete_from_bst.cpp deleted file mode 100644 index 31d1ca65..00000000 --- a/Trees/Binary Search Trees/delete_from_bst.cpp +++ /dev/null @@ -1,149 +0,0 @@ -// Binary Search Tree : Deleting from Binary Search Tree -// Program Author : Abhisek Kumar Gupta -/* - Input : 7 3 9 2 4 8 10 -1 - Value to be deleted : 5 - Output : Tree before deletion - 7 - / \ - 3 9 - / \ / \ - 2 4 8 10 - - Inorder Traversal : 2 3 4 7 8 9 10 - - Tree after deletion - 8 - / \ - 3 9 - / \ \ - 2 4 10 - - Inorder Traversal after deletion : 2 3 4 8 9 10 -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -void bfs(Node* root){ - queue q; - q.push(root); - q.push(NULL); - while(!q.empty()){ - Node* element = q.front(); - if(element == NULL){ - cout << "\n"; - q.pop(); - if(!q.empty()){ - q.push(NULL); - } - } - else{ - cout << element->data << "->"; - q.pop(); - if(element->left != NULL){ - q.push(element->left); - } - if(element->right != NULL){ - q.push(element->right); - } - } - } -} -Node* insert_into_binary_search_tree(Node* root, int data){ - if(root == NULL) - return new Node(data); - if(data <= root->data){ - root->left = insert_into_binary_search_tree(root->left, data); - } - else{ - root->right = insert_into_binary_search_tree(root->right, data); - } - return root; -} -Node* build_binary_search_tree(){ - int data; - cin >> data; - Node* root = NULL; - while(data != -1){ - root = insert_into_binary_search_tree(root, data); - cin >> data; - } - return root; -} -Node* delete_from_BST(Node* root, int data){ - if(root == NULL) - return NULL; - if(data < root->data){ - root->left = delete_from_BST(root->left, data); - return root; - } - else if(data == root->data){ - if(root->left == NULL && root->right == NULL){ - delete root; - return NULL; - } - if(root->left == NULL && root->right != NULL){ - Node* temp = root; - root = root->right; - delete temp; - return root; - } - if(root->left != NULL && root->right == NULL){ - Node* temp = root; - root = root->left; - delete temp; - return root; - } - Node* replace = root->right; - while(replace->left != NULL){ - replace = replace->left; - } - root->data = replace->data; - root->right = delete_from_BST(root->right, replace->data); - return root; - } - else{ - root->right = delete_from_BST(root->right, data); - return root; - } - return root; -} -void inorder_traversal(Node* root){ - if(root == NULL){ - return; - } - inorder_traversal(root->left); - cout << root->data << "->"; - inorder_traversal(root->right); -} -int main(){ - Node* root = build_binary_search_tree(); - cout << "\nInorder Traversal\n"; - inorder_traversal(root); - cout << "\n\n"; - cout << "Printing level by level\n"; - bfs(root); - int node_to_be_deleted; - cin >> node_to_be_deleted; - root = delete_from_BST(root, node_to_be_deleted); - cout << endl; - cout << "Printing level by level after deletion\n"; - bfs(root); - cout << "\n"; - cout << "Inorder Traversal\n"; - inorder_traversal(root); - cout << "\n\n"; - return 0; -} \ No newline at end of file From 6531f8b284041fbdf90cacc1db9e9654e3c74fda Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 2 Jun 2023 23:21:06 +0530 Subject: [PATCH 1258/1894] remove undocumented solution --- .../flatten_a_linked_list.cpp | 138 ------------------ 1 file changed, 138 deletions(-) delete mode 100644 Trees/Binary Search Trees/flatten_a_linked_list.cpp diff --git a/Trees/Binary Search Trees/flatten_a_linked_list.cpp b/Trees/Binary Search Trees/flatten_a_linked_list.cpp deleted file mode 100644 index 7ede6c13..00000000 --- a/Trees/Binary Search Trees/flatten_a_linked_list.cpp +++ /dev/null @@ -1,138 +0,0 @@ -// Binary Search Tree : Flatten a Tree [BST to sorted linkedlist] -// Program Author : Abhisek Kumar Gupta -/* - Input : 7 3 9 2 4 8 10 -1 - Output : - 7 - / \ - 3 9 - / \ / \ - 2 4 8 10 - Inorder Traversal : 2 3 4 7 8 9 10 - Flattened Linkedlist : 2->3->4->7->8->9->10-> -*/ -#include -using namespace std; - -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } -}; -class Linked_List{ - public: - Node* head; - Node* tail; -}; -Linked_List flatten_list(Node* root){ - Linked_List l; - if(root == NULL){ - l.head = l.tail = NULL; - return l; - } - if(root->left == NULL && root->right == NULL){ - l.head = l.tail = root; - return l; - } - if(root->left != NULL && root->right == NULL){ - Linked_List left_linked_list = flatten_list(root->left); - left_linked_list.tail->right = root; - l.head = left_linked_list.head; - l.tail = root; - return l; - } - if(root->left == NULL && root->right != NULL){ - Linked_List right_linked_list = flatten_list(root->right); - root->right = right_linked_list.head; - l.head = root; - l.tail = right_linked_list.tail; - return l; - } - Linked_List left_linked_list = flatten_list(root->left); - Linked_List right_linked_list = flatten_list(root->right); - left_linked_list.tail->right = root; - root->right = right_linked_list.head; - - l.head = left_linked_list.head; - l.tail = right_linked_list.tail; - return l; -} -void bfs(Node* root){ - queue q; - q.push(root); - q.push(NULL); - while(!q.empty()){ - Node* element = q.front(); - if(element == NULL){ - cout << "\n"; - q.pop(); - if(!q.empty()){ - q.push(NULL); - } - } - else{ - cout << element->data << "->"; - q.pop(); - if(element->left != NULL){ - q.push(element->left); - } - if(element->right != NULL){ - q.push(element->right); - } - } - } - return; -} -Node* insert_into_binary_search_tree(Node* root, int data){ - if(root == NULL){ - return new Node(data); - } - if(data <= root->data){ - root->left = insert_into_binary_search_tree(root->left, data); - } - else{ - root->right = insert_into_binary_search_tree(root->right, data); - } - return root; -} -Node* build_binary_search_tree(){ - int data; - cin >> data; - Node* root = NULL; - while(data != -1){ - root = insert_into_binary_search_tree(root, data); - cin >> data; - } - return root; -} -void inorder(Node*root){ - if(root == NULL) - return; - inorder(root->left); - cout << root->data << "->"; - inorder(root->right); -} - -int main(){ - Node* root = build_binary_search_tree(); - cout << endl << "Inorder Traversal\n"; - inorder(root); - cout << endl; - bfs(root); - cout << endl; - Linked_List l = flatten_list(root); - Node* temp = l.head; - - while(temp != NULL){ - cout << temp->data << "->"; - temp = temp->right; - } -return 0; -} \ No newline at end of file From e839a28fb1652997447a4a7b778d227a85f83f72 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 2 Jun 2023 23:21:44 +0530 Subject: [PATCH 1259/1894] remove undocumented solution --- kclosest_sol.cpp | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 kclosest_sol.cpp diff --git a/kclosest_sol.cpp b/kclosest_sol.cpp deleted file mode 100644 index 1780625e..00000000 --- a/kclosest_sol.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Author : SUYASH SINGH -/* -Input: points = [[1,3],[-2,2]], k = 1 -Output: [[-2,2]] - -Explanation: - -The distance between (1, 3) and the origin is sqrt(10). -The distance between (-2, 2) and the origin is sqrt(8). -Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. -We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. -*/ -#include -#include - -using namespace std; - -class Solution { -public: - vector> kClosest(vector>& points, int k) { - vector>> v; - for(auto x: points) { - double dis = sqrt(x[0] * x[0] + x[1] * x[1]); - v.push_back({dis, {x[0], x[1]}}); - } - sort(v.begin(), v.end()); - vector> ans; - for(int i=0; i> points {{3, 4}, {1, 2}, {-1, -1}, {0, 0}, {2, 3}, {-2, 2}}; - int k = 3; - Solution s; - vector> closest_points = s.kClosest(points, k); - cout << "The " << k << " closest points to the origin are:\n"; - for(auto point: closest_points) { - cout << "(" << point[0] << ", " << point[1] << ")\n"; - } - return 0; -} From 723be0150e52974720bedbfe408f2a68c073dc86 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 2 Jun 2023 23:22:19 +0530 Subject: [PATCH 1260/1894] move to 2d folder --- {Arrays => 2D Arrays (Matrix)}/Sorted_array_2D.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Arrays => 2D Arrays (Matrix)}/Sorted_array_2D.js (100%) diff --git a/Arrays/Sorted_array_2D.js b/2D Arrays (Matrix)/Sorted_array_2D.js similarity index 100% rename from Arrays/Sorted_array_2D.js rename to 2D Arrays (Matrix)/Sorted_array_2D.js From e6e91bba65a1ae270acbb3f813ddbbf2ed2c8556 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 2 Jun 2023 23:22:51 +0530 Subject: [PATCH 1261/1894] remove undocumented solution --- Arrays/heap_sort.java | 82 ------------------------------------------- 1 file changed, 82 deletions(-) delete mode 100644 Arrays/heap_sort.java diff --git a/Arrays/heap_sort.java b/Arrays/heap_sort.java deleted file mode 100644 index 6bc66f94..00000000 --- a/Arrays/heap_sort.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -Sorting: Implement Heap Sort in Java -*/ - -/* -APPROACH: Build Max Heap: The first step is to build a max heap from the given array. This is done by starting from the middle element of the array and heapifying each subtree in a bottom-up manner. Heapify operation ensures that the largest element is at the root of the subtree. - -Extract Elements: After building the max heap, the largest element (root) is at the top of the heap. We swap it with the last element of the heap and reduce the heap size by 1. Then, we heapify the root to maintain the heap property. We repeat this process until all the elements are extracted and the heap is empty. -*/ - -public class HeapSort { - - public void heapSort(int[] array) { - int length = array.length; - - // Build max heap - for (int i = length / 2 - 1; i >= 0; i--) - heapify(array, length, i); - - // Extract elements from the heap in sorted order - for (int i = length - 1; i > 0; i--) { - // Move current root to end - int temp = array[0]; - array[0] = array[i]; - array[i] = temp; - - // Heapify the reduced heap - heapify(array, i, 0); - } - } - - // Heapify a subtree rooted at index i - void heapify(int[] array, int length, int i) { - int largest = i; // Initialize largest as root - int leftChild = 2 * i + 1; // Left child index - int rightChild = 2 * i + 2; // Right child index - - // If left child is larger than root - if (leftChild < length && array[leftChild] > array[largest]) - largest = leftChild; - - // If right child is larger than largest so far - if (rightChild < length && array[rightChild] > array[largest]) - largest = rightChild; - - // If largest is not the root - if (largest != i) { - // Swap the root with the largest element - int swap = array[i]; - array[i] = array[largest]; - array[largest] = swap; - - // Recursively heapify the affected subtree - heapify(array, length, largest); - } - } - - // Utility function to print an array - void printArray(int[] array) { - int length = array.length; - for (int i = 0; i < length; ++i) - System.out.print(array[i] + " "); - System.out.println(); - } - - public static void main(String[] args) { - int[] array = { 12, 11, 13, 5, 6, 7 }; - int length = array.length; - - HeapSort heapSort = new HeapSort(); - heapSort.heapSort(array); - - System.out.println("Sorted array: "); - heapSort.printArray(array); - } -} -/* -Time Complexity: The time complexity of Heap Sort is O(n log n), where n is the number of elements in the array. The initial heap construction takes O(n) time, and the repeated heapify operation during extraction takes O(log n) time. As we perform heapify for each element, the overall time complexity is O(n log n). - -Space Complexity: The space complexity of Heap Sort is O(1) since the sorting is performed in-place, without requiring any additional space proportional to the input size. -*/ - From 2aa8b3c22dfb5c717018d32e3a70ba5aa8e1f1ab Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Sat, 3 Jun 2023 09:19:20 +0000 Subject: [PATCH 1262/1894] issue resolved #677 --- Linked List/Floyd_cycle_detection_algo.java | 56 +++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Linked List/Floyd_cycle_detection_algo.java diff --git a/Linked List/Floyd_cycle_detection_algo.java b/Linked List/Floyd_cycle_detection_algo.java new file mode 100644 index 00000000..47f3da29 --- /dev/null +++ b/Linked List/Floyd_cycle_detection_algo.java @@ -0,0 +1,56 @@ +/** + Problem :- Linked list cycle + https://leetcode.com/problems/linked-list-cycle/description/ + + Approach:- + 1. Set two pointer on head, slow 's' and a fast 'f' pointer . + 2. The slow pointer will move one step and the fast pointer will move twice the speed of slow pointer. + 3. If the slow and fast pointer meet i.e s==f , it means there is a cycle present. + Hence they will meet a some point(return true if(s==f)). + 4. If the fast pointer is null or its next is null means there is no cycle(return false). + + + + Time Complexity:- O(N) + Even if there is a cycle exists we traverse the given list, Hence * linear time *. + + Space Complexity:- O(1) + No extra space is required. + + + + */ + + + +// Easy Solution will well documented code . + +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + if (head == null || head.next == null) + return false; + ListNode s = head; // slow pointer + ListNode f = head; // fast pointer + + while (f != null && f.next != null) { + s = s.next; // move slow pointer by 1 step + f = f.next.next; // move fast pointer by 2 steps + + if (s == f) // if slow and fast pointers meet, there is a cycle + return true; + } + + return false; // if fast pointer reaches the end, there is no cycle + } +} From d8571732210b80a576d21186371abe511dfe8605 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sat, 3 Jun 2023 16:05:15 +0530 Subject: [PATCH 1263/1894] Count Sort added to Sorting Algorithms --- sorting/count_sort.c | 58 ++++++++++++++++++++++++++++++++++++ sorting/count_sort.cpp | 65 ++++++++++++++++++++++++++++++++++++++++ sorting/count_sort.java | 66 +++++++++++++++++++++++++++++++++++++++++ sorting/count_sort.js | 42 ++++++++++++++++++++++++++ sorting/count_sort.php | 62 ++++++++++++++++++++++++++++++++++++++ sorting/count_sort.py | 43 +++++++++++++++++++++++++++ 6 files changed, 336 insertions(+) create mode 100644 sorting/count_sort.c create mode 100644 sorting/count_sort.cpp create mode 100644 sorting/count_sort.java create mode 100644 sorting/count_sort.js create mode 100644 sorting/count_sort.php create mode 100644 sorting/count_sort.py diff --git a/sorting/count_sort.c b/sorting/count_sort.c new file mode 100644 index 00000000..b4ca527b --- /dev/null +++ b/sorting/count_sort.c @@ -0,0 +1,58 @@ +int getMax(int a[], int n) { + int max = a[0]; + for(int i = 1; i max) + max = a[i]; + } + return max; //maximum element from the array +} + +void countSort(int a[], int n) // function to perform counting sort +{ + int output[n+1]; + int max = getMax(a, n); + int count[max+1]; //create count array with size [max+1] + + + for (int i = 0; i <= max; ++i) + { + count[i] = 0; // Initialize count array with all zeros + } + + for (int i = 0; i < n; i++) // Store the count of each element + { + count[a[i]]++; + } + + for(int i = 1; i<=max; i++) + count[i] += count[i-1]; //find cumulative frequency + + /* This loop will find the index of each element of the original array in count array, and + place the elements in output array*/ + for (int i = n - 1; i >= 0; i--) { + output[count[a[i]] - 1] = a[i]; + count[a[i]]--; // decrease count for same numbers +} + + for(int i = 0; i +using namespace std; + +int getMax(int a[], int n) +{ + int max = a[0]; + for (int i = 1; i < n; i++) + { + if (a[i] > max) + max = a[i]; + } + return max; // maximum element from the array +} + +void countSort(int a[], int n) // function to perform counting sort +{ + int output[n + 1]; + int max = getMax(a, n); + int count[max + 1]; // create count array with size [max+1] + + for (int i = 0; i <= max; ++i) + { + count[i] = 0; // Initialize count array with all zeros + } + + for (int i = 0; i < n; i++) // Store the count of each element + { + count[a[i]]++; + } + + for (int i = 1; i <= max; i++) + count[i] += count[i - 1]; // find cumulative frequency + + /* This loop will find the index of each element of the original array in count array, and + place the elements in output array*/ + for (int i = n - 1; i >= 0; i--) + { + output[count[a[i]] - 1] = a[i]; + count[a[i]]--; // decrease count for same numbers + } + + for (int i = 0; i < n; i++) + { + a[i] = output[i]; // store the sorted elements into main array + } +} + +void printArr(int a[], int n) /* function to print the array */ +{ + int i; + for (i = 0; i < n; i++) + cout << a[i] << " "; +} + +int main() +{ + int a[] = {31, 11, 42, 7, 30, 11}; + int n = sizeof(a) / sizeof(a[0]); + cout << "Before sorting array elements are - \n"; + printArr(a, n); + countSort(a, n); + cout << "\nAfter sorting array elements are - \n"; + printArr(a, n); + return 0; +} \ No newline at end of file diff --git a/sorting/count_sort.java b/sorting/count_sort.java new file mode 100644 index 00000000..0136cbb9 --- /dev/null +++ b/sorting/count_sort.java @@ -0,0 +1,66 @@ +class CountingSort { + +int getMax(int[] a, int n) { + int max = a[0]; + for(int i = 1; i max) + max = a[i]; + } + return max; //maximum element from the array +} + +void countSort(int[] a, int n) // function to perform counting sort +{ + int[] output = new int [n+1]; + int max = getMax(a, n); + //int max = 42; + int[] count = new int [max+1]; //create count array with size [max+1] + + for (int i = 0; i <= max; ++i) + { + count[i] = 0; // Initialize count array with all zeros + } + + for (int i = 0; i < n; i++) // Store the count of each element + { + count[a[i]]++; + } + + for(int i = 1; i<=max; i++) + count[i] += count[i-1]; //find cumulative frequency + + /* This loop will find the index of each element of the original array in + + count array, and + place the elements in output array*/ + for (int i = n - 1; i >= 0; i--) { + output[count[a[i]] - 1] = a[i]; + count[a[i]]--; // decrease count for same numbers + } + + for(int i = 0; i 0); + + // Create a count array to store count of individual + // characters and initialize count array as 0 + var count = Array.from({length: 256}, (_, i) => 0); + + + // store count of each character + for (var i = 0; i < n; ++i) + ++count[arr[i].charCodeAt(0)]; + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (var i = 1; i <= 255; ++i) + count[i] += count[i - 1]; + + // Build the output character array + // To make it stable we are operating in reverse order. + for (var i = n - 1; i >= 0; i--) { + output[count[arr[i].charCodeAt(0)] - 1] = arr[i]; + --count[arr[i].charCodeAt(0)]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (var i = 0; i < n; ++i) + arr[i] = output[i]; + return arr; +} + +// Driver method + var arr = [ 'g', 'e', 'e', 'k', 's', 'f', 'o', + 'r', 'g', 'e', 'e', 'k', 's' ]; + + arr = sort(arr); + document.write("Sorted character array is "); + for (var i = 0; i < arr.length; ++i) + document.write(arr[i]); \ No newline at end of file diff --git a/sorting/count_sort.php b/sorting/count_sort.php new file mode 100644 index 00000000..97be9fa4 --- /dev/null +++ b/sorting/count_sort.php @@ -0,0 +1,62 @@ + $max) + $max = $a[$i]; + } + return $max; //maximum element from the array +} + +function countSort(&$a, $n) // function to perform counting sort +{ + $LeftArray = array($n + 1); + $max = getMax($a, $n); + $count = array($max + 1); //create count array with size [max+1] + + for ($i = 0; $i <= $max; ++$i) + { + $count[$i] = 0; // Initialize count array with all zeros + } + + for ($i = 0; $i < $n; $i++) // Store the count of each element + { + $count[$a[$i]]++; + } + + for($i = 1; $i<=$max; $i++) + $count[$i] += $count[$i-1]; //find cumulative frequency + + /* This loop will find the index of each element of the original array in +count array, and + place the elements in output array*/ + for ($i = $n - 1; $i >= 0; $i--) { + $output[$count[$a[$i]] - 1] = $a[$i]; + $count[$a[$i]]--; // decrease count for same numbers +} + + for($i = 0; $i<$n; $i++) { + $a[$i] = $output[$i]; //store the sorted elements into main array + } +} + +/* Function to print the array elements */ +function printArray($a, $n) +{ + for($i = 0; $i < $n; $i++) + { + print_r($a[$i]); + echo " "; + } +} + + $a = array( 9, 28, 22, 5, 29, 14, 37, 28, 9 ); + $n = count($a); + echo "Before sorting array elements are -
"; + printArray($a, $n); + countSort($a,$n); + echo "
After sorting array elements are -
"; + printArray($a, $n); + +?> \ No newline at end of file diff --git a/sorting/count_sort.py b/sorting/count_sort.py new file mode 100644 index 00000000..2fadcac7 --- /dev/null +++ b/sorting/count_sort.py @@ -0,0 +1,43 @@ +# The main function that sort the given string arr[] in +# alphabetical order + + +def countSort(arr): + + # The output character array that will have sorted arr + output = [0 for i in range(len(arr))] + + # Create a count array to store count of individual + # characters and initialize count array as 0 + count = [0 for i in range(256)] + + # For storing the resulting answer since the + # string is immutable + ans = ["" for _ in arr] + + # Store count of each character + for i in arr: + count[ord(i)] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this character in output array + for i in range(256): + count[i] += count[i-1] + + # Build the output character array + for i in range(len(arr)): + output[count[ord(arr[i])]-1] = arr[i] + count[ord(arr[i])] -= 1 + + # Copy the output array to arr, so that arr now + # contains sorted characters + for i in range(len(arr)): + ans[i] = output[i] + return ans + + +# Driver code +if __name__ == '__main__': + arr = "geeksforgeeks" + ans = countSort(arr) + print("Sorted character array is % s" % ("".join(ans))) \ No newline at end of file From 4c27d436f3b4b14bcf83bee0b29ffd5307858991 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sat, 3 Jun 2023 17:16:19 +0530 Subject: [PATCH 1264/1894] Radix Sort Algorithms added --- sorting/radix_sort.cpp | 76 +++++++++++++++++++++++++++++++++++++ sorting/radix_sort.cs | 83 +++++++++++++++++++++++++++++++++++++++++ sorting/radix_sort.java | 81 ++++++++++++++++++++++++++++++++++++++++ sorting/radix_sort.js | 74 ++++++++++++++++++++++++++++++++++++ sorting/radix_sort.php | 72 +++++++++++++++++++++++++++++++++++ sorting/radix_sort.py | 61 ++++++++++++++++++++++++++++++ 6 files changed, 447 insertions(+) create mode 100644 sorting/radix_sort.cpp create mode 100644 sorting/radix_sort.cs create mode 100644 sorting/radix_sort.java create mode 100644 sorting/radix_sort.js create mode 100644 sorting/radix_sort.php create mode 100644 sorting/radix_sort.py diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp new file mode 100644 index 00000000..726deee4 --- /dev/null +++ b/sorting/radix_sort.cpp @@ -0,0 +1,76 @@ +#include +using namespace std; + +// Function to get maximum value in arr[] +int getMax(int arr[], int n) +{ + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to +// the digit represented by exp. +void countSort(int arr[], int n, int exp) +{ + int output[n]; // output array + int i, count[10] = { 0 }; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using +// Radix Sort +void radixsort(int arr[], int n) +{ + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that instead + // of passing digit number, exp is passed. exp is 10^i + // where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); +} + +// Function to print an array +void print(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; +} + + +int main() +{ + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = sizeof(arr) / sizeof(arr[0]); + + // Function Call + radixsort(arr, n); + print(arr, n); + return 0; +} + +// Time Compexity -> O((n+k)*d) +// Space Complexity -> O(n+k) \ No newline at end of file diff --git a/sorting/radix_sort.cs b/sorting/radix_sort.cs new file mode 100644 index 00000000..aecec391 --- /dev/null +++ b/sorting/radix_sort.cs @@ -0,0 +1,83 @@ +// C# implementation of Radix Sort +using System; + +class RadixSort { + public static int getMax(int[] arr, int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + public static void countSort(int[] arr, int n, int exp) + { + int[] output = new int[n]; // output array + int i; + int[] count = new int[10]; + + // initializing all elements of count to 0 + for (i = 0; i < 10; i++) + count[i] = 0; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual + // position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of size n using + // Radix Sort + public static void radixsort(int[] arr, int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + public static void print(int[] arr, int n) + { + for (int i = 0; i < n; i++) + Console.Write(arr[i] + " "); + } + + // Driver Code + public static void Main() + { + int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.Length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} + +// Time Compexity -> O((n+k)*d) +// Space Complexity -> O(n+k) \ No newline at end of file diff --git a/sorting/radix_sort.java b/sorting/radix_sort.java new file mode 100644 index 00000000..b4611f32 --- /dev/null +++ b/sorting/radix_sort.java @@ -0,0 +1,81 @@ +import java.io.*; +import java.util.*; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + { + int mx = arr[0]; + for (int i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + { + int output[] = new int[n]; // output array + int i; + int count[] = new int[10]; + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current + // digit + for (i = 0; i < n; i++) + arr[i] = output[i]; + } + + // The main function to that sorts arr[] of + // size n using Radix Sort + static void radixsort(int arr[], int n) + { + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + countSort(arr, n, exp); + } + + // A utility function to print an array + static void print(int arr[], int n) + { + for (int i = 0; i < n; i++) + System.out.print(arr[i] + " "); + } + + // Main driver method + public static void main(String[] args) + { + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int n = arr.length; + + // Function Call + radixsort(arr, n); + print(arr, n); + } +} + +// Time Compexity -> O((n+k)*d) +// Space Complexity -> O(n+k) \ No newline at end of file diff --git a/sorting/radix_sort.js b/sorting/radix_sort.js new file mode 100644 index 00000000..748e783d --- /dev/null +++ b/sorting/radix_sort.js @@ -0,0 +1,74 @@ +// A utility function to get maximum value in arr[] +function getMax(arr,n) +{ + let mx = arr[0]; + for (let i = 1; i < n; i++) + if (arr[i] > mx) + mx = arr[i]; + return mx; +} + +// A function to do counting sort of arr[] according to + // the digit represented by exp. +function countSort(arr,n,exp) +{ + let output = new Array(n); // output array + let i; + let count = new Array(10); + for(let i=0;i<10;i++) + count[i]=0; + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) { + let x = Math.floor(arr[i] / exp) % 10; + count[x]++; + } + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + output[count[x] - 1] = arr[i]; + count[x]--; + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to current digit + for (i = 0; i < n; i++) + arr[i] = output[i]; +} + +// The main function to that sorts arr[] of size n using + // Radix Sort +function radixsort(arr,n) +{ + // Find the maximum number to know number of digits + let m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (let exp = 1; Math.floor(m / exp) > 0; exp *= 10) + countSort(arr, n, exp); +} + +// A utility function to print an array +function print(arr,n) +{ + for (let i = 0; i < n; i++) + document.write(arr[i] + " "); +} + +/*Driver Code*/ +let arr=[170, 45, 75, 90, 802, 24, 2, 66]; +let n = arr.length; + +// Function Call +radixsort(arr, n); +print(arr, n); + +// Time Compexity -> O((n+k)*d) +// Space Complexity -> O(n+k) \ No newline at end of file diff --git a/sorting/radix_sort.php b/sorting/radix_sort.php new file mode 100644 index 00000000..f09e6664 --- /dev/null +++ b/sorting/radix_sort.php @@ -0,0 +1,72 @@ += 0; $i--) + { + $output[$count[ ($arr[$i] / + $exp) % 10 ] - 1] = $arr[$i]; + $count[ ($arr[$i] / $exp) % 10 ]--; + } + + // Copy the output array to arr[], so + // that arr[] now contains sorted numbers + // according to current digit + for ($i = 0; $i < $n; $i++) + $arr[$i] = $output[$i]; +} + +// The main function to that sorts arr[] +// of size n using Radix Sort +function radixsort(&$arr, $n) +{ + + // Find the maximum number to know + // number of digits + $m = max($arr); + + // Do counting sort for every digit. Note + // that instead of passing digit number, + // exp is passed. exp is 10^i where i is + // current digit number + for ($exp = 1; $m / $exp > 0; $exp *= 10) + countSort($arr, $n, $exp); +} + +// A utility function to print an array +function PrintArray(&$arr,$n) +{ + for ($i = 0; $i < $n; $i++) + echo $arr[$i] . " "; +} + +// Driver Code +$arr = array(170, 45, 75, 90, 802, 24, 2, 66); +$n = count($arr); + +// Function Call +radixsort($arr, $n); +PrintArray($arr, $n); + +?> + + + \ No newline at end of file diff --git a/sorting/radix_sort.py b/sorting/radix_sort.py new file mode 100644 index 00000000..280df3b4 --- /dev/null +++ b/sorting/radix_sort.py @@ -0,0 +1,61 @@ +# Method to do Radix Sort +def countingSort(arr, exp1): + + n = len(arr) + + # The output array elements that will have sorted arr + output = [0] * (n) + + # initialize count array as 0 + count = [0] * (10) + + # Store count of occurrences in count[] + for i in range(0, n): + index = arr[i] // exp1 + count[index % 10] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this digit in output array + for i in range(1, 10): + count[i] += count[i - 1] + + # Build the output array + i = n - 1 + while i >= 0: + index = arr[i] // exp1 + output[count[index % 10] - 1] = arr[i] + count[index % 10] -= 1 + i -= 1 + + # Copying the output array to arr[], + # so that arr now contains sorted numbers + i = 0 + for i in range(0, len(arr)): + arr[i] = output[i] + +# Method to do Radix Sort +def radixSort(arr): + + # Find the maximum number to know number of digits + max1 = max(arr) + + # Do counting sort for every digit. Note that instead + # of passing digit number, exp is passed. exp is 10^i + # where i is current digit number + exp = 1 + while max1 / exp >= 1: + countingSort(arr, exp) + exp *= 10 + + +# Driver code +arr = [170, 45, 75, 90, 802, 24, 2, 66] + +# Function Call +radixSort(arr) + +for i in range(len(arr)): + print(arr[i],end=" ") + +# Time Compexity -> O((n+k)*d) +# Space Complexity -> O(n+k) \ No newline at end of file From 615af410f565f9344f51b3af925734d0195c5392 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 18:49:06 +0530 Subject: [PATCH 1265/1894] rename file --- ...inter_Merge_Sorted_Array_in_C++.cpp => merge_sorted_array.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp => merge_sorted_array.cpp} (100%) diff --git a/Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp b/Arrays/merge_sorted_array.cpp similarity index 100% rename from Arrays/Create_Two_Pointer_Merge_Sorted_Array_in_C++.cpp rename to Arrays/merge_sorted_array.cpp From a96920311820e7631db5b12f12376ea005dfca02 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 18:49:13 +0530 Subject: [PATCH 1266/1894] remove duplicate --- Arrays/merge_two_sorted_array.cpp | 49 ------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 Arrays/merge_two_sorted_array.cpp diff --git a/Arrays/merge_two_sorted_array.cpp b/Arrays/merge_two_sorted_array.cpp deleted file mode 100644 index 0bd6b08a..00000000 --- a/Arrays/merge_two_sorted_array.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Description: -// You are given two integer arrays nums1 and nums2, -// sorted in non-decreasing order, and two integers -// m and n, representing the number of elements in -// nums1 and nums2 respectively. - -// Merge nums1 and nums2 into a single array sorted -// in non-decreasing order. - -// The final sorted array should not be returned by -// the function, but instead be stored inside the -// array nums1. To accommodate this, nums1 has a -// length of m + n, where the first m elements denote -// the elements that should be merged, and the last -// n elements are set to 0 and should be ignored. -// nums2 has a length of n. - -// Sample Input/Output: - -// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 - -// Output: [1,2,2,3,5,6] - -// Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. - -// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1 - -// Time complexity of this code is O(m+n) -// Space complexity is O(1) - -class Solution { -public: - void merge(vector& nums1, int m, vector& nums2, int n) { - int tar = m + n - 1; // size of nums1 - - int i = m - 1; // index of last element of nums1 - - int j = n - 1; // index of last element of nums2 - - while(j >= 0) { // iterate from last - - if( i >= 0 && nums1[i] > nums2[j]) - nums1[tar--] = nums1[i--]; - else - nums1[tar--] = nums2[j--]; - - } - } -}; From 2d602384c2d840229bb0bc1212e73a25d00c9034 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 18:59:35 +0530 Subject: [PATCH 1267/1894] add firstduplicate value using map --- Arrays/first_duplicate_value.go | 81 +++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Arrays/first_duplicate_value.go diff --git a/Arrays/first_duplicate_value.go b/Arrays/first_duplicate_value.go new file mode 100644 index 00000000..1fa9760a --- /dev/null +++ b/Arrays/first_duplicate_value.go @@ -0,0 +1,81 @@ +package main + +import "fmt" + +/* +Approach 1: + 1. We define the `FirstDuplicateValue` function that takes an array of integers as input and returns the + first duplicate value found in the array. + + 2. Inside the function, we create a map named `seenSoFar` using the `make` function. This map will be + used to keep track of the numbers that have been seen so far in the array. + + 3. We iterate over each number in the `array` using the `range` keyword. + + 4. For each number, we check if it exists as a key in the `seenSoFar` map. If the value exists, it means + the number has been seen before and is a duplicate. + + 5. If a duplicate value is found, we immediately return the duplicate value as the result. + + 6. If the number is not a duplicate, we add it to the `seenSoFar` map by setting the corresponding key to + `true`, indicating that it has been seen. + + 7. After iterating through all the numbers in the array without finding a duplicate, we return -1 to + indicate that no duplicate value was found. + + In the `main` function, we demonstrate the usage of the `FirstDuplicateValue` function by creating an + example array with some duplicate values. We call the function and store the result in the `firstDuplicate` + variable. Finally, we print the `firstDuplicate` value, which gives us the first duplicate value in the array. + In this case, the output will be "2" since it is the first duplicate value encountered in the array + `[2, 3, 1, 4, 2, 5, 3]`. +*/ + +func FirstDuplicateValue(array []int) int { + // Create a map to store the numbers that have been seen so far. + seenSoFar := make(map[int]bool) + + // Iterate over each number in the array. + for _, num := range array { + // Check if the current number has been seen before. + if _, valueExists := seenSoFar[num]; valueExists { + // If the number is already in the map, it is the first duplicate value. + return num + } + + // Add the current number to the map to mark it as seen. + seenSoFar[num] = true + } + + // If no duplicate value is found, return -1. + return -1 +} + +/* +Approach2: + The code defines a function FirstDuplicateValue that takes an integer array array as its input and returns the + first integer value that appears more than once in the input array. The function implements this using a + technique called "negation of visited elements". + + The function first loops through each element in the input array array. For each element, it computes the + absolute value using the abs function, which is defined as a separate helper function. The absolute value + is used to get the index of the element in the array (adjusted by -1 to account for 0-based indexing). + + If the element at the computed index in the array is already negative, it means that we have seen this + element before and hence it is a duplicate. In this case, we return the absolute value of the element. + + If the element is not negative, we negate it to mark it as visited. This is done by multiplying the + element at the computed index in the array by -1. + + If there are no duplicate values in the input array, the function returns -1. + + Overall, this approach uses constant extra space and has a time complexity of O(n), where n is the + length of the input array. +*/ + + +func main() { + // Example usage of FirstDuplicateValue function + array := []int{2, 3, 1, 4, 2, 5, 3} + firstDuplicate := FirstDuplicateValue(array) + fmt.Println("First Duplicate Value:", firstDuplicate) +} \ No newline at end of file From 6ee463fa1541d4fdfeed4c5177444a9d15c46604 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 18:59:55 +0530 Subject: [PATCH 1268/1894] add first duplicate optimal approach --- Arrays/first_duplicate_value.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Arrays/first_duplicate_value.go b/Arrays/first_duplicate_value.go index 1fa9760a..94ad3766 100644 --- a/Arrays/first_duplicate_value.go +++ b/Arrays/first_duplicate_value.go @@ -71,11 +71,40 @@ Approach2: Overall, this approach uses constant extra space and has a time complexity of O(n), where n is the length of the input array. */ +// Function to find the first duplicate value in an array. +func FirstDuplicateValue2(array []int) int { + // Iterate over each element in the array. + for _, num := range array { + // Get the absolute value of the current element. + absValue := abs(num) + + // Check if the value at the index (absValue - 1) in the array is negative. + if array[absValue - 1] < 0 { + // If it is negative, then the current element is the first duplicate value. + return absValue + } + + // Otherwise, mark the value at the index (absValue - 1) in the array as negative. + array[absValue - 1] *= -1 + } + + // If no duplicates are found, return -1. + return -1 +} +// Function to get the absolute value of a number. +func abs(num int) int { + if num < 0 { + return -num + } + return num +} func main() { // Example usage of FirstDuplicateValue function array := []int{2, 3, 1, 4, 2, 5, 3} firstDuplicate := FirstDuplicateValue(array) fmt.Println("First Duplicate Value:", firstDuplicate) + firstDuplicate = FirstDuplicateValue2(array) + fmt.Println("First Duplicate Value:", firstDuplicate) } \ No newline at end of file From 56ed2f9318886030f6b878c5d18bdab755e92d43 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 19:01:32 +0530 Subject: [PATCH 1269/1894] add sample io and question --- Arrays/first_duplicate_value.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Arrays/first_duplicate_value.go b/Arrays/first_duplicate_value.go index 94ad3766..e825f4af 100644 --- a/Arrays/first_duplicate_value.go +++ b/Arrays/first_duplicate_value.go @@ -1,3 +1,11 @@ +/* + Given an array of integers between 1 and n, inclusive where n is the length of the array, write a function + that returns the first integer that appears more than once (when the array isread from left to right). + + Sample Input: [2, 3, 1, 4, 2, 5, 3] + Output: 2 +*/ + package main import "fmt" From 2fc1c8b3cfeac6200682d71a315e8b70a1ab1288 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 3 Jun 2023 19:03:27 +0530 Subject: [PATCH 1270/1894] rename file --- .../{find_first_duplicate_value.cpp => first_duplicate_value.cpp} | 0 ...find_first_duplicate_value.java => first_duplicate_value.java} | 0 .../{find_first_duplicate_value.js => first_duplicate_value.js} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Arrays/{find_first_duplicate_value.cpp => first_duplicate_value.cpp} (100%) rename Arrays/{find_first_duplicate_value.java => first_duplicate_value.java} (100%) rename Arrays/{find_first_duplicate_value.js => first_duplicate_value.js} (100%) diff --git a/Arrays/find_first_duplicate_value.cpp b/Arrays/first_duplicate_value.cpp similarity index 100% rename from Arrays/find_first_duplicate_value.cpp rename to Arrays/first_duplicate_value.cpp diff --git a/Arrays/find_first_duplicate_value.java b/Arrays/first_duplicate_value.java similarity index 100% rename from Arrays/find_first_duplicate_value.java rename to Arrays/first_duplicate_value.java diff --git a/Arrays/find_first_duplicate_value.js b/Arrays/first_duplicate_value.js similarity index 100% rename from Arrays/find_first_duplicate_value.js rename to Arrays/first_duplicate_value.js From 9ef2cda3694ab00c3393e400200cd11924603b5f Mon Sep 17 00:00:00 2001 From: Kiran Date: Sat, 3 Jun 2023 19:26:29 +0530 Subject: [PATCH 1271/1894] Changes made in Radix Sort Algorithm --- sorting/radix_sort.cpp | 56 ++++++++++++++++++++++++++++++++ sorting/radix_sort.cs | 56 ++++++++++++++++++++++++++++++++ sorting/radix_sort.java | 56 ++++++++++++++++++++++++++++++++ sorting/radix_sort.js | 56 ++++++++++++++++++++++++++++++++ sorting/radix_sort.php | 72 ----------------------------------------- sorting/radix_sort.py | 54 +++++++++++++++++++++++++++++++ 6 files changed, 278 insertions(+), 72 deletions(-) delete mode 100644 sorting/radix_sort.php diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index 726deee4..b52c372b 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -1,3 +1,59 @@ +/* + Radix Sort +1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider +during the sorting process. + +2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each +digit position, moving towards the most significant digit (leftmost digit): +a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used +to store the frequency of each digit at the current position. +b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the +current digit position is the units place, count the frequency of each digit from 0 to 9. +c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step +ensures that the count array contains the correct positions for each digit in the sorted order. +d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count +array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for +that digit in the count array. +e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted +based on the current digit position. + +3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit +position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least +significant digit to the most significant digit. + +4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. + +Here's an example to illustrate the process: + +Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] +Maximum number: 802 + +# 1. First iteration (Least significant digit - rightmost digit): + # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] + # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] + # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + +# 2. Second iteration (Next least significant digit): + # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] + # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] + # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + +# 3. Third iteration (Most significant digit): + # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] + # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] + # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + +# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. + +# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. +# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at +# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. + +*/ + #include using namespace std; diff --git a/sorting/radix_sort.cs b/sorting/radix_sort.cs index aecec391..cf0a1894 100644 --- a/sorting/radix_sort.cs +++ b/sorting/radix_sort.cs @@ -1,3 +1,59 @@ +/* + Radix Sort +1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider +during the sorting process. + +2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each +digit position, moving towards the most significant digit (leftmost digit): +a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used +to store the frequency of each digit at the current position. +b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the +current digit position is the units place, count the frequency of each digit from 0 to 9. +c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step +ensures that the count array contains the correct positions for each digit in the sorted order. +d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count +array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for +that digit in the count array. +e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted +based on the current digit position. + +3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit +position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least +significant digit to the most significant digit. + +4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. + +Here's an example to illustrate the process: + +Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] +Maximum number: 802 + +# 1. First iteration (Least significant digit - rightmost digit): + # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] + # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] + # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + +# 2. Second iteration (Next least significant digit): + # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] + # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] + # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + +# 3. Third iteration (Most significant digit): + # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] + # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] + # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + +# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. + +# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. +# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at +# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. + +*/ + // C# implementation of Radix Sort using System; diff --git a/sorting/radix_sort.java b/sorting/radix_sort.java index b4611f32..925a3978 100644 --- a/sorting/radix_sort.java +++ b/sorting/radix_sort.java @@ -1,3 +1,59 @@ +/* + Radix Sort +1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider +during the sorting process. + +2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each +digit position, moving towards the most significant digit (leftmost digit): +a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used +to store the frequency of each digit at the current position. +b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the +current digit position is the units place, count the frequency of each digit from 0 to 9. +c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step +ensures that the count array contains the correct positions for each digit in the sorted order. +d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count +array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for +that digit in the count array. +e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted +based on the current digit position. + +3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit +position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least +significant digit to the most significant digit. + +4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. + +Here's an example to illustrate the process: + +Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] +Maximum number: 802 + +# 1. First iteration (Least significant digit - rightmost digit): + # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] + # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] + # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + +# 2. Second iteration (Next least significant digit): + # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] + # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] + # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + +# 3. Third iteration (Most significant digit): + # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] + # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] + # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + +# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. + +# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. +# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at +# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. + +*/ + import java.io.*; import java.util.*; diff --git a/sorting/radix_sort.js b/sorting/radix_sort.js index 748e783d..de6ec097 100644 --- a/sorting/radix_sort.js +++ b/sorting/radix_sort.js @@ -1,3 +1,59 @@ +/* + Radix Sort +1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider +during the sorting process. + +2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each +digit position, moving towards the most significant digit (leftmost digit): +a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used +to store the frequency of each digit at the current position. +b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the +current digit position is the units place, count the frequency of each digit from 0 to 9. +c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step +ensures that the count array contains the correct positions for each digit in the sorted order. +d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count +array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for +that digit in the count array. +e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted +based on the current digit position. + +3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit +position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least +significant digit to the most significant digit. + +4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. + +Here's an example to illustrate the process: + +Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] +Maximum number: 802 + +# 1. First iteration (Least significant digit - rightmost digit): + # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] + # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] + # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + +# 2. Second iteration (Next least significant digit): + # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] + # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] + # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + +# 3. Third iteration (Most significant digit): + # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] + # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] + # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + +# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. + +# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. +# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at +# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. + +*/ + // A utility function to get maximum value in arr[] function getMax(arr,n) { diff --git a/sorting/radix_sort.php b/sorting/radix_sort.php deleted file mode 100644 index f09e6664..00000000 --- a/sorting/radix_sort.php +++ /dev/null @@ -1,72 +0,0 @@ -= 0; $i--) - { - $output[$count[ ($arr[$i] / - $exp) % 10 ] - 1] = $arr[$i]; - $count[ ($arr[$i] / $exp) % 10 ]--; - } - - // Copy the output array to arr[], so - // that arr[] now contains sorted numbers - // according to current digit - for ($i = 0; $i < $n; $i++) - $arr[$i] = $output[$i]; -} - -// The main function to that sorts arr[] -// of size n using Radix Sort -function radixsort(&$arr, $n) -{ - - // Find the maximum number to know - // number of digits - $m = max($arr); - - // Do counting sort for every digit. Note - // that instead of passing digit number, - // exp is passed. exp is 10^i where i is - // current digit number - for ($exp = 1; $m / $exp > 0; $exp *= 10) - countSort($arr, $n, $exp); -} - -// A utility function to print an array -function PrintArray(&$arr,$n) -{ - for ($i = 0; $i < $n; $i++) - echo $arr[$i] . " "; -} - -// Driver Code -$arr = array(170, 45, 75, 90, 802, 24, 2, 66); -$n = count($arr); - -// Function Call -radixsort($arr, $n); -PrintArray($arr, $n); - -?> - - - \ No newline at end of file diff --git a/sorting/radix_sort.py b/sorting/radix_sort.py index 280df3b4..b9e96bbe 100644 --- a/sorting/radix_sort.py +++ b/sorting/radix_sort.py @@ -1,3 +1,57 @@ + +# Radix Sort +# 1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider +# during the sorting process. + +# 2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each +# digit position, moving towards the most significant digit (leftmost digit): +# a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used +# to store the frequency of each digit at the current position. +# b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the +# current digit position is the units place, count the frequency of each digit from 0 to 9. +# c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step +# ensures that the count array contains the correct positions for each digit in the sorted order. +# d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count +# array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for +# that digit in the count array. +# e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted +# based on the current digit position. + +# 3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit +# position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least +# significant digit to the most significant digit. + +# 4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. + +# Here's an example to illustrate the process: + +# Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] +# Maximum number: 802 + +# 1. First iteration (Least significant digit - rightmost digit): + # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] + # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] + # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] + +# 2. Second iteration (Next least significant digit): + # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] + # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] + # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] + +# 3. Third iteration (Most significant digit): + # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] + # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] + # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] + +# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. + +# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. +# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at +# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. + # Method to do Radix Sort def countingSort(arr, exp1): From f6df0932d9b27b2972a48bd36dd67e8f0d9b0515 Mon Sep 17 00:00:00 2001 From: Kiran Date: Sat, 3 Jun 2023 19:48:29 +0530 Subject: [PATCH 1272/1894] Changes made in Count Sort Algorithm --- sorting/count_sort.c | 58 -------------------------------------- sorting/count_sort.cpp | 36 ++++++++++++++++++++++++ sorting/count_sort.java | 36 ++++++++++++++++++++++++ sorting/count_sort.js | 36 ++++++++++++++++++++++++ sorting/count_sort.php | 62 ----------------------------------------- sorting/count_sort.py | 39 +++++++++++++++++++++++--- 6 files changed, 143 insertions(+), 124 deletions(-) delete mode 100644 sorting/count_sort.c delete mode 100644 sorting/count_sort.php diff --git a/sorting/count_sort.c b/sorting/count_sort.c deleted file mode 100644 index b4ca527b..00000000 --- a/sorting/count_sort.c +++ /dev/null @@ -1,58 +0,0 @@ -int getMax(int a[], int n) { - int max = a[0]; - for(int i = 1; i max) - max = a[i]; - } - return max; //maximum element from the array -} - -void countSort(int a[], int n) // function to perform counting sort -{ - int output[n+1]; - int max = getMax(a, n); - int count[max+1]; //create count array with size [max+1] - - - for (int i = 0; i <= max; ++i) - { - count[i] = 0; // Initialize count array with all zeros - } - - for (int i = 0; i < n; i++) // Store the count of each element - { - count[a[i]]++; - } - - for(int i = 1; i<=max; i++) - count[i] += count[i-1]; //find cumulative frequency - - /* This loop will find the index of each element of the original array in count array, and - place the elements in output array*/ - for (int i = n - 1; i >= 0; i--) { - output[count[a[i]] - 1] = a[i]; - count[a[i]]--; // decrease count for same numbers -} - - for(int i = 0; i using namespace std; diff --git a/sorting/count_sort.java b/sorting/count_sort.java index 0136cbb9..92c5e709 100644 --- a/sorting/count_sort.java +++ b/sorting/count_sort.java @@ -1,3 +1,39 @@ +/* + Count Sort +The Counting Sort algorithm is a non-comparative sorting algorithm that works by counting the occurrences of each distinct element in the input +list. It then uses this information to determine the correct position of each element in the sorted output. + +Here are the steps involved in the Counting Sort algorithm: + +1. Find the range: Determine the range of values in the input list. This range is necessary to create an array with the appropriate size to store the counts. + +2. Count the occurrences: Create a count array of size equal to the range determined in the previous step. Iterate through the input list and count +the occurrences of each element by incrementing the corresponding count in the count array. + +3. Calculate cumulative counts: Modify the count array such that each element represents the cumulative count of elements up to that index. This step +ensures that the count array contains the correct positions for each element in the sorted order. + +4. Generate the sorted output: Create an output array of the same size as the input list. Iterate through the input list and use the count array to +determine the correct position of each element in the output array. Place each element in its corresponding position and decrement the count +in the count array. + +5. Return the sorted list: The output array now contains the elements in sorted order. Return this sorted list as the result of the Counting Sort algorithm. + +Here's an example to illustrate the process: + +Sample Input: [4, 2, 9, 4, 6, 1] + +1. Find the range: The range of values in the input list is from 1 to 9. +2. Count the occurrences: Create the count array [0, 1, 1, 0, 2, 0, 1, 0, 0, 1], where the index represents the element and the value represents the count. +3. Calculate cumulative counts: Modify the count array to [0, 1, 2, 2, 4, 4, 5, 5, 5, 6]. Each element represents the cumulative count of elements up to that index. +4. Generate the sorted output: Create the output array [1, 2, 4, 4, 6, 9]. Iterate through the input list, use the count array to determine the correct +position of each element, place it in the output array, and decrement the count in the count array. +5. Return the sorted list: The sorted list is [1, 2, 4, 4, 6, 9]. + +Counting Sort is an efficient algorithm when the range of values in the input list is relatively small. It has a time complexity of O(n + k), where n is +the number of elements in the input list and k is the range of values. +*/ + class CountingSort { int getMax(int[] a, int n) { diff --git a/sorting/count_sort.js b/sorting/count_sort.js index 3c9b4c40..7298e21f 100644 --- a/sorting/count_sort.js +++ b/sorting/count_sort.js @@ -1,3 +1,39 @@ +/* + Count Sort +The Counting Sort algorithm is a non-comparative sorting algorithm that works by counting the occurrences of each distinct element in the input +list. It then uses this information to determine the correct position of each element in the sorted output. + +Here are the steps involved in the Counting Sort algorithm: + +1. Find the range: Determine the range of values in the input list. This range is necessary to create an array with the appropriate size to store the counts. + +2. Count the occurrences: Create a count array of size equal to the range determined in the previous step. Iterate through the input list and count +the occurrences of each element by incrementing the corresponding count in the count array. + +3. Calculate cumulative counts: Modify the count array such that each element represents the cumulative count of elements up to that index. This step +ensures that the count array contains the correct positions for each element in the sorted order. + +4. Generate the sorted output: Create an output array of the same size as the input list. Iterate through the input list and use the count array to +determine the correct position of each element in the output array. Place each element in its corresponding position and decrement the count +in the count array. + +5. Return the sorted list: The output array now contains the elements in sorted order. Return this sorted list as the result of the Counting Sort algorithm. + +Here's an example to illustrate the process: + +Sample Input: [4, 2, 9, 4, 6, 1] + +1. Find the range: The range of values in the input list is from 1 to 9. +2. Count the occurrences: Create the count array [0, 1, 1, 0, 2, 0, 1, 0, 0, 1], where the index represents the element and the value represents the count. +3. Calculate cumulative counts: Modify the count array to [0, 1, 2, 2, 4, 4, 5, 5, 5, 6]. Each element represents the cumulative count of elements up to that index. +4. Generate the sorted output: Create the output array [1, 2, 4, 4, 6, 9]. Iterate through the input list, use the count array to determine the correct +position of each element, place it in the output array, and decrement the count in the count array. +5. Return the sorted list: The sorted list is [1, 2, 4, 4, 6, 9]. + +Counting Sort is an efficient algorithm when the range of values in the input list is relatively small. It has a time complexity of O(n + k), where n is +the number of elements in the input list and k is the range of values. +*/ + function sort(arr) { var n = arr.length; diff --git a/sorting/count_sort.php b/sorting/count_sort.php deleted file mode 100644 index 97be9fa4..00000000 --- a/sorting/count_sort.php +++ /dev/null @@ -1,62 +0,0 @@ - $max) - $max = $a[$i]; - } - return $max; //maximum element from the array -} - -function countSort(&$a, $n) // function to perform counting sort -{ - $LeftArray = array($n + 1); - $max = getMax($a, $n); - $count = array($max + 1); //create count array with size [max+1] - - for ($i = 0; $i <= $max; ++$i) - { - $count[$i] = 0; // Initialize count array with all zeros - } - - for ($i = 0; $i < $n; $i++) // Store the count of each element - { - $count[$a[$i]]++; - } - - for($i = 1; $i<=$max; $i++) - $count[$i] += $count[$i-1]; //find cumulative frequency - - /* This loop will find the index of each element of the original array in -count array, and - place the elements in output array*/ - for ($i = $n - 1; $i >= 0; $i--) { - $output[$count[$a[$i]] - 1] = $a[$i]; - $count[$a[$i]]--; // decrease count for same numbers -} - - for($i = 0; $i<$n; $i++) { - $a[$i] = $output[$i]; //store the sorted elements into main array - } -} - -/* Function to print the array elements */ -function printArray($a, $n) -{ - for($i = 0; $i < $n; $i++) - { - print_r($a[$i]); - echo " "; - } -} - - $a = array( 9, 28, 22, 5, 29, 14, 37, 28, 9 ); - $n = count($a); - echo "Before sorting array elements are -
"; - printArray($a, $n); - countSort($a,$n); - echo "
After sorting array elements are -
"; - printArray($a, $n); - -?> \ No newline at end of file diff --git a/sorting/count_sort.py b/sorting/count_sort.py index 2fadcac7..3f0f2a36 100644 --- a/sorting/count_sort.py +++ b/sorting/count_sort.py @@ -1,7 +1,38 @@ -# The main function that sort the given string arr[] in -# alphabetical order - - +# Count Sort +# The Counting Sort algorithm is a non-comparative sorting algorithm that works by counting the occurrences of each distinct element in the input +# list. It then uses this information to determine the correct position of each element in the sorted output. + +# Here are the steps involved in the Counting Sort algorithm: + +# 1. Find the range: Determine the range of values in the input list. This range is necessary to create an array with the appropriate size to store the counts. + +# 2. Count the occurrences: Create a count array of size equal to the range determined in the previous step. Iterate through the input list and count +# the occurrences of each element by incrementing the corresponding count in the count array. + +# 3. Calculate cumulative counts: Modify the count array such that each element represents the cumulative count of elements up to that index. This step +# ensures that the count array contains the correct positions for each element in the sorted order. + +# 4. Generate the sorted output: Create an output array of the same size as the input list. Iterate through the input list and use the count array to +# determine the correct position of each element in the output array. Place each element in its corresponding position and decrement the count +# in the count array. + +# 5. Return the sorted list: The output array now contains the elements in sorted order. Return this sorted list as the result of the Counting Sort algorithm. + +# Here's an example to illustrate the process: + +# Sample Input: [4, 2, 9, 4, 6, 1] + +# 1. Find the range: The range of values in the input list is from 1 to 9. +# 2. Count the occurrences: Create the count array [0, 1, 1, 0, 2, 0, 1, 0, 0, 1], where the index represents the element and the value represents the count. +# 3. Calculate cumulative counts: Modify the count array to [0, 1, 2, 2, 4, 4, 5, 5, 5, 6]. Each element represents the cumulative count of elements up to that index. +# 4. Generate the sorted output: Create the output array [1, 2, 4, 4, 6, 9]. Iterate through the input list, use the count array to determine the correct +# position of each element, place it in the output array, and decrement the count in the count array. +# 5. Return the sorted list: The sorted list is [1, 2, 4, 4, 6, 9]. + +# Counting Sort is an efficient algorithm when the range of values in the input list is relatively small. It has a time complexity of O(n + k), where n is +# the number of elements in the input list and k is the range of values. + +# The main function that sort the given string arr[] inalphabetical order def countSort(arr): # The output character array that will have sorted arr From 480351bbcff40d4343aa2aca3c13da2bb3b44aae Mon Sep 17 00:00:00 2001 From: Veena4512 <84694171+Veena4512@users.noreply.github.com> Date: Sat, 3 Jun 2023 21:38:11 +0530 Subject: [PATCH 1273/1894] Given a string s, partition s such that every substring of the partition is a palindrome in Python --- ...of the partition is a palindrome in python | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python diff --git a/Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python b/Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python new file mode 100644 index 00000000..8010fe02 --- /dev/null +++ b/Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python @@ -0,0 +1,33 @@ +"""Name : Veena +# GitHub username : Veena4512 +# Repository name : data-structures-and-algorithms +# Problem : Given a string s, partition s such that every substring of the partition is a palindrome in Python +# Issue Number : #1374 +""" + +"""The minimum_partitions function is a dynamic programming solution that calculates the minimum number of partitions +needed for a given string a, where each partition is a palindrome. It uses two arrays, dp and palindrome, +to store the intermediate results. The function iterates over each position in the string, checking if the substring +is a palindrome and updating the minimum cuts accordingly. Finally, it returns the minimum number of partitions +needed for the entire string. The solution leverages the concept of overlapping problems to efficiently compute +the minimum partitions using dynamic programming. """ + + +# using DP: +def minimum_partitions(a): + if len(a) == 0: + return 0 + dp = [0 for i in range(len(a))] + palindrome = [[False for i in range(len(a))] for j in range(len(a))] + for i in range(len(a)): + cut = i + for j in range(i + 1): + if a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1]): + palindrome[j][i] = True + cut = min(cut, 0 if j == 0 else (dp[j - 1] + 1)) + dp[i] = cut + return dp[len(a) - 1] + + +s = input() +print('Minimum cuts needed for Palindrome Partitioning is', minimum_partitions(s)) From 08e415dfddbe248fd2b180de582ece5997c7e0d3 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sun, 4 Jun 2023 09:13:59 +0530 Subject: [PATCH 1274/1894] Create Cyclic_Sort.java --- sorting/Cyclic_Sort.java | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 sorting/Cyclic_Sort.java diff --git a/sorting/Cyclic_Sort.java b/sorting/Cyclic_Sort.java new file mode 100644 index 00000000..9d378b65 --- /dev/null +++ b/sorting/Cyclic_Sort.java @@ -0,0 +1,36 @@ +/* +What is Cyclic Sort? +The basic idea behind cycle sort is to divide the input array into cycles, where each cycle consists of elements that belong to the same position in the sorted output array. The algorithm then performs a series of swaps to place each element in its correct position within its cycle, until all cycles are complete and the array is sorted. +It is usually used where elements are in the range of (1,n) +*/ + +import java.util.Arrays; + +public class Cyclic_Sort { + public static void main(String[] args) { + int[] arr={3, 5, 2, 1, 4}; //Sample Input + sort(arr); + System.out.println(Arrays.toString(arr)); //Printing the original array + } + + //Cyclic Sort Program + static void sort(int[] arr){ + int i=0; //Variable to iterate over each element of array + while(i Date: Sun, 4 Jun 2023 13:32:07 +0530 Subject: [PATCH 1275/1894] Update Cyclic_Sort.java --- sorting/Cyclic_Sort.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sorting/Cyclic_Sort.java b/sorting/Cyclic_Sort.java index 9d378b65..c42f2e1b 100644 --- a/sorting/Cyclic_Sort.java +++ b/sorting/Cyclic_Sort.java @@ -2,6 +2,11 @@ What is Cyclic Sort? The basic idea behind cycle sort is to divide the input array into cycles, where each cycle consists of elements that belong to the same position in the sorted output array. The algorithm then performs a series of swaps to place each element in its correct position within its cycle, until all cycles are complete and the array is sorted. It is usually used where elements are in the range of (1,n) + +Time Complexity Analysis: + Worst Case: O(n2) + Best Case: O(n2) +Auxiliary Space: O(1) */ import java.util.Arrays; From b6f24677c69ce4fe53dff94ffa028cb731ef444f Mon Sep 17 00:00:00 2001 From: Veena4512 <84694171+Veena4512@users.noreply.github.com> Date: Sun, 4 Jun 2023 14:59:42 +0530 Subject: [PATCH 1276/1894] palindrome partitions in python --- ...tring_of_the_partition_is_a_palindrome.py} | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) rename Strings/{Given a string s, partition s such that every substring of the partition is a palindrome in python => Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py} (56%) diff --git a/Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python b/Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py similarity index 56% rename from Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python rename to Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py index 8010fe02..c76c4cb9 100644 --- a/Strings/Given a string s, partition s such that every substring of the partition is a palindrome in python +++ b/Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py @@ -15,19 +15,36 @@ # using DP: def minimum_partitions(a): + # Check if the input list is empty if len(a) == 0: return 0 + + # Initialize an array to store the minimum number of partitions dp = [0 for i in range(len(a))] + + # Initialize a 2D array to store whether a substring is a palindrome or not palindrome = [[False for i in range(len(a))] for j in range(len(a))] + + # Iterate over the input list for i in range(len(a)): - cut = i + cut = i # Initialize the minimum number of partitions to the current index + + # Iterate over the substring from 0 to the current index for j in range(i + 1): + # Check if the characters at indices i and j are equal + # and the substring between i and j is a palindrome if a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1]): - palindrome[j][i] = True - cut = min(cut, 0 if j == 0 else (dp[j - 1] + 1)) - dp[i] = cut - return dp[len(a) - 1] + palindrome[j][i] = True # Mark the substring as a palindrome + cut = min(cut, 0 if j == 0 else (dp[j - 1] + 1)) # Update the minimum number of partitions + dp[i] = cut # Store the minimum number of partitions for the current index + return dp[len(a) - 1] s = input() print('Minimum cuts needed for Palindrome Partitioning is', minimum_partitions(s)) + +# Time complexity:O(n^2) +# Space complexity:The space complexity of the code is O(n^2) due to the usage of the 2D array +# palindrome, which dominates the space requirement, while the array dp contributes +# O(n) to the overall space complexity. + From ee730b0a4d0580737d166aba05112ff221f6683d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 4 Jun 2023 22:01:18 +0530 Subject: [PATCH 1277/1894] rename file --- .../{find_first_duplicate_value.py => first_duplicate_value.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/{find_first_duplicate_value.py => first_duplicate_value.py} (100%) diff --git a/Arrays/find_first_duplicate_value.py b/Arrays/first_duplicate_value.py similarity index 100% rename from Arrays/find_first_duplicate_value.py rename to Arrays/first_duplicate_value.py From 2b83469d957000ce87afa02ce9ff96c21e991b8b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 4 Jun 2023 22:01:25 +0530 Subject: [PATCH 1278/1894] add num ways to make change --- .../num_ways_to_make_change.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_make_change.go diff --git a/Dynamic Programming/num_ways_to_make_change.go b/Dynamic Programming/num_ways_to_make_change.go new file mode 100644 index 00000000..b6aecf81 --- /dev/null +++ b/Dynamic Programming/num_ways_to_make_change.go @@ -0,0 +1,25 @@ +package main + +func NumberOfWaysToMakeChange(n int, denoms []int) int { + // Create an array to store the number of ways to make change for each amount from 0 to n. + ways := make([]int, n+1) + + // Initialize the base case: There is one way to make change for amount 0 (using no coins). + ways[0] = 1 + + // Iterate over each denomination. + for _, denom := range denoms { + // For each denomination, iterate over each amount from 1 to n. + for amount := 1; amount < n+1; amount++ { + // Check if the denomination can be used to make change for the current amount. + if denom <= amount { + // Add the number of ways to make change for the current amount + // by considering the current denomination. + ways[amount] += ways[amount-denom] + } + } + } + + // Return the number of ways to make change for the target amount n. + return ways[n] +} From d7812345544652d7040cd4f457eedf3bf633d400 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 4 Jun 2023 22:01:41 +0530 Subject: [PATCH 1279/1894] add question and sample io --- Dynamic Programming/num_ways_to_make_change.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Dynamic Programming/num_ways_to_make_change.go b/Dynamic Programming/num_ways_to_make_change.go index b6aecf81..384d18d3 100644 --- a/Dynamic Programming/num_ways_to_make_change.go +++ b/Dynamic Programming/num_ways_to_make_change.go @@ -1,3 +1,11 @@ +/* + Given an array of distinct positive integers representing coin denominations and a single non-negative integer n + representing a target amount of money, write a function that returns the number of ways to make change for + that target amount using the given coin denominations. + + Sample Input: n = 6 denominations : [1, 5] + Output: 2 (1 * 1 + 1 * 5 and 6 * 1) +*/ package main func NumberOfWaysToMakeChange(n int, denoms []int) int { From 27cad400f0e137567706a780b24ca49337aff79f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 4 Jun 2023 22:02:42 +0530 Subject: [PATCH 1280/1894] add explanation --- .../num_ways_to_make_change.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Dynamic Programming/num_ways_to_make_change.go b/Dynamic Programming/num_ways_to_make_change.go index 384d18d3..4cdd63c4 100644 --- a/Dynamic Programming/num_ways_to_make_change.go +++ b/Dynamic Programming/num_ways_to_make_change.go @@ -5,6 +5,37 @@ Sample Input: n = 6 denominations : [1, 5] Output: 2 (1 * 1 + 1 * 5 and 6 * 1) + + Explanation: + + The given code snippet is implementing the "NumberOfWaysToMakeChange" algorithm in Go. + This algorithm calculates the number of ways to make change for a given amount using a set of denominations. + + Here's how the algorithm works: + + 1. The function "NumberOfWaysToMakeChange" takes two parameters: "n" (the target amount to make change for) and "denoms" + (an array of coin denominations). + + 2. It initializes an array called "ways" of size "n+1" to keep track of the number of ways to make change for each amount + from 0 to "n". The initial value of "ways[0]" is set to 1, representing the base case where there is one way to make + change for zero. + + 3. The algorithm iterates over each denomination in the "denoms" array using a for-each loop. + + 4. For each denomination, it further iterates from 1 to "n+1" to calculate the number of ways to make change for each + amount. + + 5. Inside the inner loop, it checks if the current denomination is less than or equal to the current amount. If so, + it means that the current denomination can contribute to the change for the current amount. + + 6. It then updates the "ways[amount]" value by adding the number of ways to make change for the current amount minus + the current denomination. This is done to accumulate all the possible ways to make change using the current denomination. + + 7. After completing the nested loops, the algorithm returns the value stored in "ways[n]", which represents the total + number of ways to make change for the target amount "n" using the given denominations. + + In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given + amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. */ package main From f5a1c867de55dc75446cbc23e23c0d4c5cd38e07 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 4 Jun 2023 22:03:49 +0530 Subject: [PATCH 1281/1894] add time and space complexity --- Dynamic Programming/num_ways_to_make_change.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Dynamic Programming/num_ways_to_make_change.go b/Dynamic Programming/num_ways_to_make_change.go index 4cdd63c4..b837a678 100644 --- a/Dynamic Programming/num_ways_to_make_change.go +++ b/Dynamic Programming/num_ways_to_make_change.go @@ -36,6 +36,10 @@ In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. + + Time complexity : O(nd) + Space complexity : O(n) where n is the target amount and d is the number of coin denominations + */ package main From 0fb77f8320384b4b3187d765266527262d96b809 Mon Sep 17 00:00:00 2001 From: Kiran Date: Mon, 5 Jun 2023 07:35:52 +0530 Subject: [PATCH 1282/1894] Changes made --- sorting/radix_sort.cs | 139 ------------------------------------------ sorting/radix_sort.go | 99 ++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 139 deletions(-) delete mode 100644 sorting/radix_sort.cs create mode 100644 sorting/radix_sort.go diff --git a/sorting/radix_sort.cs b/sorting/radix_sort.cs deleted file mode 100644 index cf0a1894..00000000 --- a/sorting/radix_sort.cs +++ /dev/null @@ -1,139 +0,0 @@ -/* - Radix Sort -1. Identify the maximum number: Find the maximum number in the given list. This is necessary to determine the number of digits we need to consider -during the sorting process. - -2. Perform counting sort for each digit position: Starting from the least significant digit (rightmost digit), perform the following steps for each -digit position, moving towards the most significant digit (leftmost digit): -a. Create a count array: Create a count array of size 10 (to represent digits 0-9) and initialize all elements to 0. This count array will be used -to store the frequency of each digit at the current position. -b. Count the frequencies: Iterate through the list of numbers and count the frequency of each digit at the current position. For example, if the -current digit position is the units place, count the frequency of each digit from 0 to 9. -c. Update the count array: Modify the count array such that each element represents the cumulative count of digits up to that index. This step -ensures that the count array contains the correct positions for each digit in the sorted order. -d. Distribute the numbers: Iterate through the list of numbers again, and for each number, find its digit at the current position. Use the count -array to determine the correct position of the number in the output array and place it there. After placing the number, decrement the count for -that digit in the count array. -e. Collect the numbers: After distributing all the numbers, collect them back into the original array. The array will now be partially sorted -based on the current digit position. - -3. Repeat the counting sort for the next digit position: After collecting the numbers based on the least significant digit, move to the next digit -position (towards the left) and repeat steps 2a to 2e for that digit. Continue this process until all the digits have been processed, from the least -significant digit to the most significant digit. - -4. Final sorted list: After completing the counting sort process for all digit positions, you will have a fully sorted list of numbers. - -Here's an example to illustrate the process: - -Sample Input: [170, 45, 75, 90, 802, 24, 2, 66] -Maximum number: 802 - -# 1. First iteration (Least significant digit - rightmost digit): - # Create the count array: [0, 2, 1, 1, 0, 1, 0, 0, 0, 1] - # Update the count array: [0, 2, 3, 4, 4, 5, 5, 5, 5, 6] - # Distribute the numbers: [802, 2, 24, 45, 75, 170, 90, 66] - # Collect the numbers: [802, 2, 24, 45, 75, 170, 90, 66] - -# 2. Second iteration (Next least significant digit): - # Create the count array: [1, 2, 1, 1, 1, 1, 0, 0, 0, 1] - # Update the count array: [1, 3, 4, 5, 6, 7, 7, 7, 7, 8] - # Distribute the numbers: [802, 2, 24, 45, 66, 75, 90, 170] - # Collect the numbers: [802, 2, 24, 45, 66, 75, 90, 170] - -# 3. Third iteration (Most significant digit): - # Create the count array: [1, 1, 1, 1, 2, 2, 1, 0, 0, 0] - # Update the count array: [1, 2, 3, 4, 6, 8, 9, 9, 9, 9] - # Distribute the numbers: [2, 24, 45, 66, 75, 90, 170, 802] - # Collect the numbers: [2, 24, 45, 66, 75, 90, 170, 802] - -# The final sorted list is [2, 24, 45, 66, 75, 90, 170, 802]. - -# Radix sort using counting sort works by sorting the numbers digit by digit, from the least significant digit to the most significant digit. -# The counting sort process distributes and collects the numbers based on each digit position, ensuring that the numbers are correctly ordered at -# each iteration. By repeating this process for each digit, the algorithm achieves a fully sorted list without the need for explicit element comparisons. - -*/ - -// C# implementation of Radix Sort -using System; - -class RadixSort { - public static int getMax(int[] arr, int n) - { - int mx = arr[0]; - for (int i = 1; i < n; i++) - if (arr[i] > mx) - mx = arr[i]; - return mx; - } - - // A function to do counting sort of arr[] according to - // the digit represented by exp. - public static void countSort(int[] arr, int n, int exp) - { - int[] output = new int[n]; // output array - int i; - int[] count = new int[10]; - - // initializing all elements of count to 0 - for (i = 0; i < 10; i++) - count[i] = 0; - - // Store count of occurrences in count[] - for (i = 0; i < n; i++) - count[(arr[i] / exp) % 10]++; - - // Change count[i] so that count[i] now contains - // actual - // position of this digit in output[] - for (i = 1; i < 10; i++) - count[i] += count[i - 1]; - - // Build the output array - for (i = n - 1; i >= 0; i--) { - output[count[(arr[i] / exp) % 10] - 1] = arr[i]; - count[(arr[i] / exp) % 10]--; - } - - // Copy the output array to arr[], so that arr[] now - // contains sorted numbers according to current - // digit - for (i = 0; i < n; i++) - arr[i] = output[i]; - } - - // The main function to that sorts arr[] of size n using - // Radix Sort - public static void radixsort(int[] arr, int n) - { - // Find the maximum number to know number of digits - int m = getMax(arr, n); - - // Do counting sort for every digit. Note that - // instead of passing digit number, exp is passed. - // exp is 10^i where i is current digit number - for (int exp = 1; m / exp > 0; exp *= 10) - countSort(arr, n, exp); - } - - // A utility function to print an array - public static void print(int[] arr, int n) - { - for (int i = 0; i < n; i++) - Console.Write(arr[i] + " "); - } - - // Driver Code - public static void Main() - { - int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; - int n = arr.Length; - - // Function Call - radixsort(arr, n); - print(arr, n); - } -} - -// Time Compexity -> O((n+k)*d) -// Space Complexity -> O(n+k) \ No newline at end of file diff --git a/sorting/radix_sort.go b/sorting/radix_sort.go new file mode 100644 index 00000000..dc436f0b --- /dev/null +++ b/sorting/radix_sort.go @@ -0,0 +1,99 @@ +/* +Radix sort is a sorting Algorithm that sorts elements by grouping them based on their individual digits or by the position of their digits. +It is a linear time sorting Algorithm that has a time complexity of O(nk). + +Using the Least Significant Bit +In this method, we will write a go language program to implement the radix sort by using the least significant bit. LSD sorts the elements +from right to left by comparing their individual digits. + +Algorithm +Step 1 − First, we need to import the fmt package. Then create a function named radixSortMSD() to sort the array. + +Step 2 − Inside the function create a new array. Use the for loop to iterate over the array and store the maximum element of the array in a variable. + +Step 3 − Now, initialize a count array to keep track of the number of elements that have a particular digit. + +Step 4 − Traverse the array and increment the count for the corresponding digit for each element. + +Step 5 − Modify the count array to store the actual position of each element in the Output array. Copy the elements from the input array to the +Output array in the order specified by the count array. + +Step 6 − Update the input array to the sorted Output array and return the sorted array. + +Step 7 − Start the main() function. Inside the main() initialize an array and store value to it. further, call the radixSort() function and pass +the array as an argument to the function. + +Step 8 − Store the result obtained by the function in a variable and print It on the screen. + +The code implements Radix Sort using the LSD (Least Significant Digit) approach to sort an array of integers. It iterates through each digit from +the least significant to the most significant, performing counting sort for each digit. Counting sort is used to determine the correct positions +of elements based on the current digit. The sorted elements are then copied back to the original array. This process is repeated until all digits +have been processed, resulting in a sorted array. +*/ + +package main + +import "fmt" + +// radixSortLSD performs Radix Sort using the LSD (Least Significant Digit) algorithm +func radixSortLSD(arr []int) []int { + // Find the maximum element in the array + max := arr[0] + for i := 1; i < len(arr); i++ { + if arr[i] > max { + max = arr[i] + } + } + + exp := 1 + // Perform counting sort for each digit from LSD to MSD + for max/exp > 0 { + // Create a count array to store the frequency of each digit (0-9) + count := make([]int, 10) + + // Count the frequency of each digit at the current exponent + for i := 0; i < len(arr); i++ { + count[(arr[i]/exp)%10]++ + } + + // Calculate the cumulative sum of count array to determine the correct positions of each digit + for i := 1; i < 10; i++ { + count[i] += count[i-1] + } + + // Create an output array to store the sorted elements based on the current digit + output := make([]int, len(arr)) + + // Build the output array by placing each element in its correct position based on the current digit + for i := len(arr) - 1; i >= 0; i-- { + output[count[(arr[i]/exp)%10]-1] = arr[i] + count[(arr[i]/exp)%10]-- + } + + // Copy the sorted elements from the output array back to the original array + for i := 0; i < len(arr); i++ { + arr[i] = output[i] + } + + // Move to the next digit by multiplying the exponent by 10 + exp *= 10 + } + + // Return the sorted array + return arr +} + +func main() { + // Test the radixSortLSD function + arr := []int{15, 31, 42, 20, 9} + fmt.Println("The unsorted array is:", arr) + result := radixSortLSD(arr) + fmt.Println("The sorted array is:", result) +} + +// Output +// The unsorted array is: [15 31 42 20 9] +// The sorted array is: [9 15 20 31 42] + +// Time Compexity -> O((n+k)*d) +// Space Complexity -> O(n+k) \ No newline at end of file From f05ad1d77631ce371d19b4e3111f08bc91b98b7b Mon Sep 17 00:00:00 2001 From: Kiran Date: Mon, 5 Jun 2023 10:32:36 +0530 Subject: [PATCH 1283/1894] Set Matrix 0 code added along with explaination in Go and cpp language --- 2D Arrays (Matrix)/set_matrix_0.cpp | 89 +++++++++++++++++++++++++++++ 2D Arrays (Matrix)/set_matrix_0.go | 87 ++++++++++++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 2D Arrays (Matrix)/set_matrix_0.cpp create mode 100644 2D Arrays (Matrix)/set_matrix_0.go diff --git a/2D Arrays (Matrix)/set_matrix_0.cpp b/2D Arrays (Matrix)/set_matrix_0.cpp new file mode 100644 index 00000000..edb6f992 --- /dev/null +++ b/2D Arrays (Matrix)/set_matrix_0.cpp @@ -0,0 +1,89 @@ +/* +Problem: +You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the +corresponding row and column to zero as well. + +Solution: +To solve this problem, you can follow the steps below: + +1. Create two sets, rows and columns, to keep track of the rows and columns that need to be set to zero. + +2. Iterate through the matrix row by row, and for each element, if it is zero, add its row index to the rows set and its column index to the columns set. + +3. Iterate through the matrix again, and for each element, check if its row index or column index exists in the respective sets (rows or columns). +If either index exists, set the element to zero. + +4. Finally, iterate through the matrix one more time, and for each row or column index in the rows or columns sets, set all the elements in that +row or column to zero. + +5. Return the modified matrix. + +Complexity: +Let's assume the matrix has dimensions MxN. + +Step 2: In this step, we iterate through the matrix once, which takes O(M*N) time. + +Step 3: In this step, we again iterate through the matrix once, which takes O(M*N) time. + +Step 4: In this step, we iterate through the rows and columns sets, which contain at most M+N elements. Therefore, this step takes O(M+N) time. + +Overall, the time complexity of the solution is O(MN + M + N), which can be simplified to O(MN). The space complexity is O(M+N) since we are +using two sets to store the rows and columns that need to be set to zero. +*/ + +#include +#include +#include + +using namespace std; + +void setZeroes(vector>& matrix) { + unordered_set rows; + unordered_set columns; + + // Step 1: Find the rows and columns that need to be set to zero + for (int i = 0; i < matrix.size(); i++) { + for (int j = 0; j < matrix[0].size(); j++) { + if (matrix[i][j] == 0) { + rows.insert(i); + columns.insert(j); + } + } + } + + // Step 2: Set the corresponding rows and columns to zero + for (int i = 0; i < matrix.size(); i++) { + for (int j = 0; j < matrix[0].size(); j++) { + if (rows.count(i) || columns.count(j)) { + matrix[i][j] = 0; + } + } + } +} + +void printMatrix(const vector>& matrix) { + for (const auto& row : matrix) { + for (int num : row) { + cout << num << " "; + } + cout << endl; + } +} + +int main() { + vector> matrix = { + {1, 1, 1}, + {1, 0, 1}, + {1, 1, 1} + }; + + cout << "Original Matrix:" << endl; + printMatrix(matrix); + + setZeroes(matrix); + + cout << "Modified Matrix:" << endl; + printMatrix(matrix); + + return 0; +} diff --git a/2D Arrays (Matrix)/set_matrix_0.go b/2D Arrays (Matrix)/set_matrix_0.go new file mode 100644 index 00000000..a7f82c4f --- /dev/null +++ b/2D Arrays (Matrix)/set_matrix_0.go @@ -0,0 +1,87 @@ +/* +Problem: +You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the +corresponding row and column to zero as well. + +Solution: +To solve this problem, you can follow the steps below: + +1. Create two sets, rows and columns, to keep track of the rows and columns that need to be set to zero. + +2. Iterate through the matrix row by row, and for each element, if it is zero, add its row index to the rows set and its column index to the columns set. + +3. Iterate through the matrix again, and for each element, check if its row index or column index exists in the respective sets (rows or columns). +If either index exists, set the element to zero. + +4. Finally, iterate through the matrix one more time, and for each row or column index in the rows or columns sets, set all the elements in that +row or column to zero. + +5. Return the modified matrix. + +Complexity: +Let's assume the matrix has dimensions MxN. + +Step 2: In this step, we iterate through the matrix once, which takes O(M*N) time. + +Step 3: In this step, we again iterate through the matrix once, which takes O(M*N) time. + +Step 4: In this step, we iterate through the rows and columns sets, which contain at most M+N elements. Therefore, this step takes O(M+N) time. + +Overall, the time complexity of the solution is O(MN + M + N), which can be simplified to O(MN). The space complexity is O(M+N) since we are +using two sets to store the rows and columns that need to be set to zero. +*/ + +package main + +import ( + "fmt" +) + +func setZeroes(matrix [][]int) { + rows := make(map[int]bool) + columns := make(map[int]bool) + + // Step 1: Find the rows and columns that need to be set to zero + for i := 0; i < len(matrix); i++ { + for j := 0; j < len(matrix[0]); j++ { + if matrix[i][j] == 0 { + rows[i] = true + columns[j] = true + } + } + } + + // Step 2: Set the corresponding rows and columns to zero + for i := 0; i < len(matrix); i++ { + for j := 0; j < len(matrix[0]); j++ { + if rows[i] || columns[j] { + matrix[i][j] = 0 + } + } + } +} + +func main() { + matrix := [][]int{ + {1, 1, 1}, + {1, 0, 1}, + {1, 1, 1}, + } + + fmt.Println("Original Matrix:") + printMatrix(matrix) + + setZeroes(matrix) + + fmt.Println("Modified Matrix:") + printMatrix(matrix) +} + +func printMatrix(matrix [][]int) { + for i := 0; i < len(matrix); i++ { + for j := 0; j < len(matrix[0]); j++ { + fmt.Print(matrix[i][j], " ") + } + fmt.Println() + } +} From 6ae92f3add30616b3523c7cc1666e6ddf551bbbf Mon Sep 17 00:00:00 2001 From: Diwakar Singh <76618190+thakurdiwakar@users.noreply.github.com> Date: Mon, 5 Jun 2023 22:59:53 +0530 Subject: [PATCH 1284/1894] Added Bloom Filter Algorithm --- Bit Manipulation/bloom_filter.cpp | 130 ++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 Bit Manipulation/bloom_filter.cpp diff --git a/Bit Manipulation/bloom_filter.cpp b/Bit Manipulation/bloom_filter.cpp new file mode 100644 index 00000000..6a14821b --- /dev/null +++ b/Bit Manipulation/bloom_filter.cpp @@ -0,0 +1,130 @@ +// Approach and Explanation + +// 1. **Hash Functions**: The Bloom filter uses four hash functions (`h1`, `h2`, `h3`, `h4`) to map input strings to positions in the bit array. These hash functions generate different indexes based on the input string and the size of the bit array. + +// 2. **Bit Array**: The Bloom filter uses a `std::bitset<1000000>` called `bitarray` to represent the filter. It is a fixed-size bit array where each bit represents a position that can be set (1) or unset (0). + +// 3. **Lookup Operation**: The `lookup` function takes a reference to the `bitarray` and a string `s` as input. It calculates the hash values for `s` using the four hash functions and checks if the corresponding positions in the `bitarray` are all set (1). If all positions are set, it returns `true`, indicating that the element is possibly present in the filter. Otherwise, it returns `false`. + +// 4. **Insert Operation**: The `insert` function takes a reference to the `bitarray` and a string `s` as input. It first checks if the element is already present in the filter by calling the `lookup` function. If the element is already present, it prints a message indicating that it is probably already present. Otherwise, it calculates the hash values for `s` using the four hash functions and sets the corresponding positions in the `bitarray` to 1, indicating the insertion of the element. + +// 5. **Main Function**: In the `main` function, a `bitarray` of size 1000000 is created. A set of strings (`sarray`) is defined, representing the elements to be added to the filter. For each string `s` in `sarray`, it checks if `s` is already present in the filter using the `lookup` function. If it is present, it prints a message indicating that it is already present. Otherwise, it inserts `s` into the filter using the `insert` function. + +// The Bloom filter provides a probabilistic way to test whether an element is possibly in a set. It may return false positives, indicating that an element is possibly in the set when it's not, but it will never give false negatives. The accuracy of the filter depends on the size of the bit array, the number of hash functions used, and the number of elements inserted. + +// In this implementation, the size of the bit array is fixed at 1000000, and four hash functions are used. The elements are inserted by setting the corresponding positions in the bit array to 1. The `lookup` function checks if all the positions for an element are set (1), indicating its possible presence in the filter. + + + + +// Time Complexity-> O(1) on average, O(n) in the worst case +// Space Complexity-> O(n) + + + + + + +#include +#include +#include +#define ll long long + +// hash 1 +int h1(std::string s, int arrSize) +{ + ll int hash = 0; + for (int i = 0; i < s.size(); i++) + { + hash = (hash + ((int)s[i])); + hash = hash % arrSize; + } + return hash; +} + +// hash 2 +int h2(std::string s, int arrSize) +{ + ll int hash = 1; + for (int i = 0; i < s.size(); i++) + { + hash = hash + pow(19, i) * s[i]; + hash = hash % arrSize; + } + return hash % arrSize; +} + +// hash 3 +int h3(std::string s, int arrSize) +{ + ll int hash = 7; + for (int i = 0; i < s.size(); i++) + { + hash = (hash * 31 + s[i]) % arrSize; + } + return hash % arrSize; +} + +// hash 4 +int h4(std::string s, int arrSize) +{ + ll int hash = 3; + int p = 7; + for (int i = 0; i < s.size(); i++) + { + hash += hash * 7 + s[i] * pow(p, i); + hash = hash % arrSize; + } + return hash; +} + +// lookup operation +bool lookup(std::bitset<1000000> &bitarray, std::string s) +{ + int a = h1(s, bitarray.size()); + int b = h2(s, bitarray.size()); + int c = h3(s, bitarray.size()); + int d = h4(s, bitarray.size()); + + return bitarray[a] && bitarray[b] && bitarray[c] && bitarray[d]; +} + +// insert operation +void insert(std::bitset<1000000> &bitarray, std::string s) +{ + // check if the element is already present or not + if (lookup(bitarray, s)) + { + std::cout << s << " is probably already present" << std::endl; + } + else + { + int a = h1(s, bitarray.size()); + int b = h2(s, bitarray.size()); + int c = h3(s, bitarray.size()); + int d = h4(s, bitarray.size()); + + bitarray[a] = true; + bitarray[b] = true; + bitarray[c] = true; + bitarray[d] = true; + + std::cout << s << " inserted" << std::endl; + } +} + +int main() { + std::bitset<1000000> bitarray; + std::string sarray[] = { "apple", "banana", "cherry", "orange", "grape", "kiwi" }; + + for (const auto& s : sarray) { + if (lookup(bitarray, s)) { + std::cout << s << " is already present" << std::endl; + } else { + insert(bitarray, s); + } + } + + return 0; +} + From 710e91ea824ed036bb9d74641609168a7e17b4bb Mon Sep 17 00:00:00 2001 From: Diwakar Singh <76618190+thakurdiwakar@users.noreply.github.com> Date: Mon, 5 Jun 2023 23:00:38 +0530 Subject: [PATCH 1285/1894] Added Bloom Filter in Python --- Bit Manipulation/bloom_filter.py | 74 ++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Bit Manipulation/bloom_filter.py diff --git a/Bit Manipulation/bloom_filter.py b/Bit Manipulation/bloom_filter.py new file mode 100644 index 00000000..dee5166d --- /dev/null +++ b/Bit Manipulation/bloom_filter.py @@ -0,0 +1,74 @@ + + +# explanation of the approach: + +# 1. The `BloomFilter` class is defined to encapsulate the functionality of the Bloom filter. It takes two parameters during initialization: `capacity` (expected number of elements to be added to the filter) and `false_positive_rate` (desired false positive rate). + +# 2. The `calculate_size()` method is used to calculate the size of the bit array based on the capacity and false positive rate. It uses the formula `- (capacity * log(false_positive_rate)) / (log(2) ** 2)` to determine the size. + +# 3. The `calculate_num_hashes()` method calculates the number of hash functions to be used based on the size of the bit array and the capacity. It uses the formula `(size / capacity) * log(2)` to determine the number of hashes. + +# 4. The `bit_array` attribute is created using the `bitarray` library and initialized with the calculated size. All bits in the array are initially set to 0. + +# 5. The `add()` method is used to add an item to the Bloom filter. It iterates over the range of `num_hashes` and calculates the index for each hash function using the `mmh3.hash()` function. The index is obtained by taking the modulo of the hash value with the size of the bit array. The corresponding bit in the bit array is set to 1. + +# 6. The `contains()` method is used to check if an item is present in the Bloom filter. It follows a similar process as the `add()` method, iterating over the range of `num_hashes` and calculating the index for each hash function. If any of the corresponding bits in the bit array are 0, it indicates that the item is not present and False is returned. If all the bits are 1, it means the item might be present (false positive) and True is returned. + +# 7. In the example usage, a `BloomFilter` object is created with a capacity of 1000 and a false positive rate of 0.01. + +# 8. Three items ("apple", "banana", "cherry") are added to the Bloom filter using the `add()` method. + +# 9. The `contains()` method is used to check if certain items ("apple", "banana", "cherry", "orange") are present in the Bloom filter. The result is printed for each item. + +# The Bloom filter uses the MurmurHash3 hash function (`mmh3.hash()`) to generate hash values for the items. The number of hash functions and the size of the bit array are calculated based on the desired false positive rate and capacity. The Bloom filter provides a probabilistic check for membership, with a possibility of false positives but no false negatives. + + + +import math +import mmh3 +from bitarray import bitarray + + +class BloomFilter: + def __init__(self, capacity, false_positive_rate): + self.capacity = capacity + self.false_positive_rate = false_positive_rate + self.size = self.calculate_size() + self.num_hashes = self.calculate_num_hashes() + self.bit_array = bitarray(self.size) + self.bit_array.setall(0) + + def calculate_size(self): + size = - (self.capacity * math.log(self.false_positive_rate)) / (math.log(2) ** 2) + return int(size) + + def calculate_num_hashes(self): + num_hashes = (self.size / self.capacity) * math.log(2) + return int(num_hashes) + + def add(self, item): + for seed in range(self.num_hashes): + index = mmh3.hash(item, seed) % self.size + self.bit_array[index] = 1 + + def contains(self, item): + for seed in range(self.num_hashes): + index = mmh3.hash(item, seed) % self.size + if self.bit_array[index] == 0: + return False + return True + + +# Example usage +bloom_filter = BloomFilter(capacity=1000, false_positive_rate=0.01) + +# Add items to the filter +bloom_filter.add("apple") +bloom_filter.add("banana") +bloom_filter.add("cherry") + +# Check if items are in the filter +print(bloom_filter.contains("apple")) +print(bloom_filter.contains("banana")) +print(bloom_filter.contains("cherry")) +print(bloom_filter.contains("orange")) From 81b15e5c23b2c16b845a487416974d2c59bfb86e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:07:19 +0530 Subject: [PATCH 1286/1894] add num ways to make change in c++ --- .../num_ways_to_make_change.cpp | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_make_change.cpp diff --git a/Dynamic Programming/num_ways_to_make_change.cpp b/Dynamic Programming/num_ways_to_make_change.cpp new file mode 100644 index 00000000..4d03a4a2 --- /dev/null +++ b/Dynamic Programming/num_ways_to_make_change.cpp @@ -0,0 +1,68 @@ +/* + Given an array of distinct positive integers representing coin denominations and a single non-negative integer n + representing a target amount of money, write a function that returns the number of ways to make change for + that target amount using the given coin denominations. + + Sample Input: n = 6 denominations : [1, 5] + Output: 2 (1 * 1 + 1 * 5 and 6 * 1) + + Explanation: + + The given code snippet is implementing the "NumberOfWaysToMakeChange" algorithm in Go. + This algorithm calculates the number of ways to make change for a given amount using a set of denominations. + + Here's how the algorithm works: + + 1. The function "NumberOfWaysToMakeChange" takes two parameters: "n" (the target amount to make change for) and "denoms" + (an array of coin denominations). + + 2. It initializes an array called "ways" of size "n+1" to keep track of the number of ways to make change for each amount + from 0 to "n". The initial value of "ways[0]" is set to 1, representing the base case where there is one way to make + change for zero. + + 3. The algorithm iterates over each denomination in the "denoms" array using a for-each loop. + + 4. For each denomination, it further iterates from 1 to "n+1" to calculate the number of ways to make change for each + amount. + + 5. Inside the inner loop, it checks if the current denomination is less than or equal to the current amount. If so, + it means that the current denomination can contribute to the change for the current amount. + + 6. It then updates the "ways[amount]" value by adding the number of ways to make change for the current amount minus + the current denomination. This is done to accumulate all the possible ways to make change using the current denomination. + + 7. After completing the nested loops, the algorithm returns the value stored in "ways[n]", which represents the total + number of ways to make change for the target amount "n" using the given denominations. + + In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given + amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. + + Time complexity : O(nd) + Space complexity : O(n) where n is the target amount and d is the number of coin denominations + +*/ +#include + +int NumberOfWaysToMakeChange(int n, const std::vector& denoms) { + // Create an array to store the number of ways to make change for each amount from 0 to n. + std::vector ways(n + 1, 0); + + // Initialize the base case: There is one way to make change for amount 0 (using no coins). + ways[0] = 1; + + // Iterate over each denomination. + for (int denom : denoms) { + // For each denomination, iterate over each amount from 1 to n. + for (int amount = 1; amount < n + 1; amount++) { + // Check if the denomination can be used to make change for the current amount. + if (denom <= amount) { + // Add the number of ways to make change for the current amount + // by considering the current denomination. + ways[amount] += ways[amount - denom]; + } + } + } + + // Return the number of ways to make change for the target amount n. + return ways[n]; +} From d64210ca57e8314d074e36e0141b0bd32895c06e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:08:46 +0530 Subject: [PATCH 1287/1894] add num ways fo make change in java --- .../num_ways_to_make_change.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_make_change.java diff --git a/Dynamic Programming/num_ways_to_make_change.java b/Dynamic Programming/num_ways_to_make_change.java new file mode 100644 index 00000000..6efdb50b --- /dev/null +++ b/Dynamic Programming/num_ways_to_make_change.java @@ -0,0 +1,79 @@ +/* + Given an array of distinct positive integers representing coin denominations and a single non-negative integer n + representing a target amount of money, write a function that returns the number of ways to make change for + that target amount using the given coin denominations. + + Sample Input: n = 6 denominations : [1, 5] + Output: 2 (1 * 1 + 1 * 5 and 6 * 1) + + Explanation: + + The given code snippet is implementing the "NumberOfWaysToMakeChange" algorithm in Go. + This algorithm calculates the number of ways to make change for a given amount using a set of denominations. + + Here's how the algorithm works: + + 1. The function "NumberOfWaysToMakeChange" takes two parameters: "n" (the target amount to make change for) and "denoms" + (an array of coin denominations). + + 2. It initializes an array called "ways" of size "n+1" to keep track of the number of ways to make change for each amount + from 0 to "n". The initial value of "ways[0]" is set to 1, representing the base case where there is one way to make + change for zero. + + 3. The algorithm iterates over each denomination in the "denoms" array using a for-each loop. + + 4. For each denomination, it further iterates from 1 to "n+1" to calculate the number of ways to make change for each + amount. + + 5. Inside the inner loop, it checks if the current denomination is less than or equal to the current amount. If so, + it means that the current denomination can contribute to the change for the current amount. + + 6. It then updates the "ways[amount]" value by adding the number of ways to make change for the current amount minus + the current denomination. This is done to accumulate all the possible ways to make change using the current denomination. + + 7. After completing the nested loops, the algorithm returns the value stored in "ways[n]", which represents the total + number of ways to make change for the target amount "n" using the given denominations. + + In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given + amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. + + Time complexity : O(nd) + Space complexity : O(n) where n is the target amount and d is the number of coin denominations + +*/ +import java.util.Arrays; + +public class CoinChange { + + public static int numberOfWaysToMakeChange(int n, int[] denoms) { + // Create an array to store the number of ways to make change for each amount from 0 to n. + int[] ways = new int[n + 1]; + + // Initialize the base case: There is one way to make change for amount 0 (using no coins). + ways[0] = 1; + + // Iterate over each denomination. + for (int denom : denoms) { + // For each denomination, iterate over each amount from 1 to n. + for (int amount = 1; amount < n + 1; amount++) { + // Check if the denomination can be used to make change for the current amount. + if (denom <= amount) { + // Add the number of ways to make change for the current amount + // by considering the current denomination. + ways[amount] += ways[amount - denom]; + } + } + } + + // Return the number of ways to make change for the target amount n. + return ways[n]; + } + + public static void main(String[] args) { + int n = 10; + int[] denoms = {1, 2, 5}; + + int numberOfWays = numberOfWaysToMakeChange(n, denoms); + System.out.println("Number of ways to make change: " + numberOfWays); + } +} From 1f8fdb052dd9733965e650ff28bc83f6853d5c33 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:10:03 +0530 Subject: [PATCH 1288/1894] add num ways to make change in python --- .../num_ways_to_make_change.py | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_make_change.py diff --git a/Dynamic Programming/num_ways_to_make_change.py b/Dynamic Programming/num_ways_to_make_change.py new file mode 100644 index 00000000..0bd8fcc5 --- /dev/null +++ b/Dynamic Programming/num_ways_to_make_change.py @@ -0,0 +1,69 @@ +''' + Given an array of distinct positive integers representing coin denominations and a single non-negative integer n + representing a target amount of money, write a function that returns the number of ways to make change for + that target amount using the given coin denominations. + + Sample Input: n = 6 denominations : [1, 5] + Output: 2 (1 * 1 + 1 * 5 and 6 * 1) + + Explanation: + + The given code snippet is implementing the "NumberOfWaysToMakeChange" algorithm in Go. + This algorithm calculates the number of ways to make change for a given amount using a set of denominations. + + Here's how the algorithm works: + + 1. The function "NumberOfWaysToMakeChange" takes two parameters: "n" (the target amount to make change for) and "denoms" + (an array of coin denominations). + + 2. It initializes an array called "ways" of size "n+1" to keep track of the number of ways to make change for each amount + from 0 to "n". The initial value of "ways[0]" is set to 1, representing the base case where there is one way to make + change for zero. + + 3. The algorithm iterates over each denomination in the "denoms" array using a for-each loop. + + 4. For each denomination, it further iterates from 1 to "n+1" to calculate the number of ways to make change for each + amount. + + 5. Inside the inner loop, it checks if the current denomination is less than or equal to the current amount. If so, + it means that the current denomination can contribute to the change for the current amount. + + 6. It then updates the "ways[amount]" value by adding the number of ways to make change for the current amount minus + the current denomination. This is done to accumulate all the possible ways to make change using the current denomination. + + 7. After completing the nested loops, the algorithm returns the value stored in "ways[n]", which represents the total + number of ways to make change for the target amount "n" using the given denominations. + + In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given + amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. + + Time complexity : O(nd) + Space complexity : O(n) where n is the target amount and d is the number of coin denominations +''' +def number_of_ways_to_make_change(n, denoms): + # Create a list to store the number of ways to make change for each amount from 0 to n. + ways = [0] * (n + 1) + + # Initialize the base case: There is one way to make change for amount 0 (using no coins). + ways[0] = 1 + + # Iterate over each denomination. + for denom in denoms: + # For each denomination, iterate over each amount from 1 to n. + for amount in range(1, n + 1): + # Check if the denomination can be used to make change for the current amount. + if denom <= amount: + # Add the number of ways to make change for the current amount + # by considering the current denomination. + ways[amount] += ways[amount - denom] + + # Return the number of ways to make change for the target amount n. + return ways[n] + + +# Example usage +n = 10 +denoms = [1, 2, 5] + +number_of_ways = number_of_ways_to_make_change(n, denoms) +print("Number of ways to make change:", number_of_ways) From 6a93d31bda03dc6d8a036e44577d30145a2923f7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:11:02 +0530 Subject: [PATCH 1289/1894] add num ways to make change in javascript --- .../num_ways_to_make_change.js | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_make_change.js diff --git a/Dynamic Programming/num_ways_to_make_change.js b/Dynamic Programming/num_ways_to_make_change.js new file mode 100644 index 00000000..0ba6d8a3 --- /dev/null +++ b/Dynamic Programming/num_ways_to_make_change.js @@ -0,0 +1,73 @@ +/* + Given an array of distinct positive integers representing coin denominations and a single non-negative integer n + representing a target amount of money, write a function that returns the number of ways to make change for + that target amount using the given coin denominations. + + Sample Input: n = 6 denominations : [1, 5] + Output: 2 (1 * 1 + 1 * 5 and 6 * 1) + + Explanation: + + The given code snippet is implementing the "NumberOfWaysToMakeChange" algorithm in Go. + This algorithm calculates the number of ways to make change for a given amount using a set of denominations. + + Here's how the algorithm works: + + 1. The function "NumberOfWaysToMakeChange" takes two parameters: "n" (the target amount to make change for) and "denoms" + (an array of coin denominations). + + 2. It initializes an array called "ways" of size "n+1" to keep track of the number of ways to make change for each amount + from 0 to "n". The initial value of "ways[0]" is set to 1, representing the base case where there is one way to make + change for zero. + + 3. The algorithm iterates over each denomination in the "denoms" array using a for-each loop. + + 4. For each denomination, it further iterates from 1 to "n+1" to calculate the number of ways to make change for each + amount. + + 5. Inside the inner loop, it checks if the current denomination is less than or equal to the current amount. If so, + it means that the current denomination can contribute to the change for the current amount. + + 6. It then updates the "ways[amount]" value by adding the number of ways to make change for the current amount minus + the current denomination. This is done to accumulate all the possible ways to make change using the current denomination. + + 7. After completing the nested loops, the algorithm returns the value stored in "ways[n]", which represents the total + number of ways to make change for the target amount "n" using the given denominations. + + In summary, this algorithm utilizes dynamic programming to calculate the number of ways to make change for a given + amount using a set of denominations. By iteratively building up the solutions for smaller amounts, it efficiently computes the result in O(n * m) time complexity, where "n" is the target amount and "m" is the number of denominations. The space complexity is O(n), as the algorithm uses an array of size "n+1" to store the intermediate results. + + Time complexity : O(nd) + Space complexity : O(n) where n is the target amount and d is the number of coin denominations + +*/ +function numberOfWaysToMakeChange(n, denoms) { + // Create an array to store the number of ways to make change for each amount from 0 to n. + const ways = new Array(n + 1).fill(0); + + // Initialize the base case: There is one way to make change for amount 0 (using no coins). + ways[0] = 1; + + // Iterate over each denomination. + for (const denom of denoms) { + // For each denomination, iterate over each amount from 1 to n. + for (let amount = 1; amount < n + 1; amount++) { + // Check if the denomination can be used to make change for the current amount. + if (denom <= amount) { + // Add the number of ways to make change for the current amount + // by considering the current denomination. + ways[amount] += ways[amount - denom]; + } + } + } + + // Return the number of ways to make change for the target amount n. + return ways[n]; +} + +// Example usage +const n = 10; +const denoms = [1, 2, 5]; + +const numberOfWays = numberOfWaysToMakeChange(n, denoms); +console.log("Number of ways to make change:", numberOfWays); From 791026002aeb2362f4d6a12b119a95111f66bf2b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:13:28 +0530 Subject: [PATCH 1290/1894] add optimal approach --- Arrays/array_of_products.go | 55 ++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/Arrays/array_of_products.go b/Arrays/array_of_products.go index e51a6941..63df8f1b 100644 --- a/Arrays/array_of_products.go +++ b/Arrays/array_of_products.go @@ -30,32 +30,29 @@ three times. It has a space complexity of O(n), since it creates a new result array of size n, and two additional integer variables. */ -package main - -func ArrayOfProducts(array []int) []int { - // create two arrays to store the products of all elements to the left and right of each element in the input array - leftProduct := make([]int, len(array)) - rightProduct := make([]int, len(array)) - - // compute the product of all elements to the left of each element in the input array - leftRunningProduct := 1 - for i := 0; i < len(array); i++ { - leftProduct[i] = leftRunningProduct - leftRunningProduct *= array[i] - } - - // compute the product of all elements to the right of each element in the input array - rightRunningProduct := 1 - for i := len(array) - 1; i >= 0; i-- { - rightProduct[i] = rightRunningProduct - rightRunningProduct *= array[i] - } - - // compute the product of all elements to the left and right of each element in the input array - for i := 0; i < len(array); i++ { - rightProduct[i] = leftProduct[i] * rightProduct[i] - } - - // return the array of products - return rightProduct -} + package main + + // Given an array of integers, returns an array where each element + // is the product of all the integers in the input array except for the one at that index. + func ArrayOfProducts(array []int) []int { + result := make([]int, len(array)) + + // Compute the running product of all elements to the left of each index + // and store it in the result array. + leftRunningProduct := 1 + for i := 0; i < len(array); i++ { + result[i] = leftRunningProduct // Store left product in the result array + leftRunningProduct *= array[i] // Update left product + } + + // Compute the running product of all elements to the right of each index + // and multiply it with the corresponding left product in the result array. + rightRunningProduct := 1 + for i := len(array) - 1; i >= 0; i-- { + result[i] = rightRunningProduct * result[i] // Multiply the right product with the corresponding left product + rightRunningProduct *= array[i] // Update right product + } + + return result + } + From 940a35c8ac97f88fc942565acc5f97b87d935ea3 Mon Sep 17 00:00:00 2001 From: Diwakar Singh <76618190+thakurdiwakar@users.noreply.github.com> Date: Mon, 5 Jun 2023 23:16:50 +0530 Subject: [PATCH 1291/1894] Added Bloom Filter Algo in C++ --- Bit Manipulation/bloom_filter.cpp | 87 ++++++++++++++++--------------- 1 file changed, 46 insertions(+), 41 deletions(-) diff --git a/Bit Manipulation/bloom_filter.cpp b/Bit Manipulation/bloom_filter.cpp index 6a14821b..e9b78eae 100644 --- a/Bit Manipulation/bloom_filter.cpp +++ b/Bit Manipulation/bloom_filter.cpp @@ -1,3 +1,6 @@ +// Bloom Filter Implementation +// Question: How does the Bloom filter work, and how is it implemented in the C++ + // Approach and Explanation // 1. **Hash Functions**: The Bloom filter uses four hash functions (`h1`, `h2`, `h3`, `h4`) to map input strings to positions in the bit array. These hash functions generate different indexes based on the input string and the size of the bit array. @@ -14,117 +17,119 @@ // In this implementation, the size of the bit array is fixed at 1000000, and four hash functions are used. The elements are inserted by setting the corresponding positions in the bit array to 1. The `lookup` function checks if all the positions for an element are set (1), indicating its possible presence in the filter. - - - // Time Complexity-> O(1) on average, O(n) in the worst case // Space Complexity-> O(n) - - - - - #include #include #include #define ll long long -// hash 1 +// Hash function 1 +// This function calculates the hash value of a string using a simple additive approach. int h1(std::string s, int arrSize) { ll int hash = 0; for (int i = 0; i < s.size(); i++) { - hash = (hash + ((int)s[i])); - hash = hash % arrSize; + hash = (hash + ((int)s[i])); // Add the ASCII value of each character to the hash + hash = hash % arrSize; // Take the modulus to ensure the hash value is within the array size } return hash; } -// hash 2 +// Hash function 2 +// This function calculates the hash value of a string using an exponential approach. int h2(std::string s, int arrSize) { ll int hash = 1; for (int i = 0; i < s.size(); i++) { - hash = hash + pow(19, i) * s[i]; - hash = hash % arrSize; + hash = hash + pow(19, i) * s[i]; // Multiply each character by a power of 19 and add to the hash + hash = hash % arrSize; // Take the modulus to ensure the hash value is within the array size } return hash % arrSize; } -// hash 3 +// Hash function 3 +// This function calculates the hash value of a string using a polynomial approach. int h3(std::string s, int arrSize) { ll int hash = 7; for (int i = 0; i < s.size(); i++) { - hash = (hash * 31 + s[i]) % arrSize; + hash = (hash * 31 + s[i]) % arrSize; // Multiply the hash by 31, add the character, and take the modulus } return hash % arrSize; } -// hash 4 +// Hash function 4 +// This function calculates the hash value of a string using a combination of multiplication and exponentiation. int h4(std::string s, int arrSize) { ll int hash = 3; int p = 7; for (int i = 0; i < s.size(); i++) { - hash += hash * 7 + s[i] * pow(p, i); - hash = hash % arrSize; + hash += hash * 7 + s[i] * pow(p, i); // Multiply the hash by 7, add the character multiplied by a power of 7 + hash = hash % arrSize; // Take the modulus to ensure the hash value is within the array size } return hash; } -// lookup operation +// Lookup operation +// This function checks if a given string is present in the bit array. bool lookup(std::bitset<1000000> &bitarray, std::string s) { - int a = h1(s, bitarray.size()); - int b = h2(s, bitarray.size()); - int c = h3(s, bitarray.size()); - int d = h4(s, bitarray.size()); + int a = h1(s, bitarray.size()); // Calculate hash using h1 + int b = h2(s, bitarray.size()); // Calculate hash using h2 + int c = h3(s, bitarray.size()); // Calculate hash using h3 + int d = h4(s, bitarray.size()); // Calculate hash using h4 - return bitarray[a] && bitarray[b] && bitarray[c] && bitarray[d]; + return bitarray[a] && bitarray[b] && bitarray[c] && bitarray[d]; // Check if all corresponding bits are set in the bit array } -// insert operation +// Insert operation +// This function inserts a string into the bit array. void insert(std::bitset<1000000> &bitarray, std::string s) { - // check if the element is already present or not + // Check if the element is already present or not if (lookup(bitarray, s)) { std::cout << s << " is probably already present" << std::endl; } else { - int a = h1(s, bitarray.size()); - int b = h2(s, bitarray.size()); - int c = h3(s, bitarray.size()); - int d = h4(s, bitarray.size()); + int a = h1(s, bitarray.size()); // Calculate hash using h1 + int b = h2(s, bitarray.size()); // Calculate hash using h2 + int c = h3(s, bitarray.size()); // Calculate hash using h3 + int d = h4(s, bitarray.size()); // Calculate hash using h4 - bitarray[a] = true; - bitarray[b] = true; - bitarray[c] = true; - bitarray[d] = true; + bitarray[a] = true; // Set corresponding bit in the bit array for hash a + bitarray[b] = true; // Set corresponding bit in the bit array for hash b + bitarray[c] = true; // Set corresponding bit in the bit array for hash c + bitarray[d] = true; // Set corresponding bit in the bit array for hash d std::cout << s << " inserted" << std::endl; } } -int main() { +int main() +{ std::bitset<1000000> bitarray; - std::string sarray[] = { "apple", "banana", "cherry", "orange", "grape", "kiwi" }; + std::string sarray[] = {"apple", "banana", "cherry", "orange", "grape", "kiwi"}; - for (const auto& s : sarray) { - if (lookup(bitarray, s)) { + for (const auto &s : sarray) + { + if (lookup(bitarray, s)) + { std::cout << s << " is already present" << std::endl; - } else { + } + else + { insert(bitarray, s); } } return 0; } - From a7341e4fef58a830f663be982ec575fc5f20da70 Mon Sep 17 00:00:00 2001 From: Diwakar Singh <76618190+thakurdiwakar@users.noreply.github.com> Date: Mon, 5 Jun 2023 23:17:36 +0530 Subject: [PATCH 1292/1894] Update bloom_filter.cpp --- Bit Manipulation/bloom_filter.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Bit Manipulation/bloom_filter.cpp b/Bit Manipulation/bloom_filter.cpp index e9b78eae..31bba2ef 100644 --- a/Bit Manipulation/bloom_filter.cpp +++ b/Bit Manipulation/bloom_filter.cpp @@ -3,15 +3,15 @@ // Approach and Explanation -// 1. **Hash Functions**: The Bloom filter uses four hash functions (`h1`, `h2`, `h3`, `h4`) to map input strings to positions in the bit array. These hash functions generate different indexes based on the input string and the size of the bit array. +// 1.Hash Functions: The Bloom filter uses four hash functions (`h1`, `h2`, `h3`, `h4`) to map input strings to positions in the bit array. These hash functions generate different indexes based on the input string and the size of the bit array. -// 2. **Bit Array**: The Bloom filter uses a `std::bitset<1000000>` called `bitarray` to represent the filter. It is a fixed-size bit array where each bit represents a position that can be set (1) or unset (0). +// 2. Bit Array: The Bloom filter uses a `std::bitset<1000000>` called `bitarray` to represent the filter. It is a fixed-size bit array where each bit represents a position that can be set (1) or unset (0). -// 3. **Lookup Operation**: The `lookup` function takes a reference to the `bitarray` and a string `s` as input. It calculates the hash values for `s` using the four hash functions and checks if the corresponding positions in the `bitarray` are all set (1). If all positions are set, it returns `true`, indicating that the element is possibly present in the filter. Otherwise, it returns `false`. +// 3. Lookup Operation: The `lookup` function takes a reference to the `bitarray` and a string `s` as input. It calculates the hash values for `s` using the four hash functions and checks if the corresponding positions in the `bitarray` are all set (1). If all positions are set, it returns `true`, indicating that the element is possibly present in the filter. Otherwise, it returns `false`. -// 4. **Insert Operation**: The `insert` function takes a reference to the `bitarray` and a string `s` as input. It first checks if the element is already present in the filter by calling the `lookup` function. If the element is already present, it prints a message indicating that it is probably already present. Otherwise, it calculates the hash values for `s` using the four hash functions and sets the corresponding positions in the `bitarray` to 1, indicating the insertion of the element. +// 4. Insert Operation: The `insert` function takes a reference to the `bitarray` and a string `s` as input. It first checks if the element is already present in the filter by calling the `lookup` function. If the element is already present, it prints a message indicating that it is probably already present. Otherwise, it calculates the hash values for `s` using the four hash functions and sets the corresponding positions in the `bitarray` to 1, indicating the insertion of the element. -// 5. **Main Function**: In the `main` function, a `bitarray` of size 1000000 is created. A set of strings (`sarray`) is defined, representing the elements to be added to the filter. For each string `s` in `sarray`, it checks if `s` is already present in the filter using the `lookup` function. If it is present, it prints a message indicating that it is already present. Otherwise, it inserts `s` into the filter using the `insert` function. +// 5. Main Function: In the `main` function, a `bitarray` of size 1000000 is created. A set of strings (`sarray`) is defined, representing the elements to be added to the filter. For each string `s` in `sarray`, it checks if `s` is already present in the filter using the `lookup` function. If it is present, it prints a message indicating that it is already present. Otherwise, it inserts `s` into the filter using the `insert` function. // The Bloom filter provides a probabilistic way to test whether an element is possibly in a set. It may return false positives, indicating that an element is possibly in the set when it's not, but it will never give false negatives. The accuracy of the filter depends on the size of the bit array, the number of hash functions used, and the number of elements inserted. From 1bf40419a24623ca5f60bf84c3e6ef6241ae5be9 Mon Sep 17 00:00:00 2001 From: Diwakar Singh <76618190+thakurdiwakar@users.noreply.github.com> Date: Mon, 5 Jun 2023 23:18:41 +0530 Subject: [PATCH 1293/1894] Added Bloom FIlter Algorithm in Python --- Bit Manipulation/bloom_filter.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/Bit Manipulation/bloom_filter.py b/Bit Manipulation/bloom_filter.py index dee5166d..816193da 100644 --- a/Bit Manipulation/bloom_filter.py +++ b/Bit Manipulation/bloom_filter.py @@ -1,4 +1,5 @@ - +# Bloom Filter Implementation +# Question: How can I implement a Bloom filter in Python? # explanation of the approach: @@ -23,7 +24,6 @@ # The Bloom filter uses the MurmurHash3 hash function (`mmh3.hash()`) to generate hash values for the items. The number of hash functions and the size of the bit array are calculated based on the desired false positive rate and capacity. The Bloom filter provides a probabilistic check for membership, with a possibility of false positives but no false negatives. - import math import mmh3 from bitarray import bitarray @@ -39,27 +39,34 @@ def __init__(self, capacity, false_positive_rate): self.bit_array.setall(0) def calculate_size(self): - size = - (self.capacity * math.log(self.false_positive_rate)) / (math.log(2) ** 2) + # Calculate the size of the bit array based on the capacity and false positive rate + size = - (self.capacity * math.log(self.false_positive_rate) + ) / (math.log(2) ** 2) return int(size) def calculate_num_hashes(self): + # Calculate the number of hash functions based on the size and capacity num_hashes = (self.size / self.capacity) * math.log(2) return int(num_hashes) def add(self, item): + # Add an item to the Bloom filter for seed in range(self.num_hashes): + # Generate a hash value using the MurmurHash3 algorithm with different seeds index = mmh3.hash(item, seed) % self.size self.bit_array[index] = 1 def contains(self, item): + # Check if an item is possibly in the Bloom filter for seed in range(self.num_hashes): + # Generate a hash value using the MurmurHash3 algorithm with different seeds index = mmh3.hash(item, seed) % self.size if self.bit_array[index] == 0: return False return True -# Example usage +# Create a Bloom filter with a capacity of 1000 items and a false positive rate of 0.01 bloom_filter = BloomFilter(capacity=1000, false_positive_rate=0.01) # Add items to the filter @@ -68,7 +75,7 @@ def contains(self, item): bloom_filter.add("cherry") # Check if items are in the filter -print(bloom_filter.contains("apple")) -print(bloom_filter.contains("banana")) -print(bloom_filter.contains("cherry")) -print(bloom_filter.contains("orange")) +print(bloom_filter.contains("apple")) # Expected output: True +print(bloom_filter.contains("banana")) # Expected output: True +print(bloom_filter.contains("cherry")) # Expected output: True +print(bloom_filter.contains("orange")) # Expected output: False From ee26f8de31cba80d2ee7f9bb56d6fd02c3555b3d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:20:07 +0530 Subject: [PATCH 1294/1894] update explanation --- Arrays/array_of_products.go | 58 +++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/Arrays/array_of_products.go b/Arrays/array_of_products.go index 63df8f1b..cfdf2e31 100644 --- a/Arrays/array_of_products.go +++ b/Arrays/array_of_products.go @@ -1,39 +1,41 @@ /* - Given an array of integers A, find and return the product array of the same size where the ith - element of the product array will be equal to the product of all the elements divided by the ith + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith element of the array. - Note: It is always possible to form the product array with integer (32 bit) values. + Note: It is always possible to form the product array with integer (32 bit) values. Solve it without using the division operator. Input: [1, 2, 3, 4, 5] Output : [120, 60, 40, 30, 24] - - Explanation: - This code implements a function called `ArrayOfProducts`, which takes an input array of integers and returns a - new array of the same size, where each element in the new array is the product of all the elements in the input - array except for the element at that index. - - To accomplish this, the function first creates a new result array with the same length as the input array. - Then, it initializes a `leftRunningProduct` variable to 1, and loops through the input array from left to right. - For each element in the input array, the function sets the corresponding element in the result array to the - current value of `leftRunningProduct`, and then updates `leftRunningProduct` to be the product of `leftRunningProduct` - and the current element in the input array. - - Next, the function initializes a `rightRunningProduct` variable to 1, and loops through the input array from right to left. - For each element in the input array, the function multiplies the corresponding element in the result array by `rightRunningProduct`, - and then updates `rightRunningProduct` to be the product of `rightRunningProduct` and the current element in the input array. - - Finally, the function returns the result array. - This algorithm has a time complexity of O(n), where n is the length of the input array, since it loops through the input array - three times. It has a space complexity of O(n), since it creates a new result array of size n, and two additional integer variables. - */ - - package main - - // Given an array of integers, returns an array where each element - // is the product of all the integers in the input array except for the one at that index. + Explanation: + The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works: + + 1. It initializes an empty result array with the same length as the input array to store the final products. + 2. It uses a left-to-right approach to compute the running product of all elements to the left of each index. + 3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side. + 4. It iterates over the input array from left to right using a `for` loop. + 5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the + `leftRunningProduct` by multiplying it with the corresponding element in the input array. + 6. After the loop, the result array will contain the product of all elements to the left of each index. + 7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and + multiply it with the corresponding left product in the result array. + 8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side. + 9. It iterates over the input array from right to left using a `for` loop. + 10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array + and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array. + 11. After the loop, the result array will contain the product of all elements to the left and right of each index, + except for the element at that index. + 12. Finally, it returns the result array. + + This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products. +*/ + +package main + +// Given an array of integers, returns an array where each element +// is the product of all the integers in the input array except for the one at that index. func ArrayOfProducts(array []int) []int { result := make([]int, len(array)) From a0549a0703bcb1e5f49d4b95fd49ed9fba78a79f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:22:11 +0530 Subject: [PATCH 1295/1894] add array of product in c++ --- Arrays/array_of_products.cpp | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Arrays/array_of_products.cpp diff --git a/Arrays/array_of_products.cpp b/Arrays/array_of_products.cpp new file mode 100644 index 00000000..20bbcc4e --- /dev/null +++ b/Arrays/array_of_products.cpp @@ -0,0 +1,77 @@ +/* + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith + element of the array. + + Note: It is always possible to form the product array with integer (32 bit) values. + Solve it without using the division operator. + + Input: [1, 2, 3, 4, 5] + Output : [120, 60, 40, 30, 24] + + Explanation: + The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works: + + 1. It initializes an empty result array with the same length as the input array to store the final products. + 2. It uses a left-to-right approach to compute the running product of all elements to the left of each index. + 3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side. + 4. It iterates over the input array from left to right using a `for` loop. + 5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the + `leftRunningProduct` by multiplying it with the corresponding element in the input array. + 6. After the loop, the result array will contain the product of all elements to the left of each index. + 7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and + multiply it with the corresponding left product in the result array. + 8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side. + 9. It iterates over the input array from right to left using a `for` loop. + 10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array + and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array. + 11. After the loop, the result array will contain the product of all elements to the left and right of each index, + except for the element at that index. + 12. Finally, it returns the result array. + + This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products. +*/ + +#include +#include + +using namespace std; + +// Given an array of integers, returns an array where each element +// is the product of all the integers in the input array except for the one at that index. +vector ArrayOfProducts(vector& array) { + int n = array.size(); + vector result(n, 1); + + // Compute the running product of all elements to the left of each index + // and store it in the result array. + int leftRunningProduct = 1; + for (int i = 0; i < n; i++) { + result[i] = leftRunningProduct; // Store left product in the result array + leftRunningProduct *= array[i]; // Update left product + } + + // Compute the running product of all elements to the right of each index + // and multiply it with the corresponding left product in the result array. + int rightRunningProduct = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product + rightRunningProduct *= array[i]; // Update right product + } + + return result; +} + +int main() { + // Example usage + vector input = {1, 2, 3, 4, 5}; + vector output = ArrayOfProducts(input); + + // Print the result + for (int num : output) { + cout << num << " "; + } + cout << endl; + + return 0; +} From 6803842516850c05dc234ef06dbccc02e92bda15 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:26:25 +0530 Subject: [PATCH 1296/1894] add array of products in java --- Arrays/array_of_products.java | 68 +++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Arrays/array_of_products.java diff --git a/Arrays/array_of_products.java b/Arrays/array_of_products.java new file mode 100644 index 00000000..b1f65e82 --- /dev/null +++ b/Arrays/array_of_products.java @@ -0,0 +1,68 @@ +/* + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith + element of the array. + + Note: It is always possible to form the product array with integer (32 bit) values. + Solve it without using the division operator. + + Input: [1, 2, 3, 4, 5] + Output : [120, 60, 40, 30, 24] + + Explanation: + The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works: + + 1. It initializes an empty result array with the same length as the input array to store the final products. + 2. It uses a left-to-right approach to compute the running product of all elements to the left of each index. + 3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side. + 4. It iterates over the input array from left to right using a `for` loop. + 5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the + `leftRunningProduct` by multiplying it with the corresponding element in the input array. + 6. After the loop, the result array will contain the product of all elements to the left of each index. + 7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and + multiply it with the corresponding left product in the result array. + 8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side. + 9. It iterates over the input array from right to left using a `for` loop. + 10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array + and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array. + 11. After the loop, the result array will contain the product of all elements to the left and right of each index, + except for the element at that index. + 12. Finally, it returns the result array. + + This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products. +*/ +import java.util.Arrays; + +public class ArrayOfProducts { + public static int[] arrayOfProducts(int[] array) { + int n = array.length; + int[] result = new int[n]; + + // Compute the running product of all elements to the left of each index + // and store it in the result array. + int leftRunningProduct = 1; + for (int i = 0; i < n; i++) { + result[i] = leftRunningProduct; // Store left product in the result array + leftRunningProduct *= array[i]; // Update left product + } + + // Compute the running product of all elements to the right of each index + // and multiply it with the corresponding left product in the result array. + int rightRunningProduct = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product + rightRunningProduct *= array[i]; // Update right product + } + + return result; + } + + public static void main(String[] args) { + // Example usage + int[] input = {1, 2, 3, 4, 5}; + int[] output = arrayOfProducts(input); + + // Print the result + System.out.println(Arrays.toString(output)); + } +} From 34af204def4b15c03e78d6b2a48981b921f3ff36 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:26:33 +0530 Subject: [PATCH 1297/1894] add array of products in javascript --- Arrays/array_of_products.js | 62 +++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Arrays/array_of_products.js diff --git a/Arrays/array_of_products.js b/Arrays/array_of_products.js new file mode 100644 index 00000000..55c38276 --- /dev/null +++ b/Arrays/array_of_products.js @@ -0,0 +1,62 @@ +/* + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith + element of the array. + + Note: It is always possible to form the product array with integer (32 bit) values. + Solve it without using the division operator. + + Input: [1, 2, 3, 4, 5] + Output : [120, 60, 40, 30, 24] + + Explanation: + The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works: + + 1. It initializes an empty result array with the same length as the input array to store the final products. + 2. It uses a left-to-right approach to compute the running product of all elements to the left of each index. + 3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side. + 4. It iterates over the input array from left to right using a `for` loop. + 5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the + `leftRunningProduct` by multiplying it with the corresponding element in the input array. + 6. After the loop, the result array will contain the product of all elements to the left of each index. + 7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and + multiply it with the corresponding left product in the result array. + 8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side. + 9. It iterates over the input array from right to left using a `for` loop. + 10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array + and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array. + 11. After the loop, the result array will contain the product of all elements to the left and right of each index, + except for the element at that index. + 12. Finally, it returns the result array. + + This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products. +*/ +function arrayOfProducts(array) { + const n = array.length; + const result = new Array(n).fill(1); + + // Compute the running product of all elements to the left of each index + // and store it in the result array. + let leftRunningProduct = 1; + for (let i = 0; i < n; i++) { + result[i] = leftRunningProduct; // Store left product in the result array + leftRunningProduct *= array[i]; // Update left product + } + + // Compute the running product of all elements to the right of each index + // and multiply it with the corresponding left product in the result array. + let rightRunningProduct = 1; + for (let i = n - 1; i >= 0; i--) { + result[i] *= rightRunningProduct; // Multiply the right product with the corresponding left product + rightRunningProduct *= array[i]; // Update right product + } + + return result; +} + +// Example usage +const inputArray = [1, 2, 3, 4, 5]; +const outputArray = arrayOfProducts(inputArray); + +// Print the result +console.log(outputArray); From 9d9d9b0e8713560bf9be19867e73bbae3fd4f583 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 5 Jun 2023 23:26:38 +0530 Subject: [PATCH 1298/1894] add array of products in python --- Arrays/array_of_products.py | 59 +++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Arrays/array_of_products.py diff --git a/Arrays/array_of_products.py b/Arrays/array_of_products.py new file mode 100644 index 00000000..2972deea --- /dev/null +++ b/Arrays/array_of_products.py @@ -0,0 +1,59 @@ +''' + Given an array of integers A, find and return the product array of the same size where the ith + element of the product array will be equal to the product of all the elements divided by the ith + element of the array. + + Note: It is always possible to form the product array with integer (32 bit) values. + Solve it without using the division operator. + + Input: [1, 2, 3, 4, 5] + Output : [120, 60, 40, 30, 24] + + Explanation: + The code snippet provides a function called `ArrayOfProducts` that takes an array of integers as input and returns another array where each element is the product of all the integers in the input array except for the one at that index. Here's how the code works: + + 1. It initializes an empty result array with the same length as the input array to store the final products. + 2. It uses a left-to-right approach to compute the running product of all elements to the left of each index. + 3. It initializes a variable `leftRunningProduct` to keep track of the running product of elements on the left side. + 4. It iterates over the input array from left to right using a `for` loop. + 5. For each index `i`, it stores the current `leftRunningProduct` in the result array at index `i` and then updates the + `leftRunningProduct` by multiplying it with the corresponding element in the input array. + 6. After the loop, the result array will contain the product of all elements to the left of each index. + 7. It uses a right-to-left approach to compute the running product of all elements to the right of each index and + multiply it with the corresponding left product in the result array. + 8. It initializes a variable `rightRunningProduct` to keep track of the running product of elements on the right side. + 9. It iterates over the input array from right to left using a `for` loop. + 10. For each index `i`, it multiplies the `rightRunningProduct` with the corresponding left product in the result array + and updates the `rightRunningProduct` by multiplying it with the corresponding element in the input array. + 11. After the loop, the result array will contain the product of all elements to the left and right of each index, + except for the element at that index. + 12. Finally, it returns the result array. + + This algorithm avoids using division and solves the problem in linear time complexity, making two passes over the input array. The space complexity is also linear, as it uses an additional array to store the products. +''' +def array_of_products(array): + n = len(array) + result = [1] * n + + # Compute the running product of all elements to the left of each index + # and store it in the result array. + left_running_product = 1 + for i in range(n): + result[i] = left_running_product # Store left product in the result array + left_running_product *= array[i] # Update left product + + # Compute the running product of all elements to the right of each index + # and multiply it with the corresponding left product in the result array. + right_running_product = 1 + for i in range(n - 1, -1, -1): + result[i] *= right_running_product # Multiply the right product with the corresponding left product + right_running_product *= array[i] # Update right product + + return result + +# Example usage +input_array = [1, 2, 3, 4, 5] +output_array = array_of_products(input_array) + +# Print the result +print(output_array) From 71a501641ac79e9e16e6a7ff6f18fb4e89b56688 Mon Sep 17 00:00:00 2001 From: Anup Khismatrao Date: Tue, 6 Jun 2023 14:14:06 +0530 Subject: [PATCH 1299/1894] New Problem added --- 2D Arrays (Matrix)/setMatrixZero.java | 177 ++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 2D Arrays (Matrix)/setMatrixZero.java diff --git a/2D Arrays (Matrix)/setMatrixZero.java b/2D Arrays (Matrix)/setMatrixZero.java new file mode 100644 index 00000000..ecf0b2cd --- /dev/null +++ b/2D Arrays (Matrix)/setMatrixZero.java @@ -0,0 +1,177 @@ +/* SET MATRIX ZERO - JAVA LANGUAGE + Problem Link1 : https://leetcode.com/problems/set-matrix-zeroes/ + Problem Link2 : https://www.codingninjas.com/codestudio/problems/zero-matrix_1171153 + +Problem: +You are given a 2D matrix, and the task is to modify it such that if an element in the matrix is zero, you need to set all the elements in the +corresponding row and column to zero as well. + +E.g- Input: | 1 1 1 | + | 1 0 1 | + | 1 1 1 | + + Output: | 1 0 1 | + | 0 0 0 | + | 1 0 1 | + +-- Naive Approach for Set Matrix Zeroes +Step 1. Create an array answer of size (n X m) and initialize every element as 1. +Step 2. Traverse the matrix array row-wise and set the current row as 0 in answer array if the current row contains an element equals to 0. +Step 3. Traverse the matrix array column-wise and set the current column as 0 in answer array if the current column contains an element equals to 0. +Step 4. Now traverse the answer array, if the current element is 0, then set this element as 0 in a matrix array. +Step 5. Return matrix array + +Complexity Analysis +Time Complexity = O(n * m) +Space Complexity = O(n * m) +where n is the number of rows in the matrix and m is the number of columns in the matrix. + +*/ +/* +public class setMatrixZero { + private static void setZeroes(int[][] matrix, int n, int m) { + int answer[][] = new int[n][m]; // Step 1 + // Set all elements of answer array as 1 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + answer[i][j] = 1; // making each element as 1 + } + } + // Traverse row wise -- Step 2 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (matrix[i][j] == 0) { + // Set this row as zero in answer array + for (int k = 0; k < m; k++) { + answer[i][k] = 0; + } + break; + } + } + } + // Traverse column wise -- Step 3 + for (int j = 0; j < m; j++) { + for (int i = 0; i < n; i++) { + if (matrix[i][j] == 0) { + // Set this column as 0 in answer array + for (int k = 0; k < n; k++) { + answer[k][j] = 0; + } + } + } + } + // Update the elements in matrix array -- Step 4 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (answer[i][j] == 0) { + matrix[i][j] = 0; + } + } + } + } + public static void main(String[] args) { + // Example 1 + int[][] matrix = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; + int n = matrix.length; + int m = matrix[0].length; + setZeroes(matrix, n, m); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + // Example 2 + matrix = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; + n = matrix.length; + m = matrix[0].length; + + setZeroes(matrix, n, m); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } +} +*/ + +/* +-- Optimal Approach for Set Matrix Zeroes +If we assume that -1, do not occur in the matrix array, then + +Step 1. Traverse the matrix array row-wise and set all the elements of current row which are not 0 as -1, if the current row contains an element equals to 0. +Step 2. Traverse the matrix array column-wise and set all the elements of the current column which are not 0 as -1, if the current column contains an element equals to 0. +Step 3. Again traverse the matrix and set all the elements that are -1 to 0. +Step 4. Return matrix array. + +Complexity Analysis +Time Complexity = O(n * m) +Space Complexity = O(1) +where n is the number of rows in the matrix and m is the number of columns in the matrix. +*/ + +public class setMatrixZero { + private static void setZeroes(int[][] matrix, int n, int m) { + // Traverse row wise + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (matrix[i][j] == 0) { + // Set all the elements that are not zero as -1 + for (int k = 0; k < m; k++) { + if (matrix[i][k] != 0) { + matrix[i][k] = -1; + } + } + } + } + } + // Traverse column wise + for (int j = 0; j < m; j++) { + for (int i = 0; i < n; i++) { + if (matrix[i][j] == 0) { + // Set all the elements that are not zero as -1 + for (int k = 0; k < n; k++) { + if (matrix[k][j] != 0) { + matrix[k][j] = -1; + } + } + } + } + } + + // Update all -1 as 0 + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (matrix[i][j] == -1) { + matrix[i][j] = 0; + } + } + } + } + public static void main(String[] args) { + // Example 1 + int[][] matrix = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; + int n = matrix.length; + int m = matrix[0].length; + setZeroes(matrix, n, m); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + // Example 2 + matrix = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; + n = matrix.length; + m = matrix[0].length; + setZeroes(matrix, n, m); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + } +} \ No newline at end of file From f266b44c8ab61bab26b5654318e70a3517267638 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:09:15 +0530 Subject: [PATCH 1300/1894] remove duplicate --- Arrays/add_valid_palindrome.java | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 Arrays/add_valid_palindrome.java diff --git a/Arrays/add_valid_palindrome.java b/Arrays/add_valid_palindrome.java deleted file mode 100644 index 6baec3ed..00000000 --- a/Arrays/add_valid_palindrome.java +++ /dev/null @@ -1,27 +0,0 @@ -/* -Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it. -Example 1: - -Input: s = "aba" -Output: true -*/ - -class Solution { - public boolean validPalindrome(String s) { - int i=0,j=s.length()-1; // initialize two pointers, i and j to the start and end of the string respectively - while(i Date: Tue, 6 Jun 2023 22:12:07 +0530 Subject: [PATCH 1301/1894] add valid pallindrome 2 in java --- Strings/valid_pallindrome2.java | 56 +++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Strings/valid_pallindrome2.java diff --git a/Strings/valid_pallindrome2.java b/Strings/valid_pallindrome2.java new file mode 100644 index 00000000..0c864231 --- /dev/null +++ b/Strings/valid_pallindrome2.java @@ -0,0 +1,56 @@ +// Check whether a string can be a valid palindrome by removing at most one character from it +/* + The given Go program takes a string as input and checks if it can be a valid palindrome by removing at most one + character from it. The program starts by defining two pointers, left and right, that move towards each other from + opposite ends of the input string. At each step, if the characters at the left and right pointers are equal, + then they move towards the center of the string. If the characters are not equal, then we check whether removing + the character at the left or right pointer would make the rest of the string a palindrome. If both removals fail, + then the string cannot be a valid palindrome by removing at most one character. The program returns true + if the string can be made a valid palindrome by removing at most one character, false otherwise. + + The time complexity of this algorithm is O(n), where n is the length of the input string. + The space complexity is O(1), as we only use constant extra space to store a few variables. + +*/ +public static boolean isPalindromeWithRemoval(String s) { + // Define two pointers to check the string from both ends + int i = 0, j = s.length() - 1; + + while (i < j) { + // If characters at the pointers are not equal + if (s.charAt(i) != s.charAt(j)) { + // Check if removing a character from the left pointer makes it a palindrome + String leftStr = s.substring(0, i) + s.substring(i + 1); + if (isPalindrome(leftStr)) { + return true; + } + // Check if removing a character from the right pointer makes it a palindrome + String rightStr = s.substring(0, j) + s.substring(j + 1); + if (isPalindrome(rightStr)) { + return true; + } + // If neither option works, it cannot be converted into a palindrome by removing at most one character + return false; + } + // Move the pointers towards the middle of the string + i++; + j--; + } + return true; +} + +public static boolean isPalindrome(String s) { + // Define two pointers to check the string from both ends + int i = 0, j = s.length() - 1; + + while (i < j) { + // If characters at the pointers are not equal, it is not a palindrome + if (s.charAt(i) != s.charAt(j)) { + return false; + } + // Move the pointers towards the middle of the string + i++; + j--; + } + return true; +} From 7f36f4748b492777b316e3215d8fb6ea983fceea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:14:37 +0530 Subject: [PATCH 1302/1894] remove unnecessary programs --- ...string_of_the_partition_is_a_palindrome.py | 50 --------- ...tring_of_the_partition_is_a_palindrome.cpp | 81 -------------- Strings/count_matches_in_tournament.cpp | 50 --------- Strings/halves_are_alike.cpp | 45 -------- ..._concatenated_string_with_unique_chars.cpp | 67 ----------- ...substring_without_repeating_characters.cpp | 86 --------------- ...h_concatenated_string_unique_characters.py | 60 ---------- Strings/no_of_substrings_with_1s.py | 104 ------------------ 8 files changed, 543 deletions(-) delete mode 100644 Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py delete mode 100644 Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp delete mode 100644 Strings/count_matches_in_tournament.cpp delete mode 100644 Strings/halves_are_alike.cpp delete mode 100644 Strings/len_of_concatenated_string_with_unique_chars.cpp delete mode 100644 Strings/longest_substring_without_repeating_characters.cpp delete mode 100644 Strings/max_length_concatenated_string_unique_characters.py delete mode 100644 Strings/no_of_substrings_with_1s.py diff --git a/Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py b/Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py deleted file mode 100644 index c76c4cb9..00000000 --- a/Strings/ Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Name : Veena -# GitHub username : Veena4512 -# Repository name : data-structures-and-algorithms -# Problem : Given a string s, partition s such that every substring of the partition is a palindrome in Python -# Issue Number : #1374 -""" - -"""The minimum_partitions function is a dynamic programming solution that calculates the minimum number of partitions -needed for a given string a, where each partition is a palindrome. It uses two arrays, dp and palindrome, -to store the intermediate results. The function iterates over each position in the string, checking if the substring -is a palindrome and updating the minimum cuts accordingly. Finally, it returns the minimum number of partitions -needed for the entire string. The solution leverages the concept of overlapping problems to efficiently compute -the minimum partitions using dynamic programming. """ - - -# using DP: -def minimum_partitions(a): - # Check if the input list is empty - if len(a) == 0: - return 0 - - # Initialize an array to store the minimum number of partitions - dp = [0 for i in range(len(a))] - - # Initialize a 2D array to store whether a substring is a palindrome or not - palindrome = [[False for i in range(len(a))] for j in range(len(a))] - - # Iterate over the input list - for i in range(len(a)): - cut = i # Initialize the minimum number of partitions to the current index - - # Iterate over the substring from 0 to the current index - for j in range(i + 1): - # Check if the characters at indices i and j are equal - # and the substring between i and j is a palindrome - if a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1]): - palindrome[j][i] = True # Mark the substring as a palindrome - cut = min(cut, 0 if j == 0 else (dp[j - 1] + 1)) # Update the minimum number of partitions - dp[i] = cut # Store the minimum number of partitions for the current index - - return dp[len(a) - 1] - -s = input() -print('Minimum cuts needed for Palindrome Partitioning is', minimum_partitions(s)) - -# Time complexity:O(n^2) -# Space complexity:The space complexity of the code is O(n^2) due to the usage of the 2D array -# palindrome, which dominates the space requirement, while the array dp contributes -# O(n) to the overall space complexity. - diff --git a/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp b/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp deleted file mode 100644 index d8a8098d..00000000 --- a/Strings/Given_a_string_s_partition_s_such_that_every_substring_of_the_partition_is_a_palindrome.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* -Name : MAnmay Ghosh -Github username : ManmayGhosh -Repository name : data-structures-and-algorithms -Problem : Given a string s, partition s such that every substring of the partition is a palindrome in C++ -Issue Number : #1373 - -Explanation of the below C++ code : - -A string is given, then a partition of the string is a palindrome partitioning if every substring of the partition is a palindrome. -For example, “aba|b|bbabb|a|b|aba” is a palindrome partitioning of “ababbbabbababa”. -We have to find the minimum cuts needed for a palindrome partitioning of a given string. -For example, minimum of 3 cuts are needed for “ababbbabbababa”. The three cuts are “a|babbbab|b|ababa”. - -Edge Cases -If string is palindrome, then minimum 0 cuts are needed. -If string contain all different characters, then minimum n-1 cuts are needed as by atleast - --------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ -*/ - -// Dynamic Programming Solution for Palindrome Partitioning Problem -#include -using namespace std; - -// This function returns the minimum number of cuts needed to partition a string such that every part is a palindrome -int minPalPartion(string str) -{ - int n = str.length(); - // C[i][j] = Minimum number of cuts needed for palindrome partitioning of substring str[i..j] - int C[n][n]; - - // P[i][j] = true if substring str[i..j] is palindrome, else false - bool P[n][n]; - - // Note that C[i][j] is 0 if P[i][j] is true - - // A string of length 1 will always be palindrome - for (int i = 0; i < n; i++) { - P[i][i] = true; - C[i][i] = 0; - } - - // L is substring length. Build the solution in bottom up manner by considering all substrings of length starting from 2 to n. - for (int L = 2; L <= n; L++) { - // For substring of length L, set different possible starting indexes - for (int i = 0; i < n - L + 1; i++) { - int j = i + L - 1; // Set ending index - - // If L is 2, then we just need tocompare two characters. - if (L == 2) - P[i][j] = (str[i] == str[j]); - // Else need to check two corner charactersand value of P[i+1][j-1] - else - P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1]; - - // IF str[i..j] is palindrome, then C[i][j] is 0 - if (P[i][j] == true) - C[i][j] = 0; - else { - // Make a cut at every possiblen location starting from i to j,n and get the minimum cost cut. - C[i][j] = INT_MAX; - for (int k = i; k <= j - 1; k++) - C[i][j] = min(C[i][j], C[i][k] + C[k + 1][j] + 1); - } - } - } - // Return the min cut value for complete string. ababbbabbababa - return C[0][n - 1]; -} - -// Driver code -int main() -{ - string str; - cout << "Enter String\t"; - cin >> str; - cout << "Min cuts needed for Palindrome Partitioning is "<< minPalPartion(str); - return 0; -} - diff --git a/Strings/count_matches_in_tournament.cpp b/Strings/count_matches_in_tournament.cpp deleted file mode 100644 index 963aadac..00000000 --- a/Strings/count_matches_in_tournament.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* - You are given an integer n, the number of teams in a tournament that has strange rules: - - If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. - If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. - Return the number of matches played in the tournament until a winner is decided. - - Example 1: - Input: n = 7 - Output: 6 - Explanation: Details of the tournament: - - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. - Total number of matches = 3 + 2 + 1 = 6. - - Example 2: - Input: n = 14 - Output: 13 - Explanation: Details of the tournament: - - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. - Total number of matches = 7 + 3 + 2 + 1 = 13. - - Constraints:\ - 1 <= n <= 200 -*/ - -class Solution { -public: - int numberOfMatches(int n) { - int res = 0; - while(n > 1){ - // In case of even simply divide number by 2 ad add result - if(n % 2 == 0){ - n = n / 2; - res += n; - } - // In case of odd simply divide number by 2 ad add result and increase n by 1 - if(n % 2 == 1){ - n = n / 2; - res += n; - n++; - } - } - return res; - } -}; \ No newline at end of file diff --git a/Strings/halves_are_alike.cpp b/Strings/halves_are_alike.cpp deleted file mode 100644 index e79cb0ce..00000000 --- a/Strings/halves_are_alike.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. - - Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. - - Return true if a and b are alike. Otherwise, return false. - - Example 1: - Input: s = "book" - Output: true - Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. - - Example 2: - Input: s = "textbook" - Output: false - Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. - Notice that the vowel o is counted twice. - - Constraints: - 2 <= s.length <= 1000 - s.length is even. - s consists of uppercase and lowercase letters. -*/ - -// Approach: Count vowels in first and second half and return whether count is equal or not -class Solution { -public: - bool halvesAreAlike(string s) { - set X {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; - int half = s.size() / 2; - int c = 0, d = 0; - // count vowels in first half - for(int i = 0; i < half; i++){ - if(X.find(s[i]) != X.end()) - c++; - } - // count vowels in second half - for(int i = half; i < s.size(); i++){ - if(X.find(s[i]) != X.end()){ - d++; - } - } - return c == d; - } -}; \ No newline at end of file diff --git a/Strings/len_of_concatenated_string_with_unique_chars.cpp b/Strings/len_of_concatenated_string_with_unique_chars.cpp deleted file mode 100644 index d4a8a568..00000000 --- a/Strings/len_of_concatenated_string_with_unique_chars.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* -You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. - -Return the maximum possible length of s. - -A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. - - - -Example 1: - -Input: arr = ["un","iq","ue"] -Output: 4 -Explanation: All the valid concatenations are: -- "" -- "un" -- "iq" -- "ue" -- "uniq" ("un" + "iq") -- "ique" ("iq" + "ue") -Maximum length is 4. -Example 2: - -Input: arr = ["cha","r","act","ers"] -Output: 6 -Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). -Example 3: - -Input: arr = ["abcdefghijklmnopqrstuvwxyz"] -Output: 26 -Explanation: The only string in arr has all 26 characters. - - -Constraints: - -1 <= arr.length <= 16 -1 <= arr[i].length <= 26 -arr[i] contains only lowercase English letters. -*/ - -#include -class Solution { -public: - int check(vector& arr, int i, string s){ - if(i == arr.size()){ - int freq[26] = {0}; - for(int k = 0; k < s.length(); k++){ - if(freq[s[k]-'a'] == 1) - return 0; - freq[s[k]-'a']++; - } - return s.length(); - } - int op1, op2; - op1 = op2 = INT_MIN; - // include the string - if(s.length() + arr[i].length() <= 26){ - op1 = check(arr, i+1, s + arr[i]); - } - // exclude it - op2 = check(arr, i+1, s); - return max(op1, op2); - } - int maxLength(vector& arr) { - return check(arr, 0, ""); - } -}; \ No newline at end of file diff --git a/Strings/longest_substring_without_repeating_characters.cpp b/Strings/longest_substring_without_repeating_characters.cpp deleted file mode 100644 index 29cdff8b..00000000 --- a/Strings/longest_substring_without_repeating_characters.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - Time Complexity: t(n) = n * 128 -> O(n). - Where n is the size of string s. - - Space Complexity: O(1) - - Given a string s, find the length of the longest substring without repeating characters. - - Example 1: - Input: s = "abcabcbb" - Output: 3 - Explanation: The answer is "abc", with the length of 3. - - Example 2: - Input: s = "bbbbb" - Output: 1 - Explanation: The answer is "b", with the length of 1. - - Example 3: - Input: s = "pwwkew" - Output: 3 - Explanation: The answer is "wke", with the length of 3. - Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. - - Constraints: - 0 <= s.length <= 5 * 104 - s consists of English letters, digits, symbols and spaces. - -**/ - - -class Solution { -public: - - - - // Array to store the frequency of characters for sub-string that's starts at index a and end at index b - 1. - int v[128] = {0}; - - /** - Function: mxDistinct returns the maximum number of unique charachters of substring s[a, b[ - if there is at least one character that present more than one time the function returns 0, - beacause where are looking for the lonest substring withput repating characters. - **/ - int mxDistinct() - { - int c = 0; - for (int i = 0; i < 128; ++i) { - if(v[i] > 1) - return 0; - - if(v[i] == 1) - c++; - } - return c; - } - - int lengthOfLongestSubstring(string s) { - - int a = 0, b = 0; - int sz = s.size(); - - if(!sz) // If the string s is empty the functon returns 0. - return 0; - - int mx = 0; // Variable mx to store the result. - - while (a <= b && b < sz) - { - - v[s[b++] - ' ']++; // Count how many times character at index b (s[b]) appears in the string s. - - int curMax = mxDistinct(); // Variable to store the current max or the max so far. - if(curMax) /** - If we find a substring without repeating characters we take the maximum between mx and curMax. - REMEMBER: We are looking for the longest one. Actullay, the size of the longest one. - **/ - - mx = max(mx, curMax); - else // If there is no such a substring we start looking for substring that begins at index a + 1. - v[s[a++] - ' ']--; - } - - return mx; - } -}; diff --git a/Strings/max_length_concatenated_string_unique_characters.py b/Strings/max_length_concatenated_string_unique_characters.py deleted file mode 100644 index 705401f9..00000000 --- a/Strings/max_length_concatenated_string_unique_characters.py +++ /dev/null @@ -1,60 +0,0 @@ -# Question -> - -# You are given an array of strings arr. A string s is formed by the concatenation -# of a subsequence of arr that has unique characters. - -# Return the maximum possible length of s. - -# A subsequence is an array that can be derived from another array -# by deleting some or no elements without changing the order of the remaining elements. - - -# Sample IO -> - -# Example 1: - -# Input: arr = ["un","iq","ue"] -# Output: 4 -# Explanation: All the valid concatenations are: -# - "" -# - "un" -# - "iq" -# - "ue" -# - "uniq" ("un" + "iq") -# - "ique" ("iq" + "ue") -# Maximum length is 4. -# Example 2: - -# Input: arr = ["cha","r","act","ers"] -# Output: 6 -# Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). -# Example 3: - -# Input: arr = ["abcdefghijklmnopqrstuvwxyz"] -# Output: 26 -# Explanation: The only string in arr has all 26 characters. - - -# Solution -> - -class Solution: - def maxLength(self, arr: List[str]) -> int: - - # [1] we should first throw away all strings with any - # duplicate characters; strings with all unique - # characters are the subsets of the alphabet, - # thus, can be stored using 'set' - unique = [] - for s in arr: - u = set(s) - if len(u) == len(s): unique.append(u) - - # [2] now start with an empty concatenation and iteratively - # increase its length by trying to add more strings - concat = [set()] - for u in unique: - for c in concat: - if not c & u: - concat.append(c | u) - - return max(len(cc) for cc in concat) \ No newline at end of file diff --git a/Strings/no_of_substrings_with_1s.py b/Strings/no_of_substrings_with_1s.py deleted file mode 100644 index 11ffe852..00000000 --- a/Strings/no_of_substrings_with_1s.py +++ /dev/null @@ -1,104 +0,0 @@ -# ---------------------------------------------------------------- -# 1513. Number of Substrings With Only 1s -# ---------------------------------------------------------------- - -""" -Input -> A binary string -Output -> An integer - -The goal of the problem is to find out the number of substrings in the -given binary string that consists of 1's only. For example : - -Sample Input: - -a) Input 1 = "0110111" - Output 1 = 9 - There are 9 substrings in total with only 1's characters - -b) Input 2 = "101" - Output 2 = 2 - There are 2 substrings in total with only 1's characters - -c) Input 3 = "1" - Output 3 = 1 - There is only one substring in this string that contains 1 - -d) Input 4 = "111111" - Output 4 = 21 - There is only 12 substrings in this string that contain only 1's - - -How to tackle this problem? - -Solution 1) - -This is the brute force solution and is extremely simple. We look at all -the substrings and simply decide which one ha only 1's by iterating -over each individual substring. This however is a tedious solution and -not very optimised. The time complexity for this solution would be -O(N^3). This is not a good solution. However, it is the first solution that -comes to mind. - -Solution 2) - -We can take advantage of a built in python function. This function is -str.slpit(), it splits a string into an array depending upon the breakpoint -that we provide it. What we can do is, split the string by 0's. This results -in an array that consists of all the substrings in the array that -consist of 1's only. We can now start to notice a pattern with. - -If Input = "1" Output = 1 -If Input = "11" Output = 2 -If Input = "111" Output = 6 -If Input = "1111" Output = 10 -If Input = "11111" Output = 15 - -By looking at the above results we can state that the number of -substrings in a given string can be calculated by using ((n*(n+1) )/ 2) - -This leads to another fact, that we dont really need to find all of the -substrings to find their total. The time complexity for this approach will be -O(N) which is much better than ourbrute force approach. - -**Note : This approach can be used in any other language as well - -Coding the second approach - -""" - - -class Solution: - def numSub(self, s: str) -> int: - # This will get us all the subtrings that contain 1's only - substrings = s.split("0") - - sub_sum = 0 - for substring in substrings: - sub_sum += len(substring) * (len(substring) + 1) // 2 - # Implementing the formula that we derived above - return sub_sum - # finally return the sum - - -""" -Another problem that we face is when we try to run the above code -on leetcode, it will not pass all the test cases. - -Short Answer: The numbers get too big and it simply overflows. -To avoid this overflow, we use the modulo operator. - -Long Answer: We use the expression -> num % (10 ** 9 + 7) calculates the remainder of -num divided by 10 ** 9 + 7. The value 10 ** 9 + 7 is a large constant that -is used as the modulo. The purpose of taking the modulo is to avoid large numbers that might -overflow the maximum value that can be stored in an integer data type. -When the result of an operation is larger than the maximum value that can -be stored in an integer, the result wraps around to a negative value. -Taking the modulo avoids this issue by reducing the result to a value that -can be stored in an integer data type. - - -To fix this issue simply replace the return statement with the below line - -return sub_sum % (10 ** 9 + 7) - -""" From 1b4f4458615eaa07a6e26a699a42be154fd63db2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:15:37 +0530 Subject: [PATCH 1303/1894] update link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2261f459..4bd62e8a 100644 --- a/README.md +++ b/README.md @@ -547,7 +547,7 @@ The pointers can be used to iterate the data structure in one or both directions - Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) -- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.js) +- Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.js) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.java) # Pattern 2: Fast and Slow Pointers From cf6b32a7e86d336d75e7379f3f3e75b4550192c5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:22:40 +0530 Subject: [PATCH 1304/1894] move to appropriate folder --- Arrays/coin_change_greedy.go => Greedy/coin_change.go | 0 Greedy/{CoinChange.java => coin_change.java} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Arrays/coin_change_greedy.go => Greedy/coin_change.go (100%) rename Greedy/{CoinChange.java => coin_change.java} (100%) diff --git a/Arrays/coin_change_greedy.go b/Greedy/coin_change.go similarity index 100% rename from Arrays/coin_change_greedy.go rename to Greedy/coin_change.go diff --git a/Greedy/CoinChange.java b/Greedy/coin_change.java similarity index 100% rename from Greedy/CoinChange.java rename to Greedy/coin_change.java From 1825e22050f0762c840f7e847774d7cafd784877 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:23:47 +0530 Subject: [PATCH 1305/1894] update ceasar cipher --- Arrays/ceaser_cipher.go | 42 +++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/Arrays/ceaser_cipher.go b/Arrays/ceaser_cipher.go index f730fe9b..00784acc 100644 --- a/Arrays/ceaser_cipher.go +++ b/Arrays/ceaser_cipher.go @@ -12,23 +12,29 @@ */ package main -import "fmt" - +// CaesarCipherEncryptor takes a string and a key (integer) as input and returns +// a new string obtained by shifting each character of the input string by the +// key number of positions to the right in the alphabet, wrapping around if necessary. func CaesarCipherEncryptor(str string, key int) string { - key = key % 26 // mod with 26 just in case the key is not bigger - result := "" - // find out ascii value if its greater than ascii value of 'z' then reduce 26 from value - for i := 0; i < len(str); i++ { - asciiValue := int(str[i]) + key - if asciiValue > 122 { - asciiValue -= 26 - } - result += string(asciiValue) - } - return result + // Calculate the shift amount and offset value + shift, offset := rune(key % 26), rune(26) + + // Convert the input string to a rune slice (for ease of manipulation) + runes := []rune(str) + + // Iterate over each character in the rune slice + for i, char := range runes { + // If the character is a lowercase letter and shifting it will still be within the lowercase range + if char >= 'a' && char + shift <= 'z' { + char += shift + } else { + // If the character is outside of the lowercase range after shifting, wrap it around + char += shift - offset + } + // Update the character in the rune slice + runes[i] = char + } + + // Convert the resulting rune slice back to a string and return it + return string(runes) } - -func main() { - msg := CaesarCipherEncryptor("abcadzxc", 10) - fmt.Println(msg) -} \ No newline at end of file From d1b49c469feb68cbd0dac395626dd65715791e6f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:25:16 +0530 Subject: [PATCH 1306/1894] add explanation --- Arrays/ceaser_cipher.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Arrays/ceaser_cipher.go b/Arrays/ceaser_cipher.go index 00784acc..06130cc6 100644 --- a/Arrays/ceaser_cipher.go +++ b/Arrays/ceaser_cipher.go @@ -9,6 +9,30 @@ Sample Input : abz key: 3 Output: dec + + Explanation: + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in + the alphabet, wrapping around if necessary. + + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + value is calculated by taking 26, which is the number of letters in the alphabet. + + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + character in a programming language. The rune type is used to represent characters in Go. + + The function then iterates over each character in the rune slice. For each character, the function checks + + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the + function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. + + The function then updates the character in the rune slice. + + The function then converts the resulting rune slice back to a string and returns it. */ package main From 6d22bdcc9fbff31a5d3c41c0650be5f5d7cfb3ef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:25:51 +0530 Subject: [PATCH 1307/1894] add time and space complexity --- Arrays/ceaser_cipher.go | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/Arrays/ceaser_cipher.go b/Arrays/ceaser_cipher.go index 06130cc6..beac8685 100644 --- a/Arrays/ceaser_cipher.go +++ b/Arrays/ceaser_cipher.go @@ -11,28 +11,36 @@ Output: dec Explanation: - - The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string - obtained by shifting each character of the input string by the key number of positions to the right in + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in the alphabet, wrapping around if necessary. - The function first calculates the shift amount and offset value. The shift amount is calculated by taking - the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset value is calculated by taking 26, which is the number of letters in the alphabet. - The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single character in a programming language. The rune type is used to represent characters in Go. - The function then iterates over each character in the rune slice. For each character, the function checks + The function then iterates over each character in the rune slice. For each character, the function checks - if the character is a lowercase letter and if shifting it will still be within the lowercase range. - - If the character is a lowercase letter and shifting it will still be within the lowercase range, the + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. The function then updates the character in the rune slice. The function then converts the resulting rune slice back to a string and returns it. + + The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function iterates over each character in the input string, performing a constant amount + of work for each character. + + The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function creates a new rune slice to store the encrypted string. The rune slice is the + same size as the input string, so the space complexity is O(n). */ package main From 3acda2d73dfd5074128afd5a946d5c00b2d54c02 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:29:46 +0530 Subject: [PATCH 1308/1894] add ceasar cipher in c++ --- Arrays/ceaser_cipher.cpp | 92 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Arrays/ceaser_cipher.cpp diff --git a/Arrays/ceaser_cipher.cpp b/Arrays/ceaser_cipher.cpp new file mode 100644 index 00000000..f1c57495 --- /dev/null +++ b/Arrays/ceaser_cipher.cpp @@ -0,0 +1,92 @@ +/* + Given a non-empty string of lowercase letters and a non-negative integer + representing a key, write a function that returns a new string obtained by + shifting every letter in the input string by k positions in the alphabet, + where k is the key. + + Note that letters should "wrap" around the alphabet; in other words, the + letter z shifted by one returns the letter a + + Sample Input : abz key: 3 + Output: dec + + Explanation: + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in + the alphabet, wrapping around if necessary. + + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + value is calculated by taking 26, which is the number of letters in the alphabet. + + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + character in a programming language. The rune type is used to represent characters in Go. + + The function then iterates over each character in the rune slice. For each character, the function checks + + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the + function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. + + The function then updates the character in the rune slice. + + The function then converts the resulting rune slice back to a string and returns it. + + The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function iterates over each character in the input string, performing a constant amount + of work for each character. + + The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function creates a new rune slice to store the encrypted string. The rune slice is the + same size as the input string, so the space complexity is O(n). +*/ +// C++ + +#include +#include + +using namespace std; + +string CaesarCipherEncryptor(string str, int key) { + // Calculate the shift amount and offset value + int shift = key % 26; + int offset = 26; + + // Convert the input string to a vector of characters + vector chars(str.begin(), str.end()); + + // Iterate over each character in the vector + for (int i = 0; i < chars.size(); i++) { + // If the character is a lowercase letter and shifting it will still be within the lowercase range + if (chars[i] >= 'a' && chars[i] + shift <= 'z') { + chars[i] += shift; + } else { + // If the character is outside of the lowercase range after shifting, wrap it around + chars[i] += shift - offset; + } + } + + // Convert the resulting vector of characters back to a string and return it + return string(chars.begin(), chars.end()); +} + +int main() { + // Get the input string and key from the user + string str; + cout << "Enter a string: "; + cin >> str; + + int key; + cout << "Enter a key: "; + cin >> key; + + // Encrypt the string using the Caesar cipher + string encrypted_str = CaesarCipherEncryptor(str, key); + + // Print the encrypted string + cout << "Encrypted string: " << encrypted_str << endl; + + return 0; +} From 386ba121adbe05dcbd7ed1f8e3b96c85a7be4715 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:29:56 +0530 Subject: [PATCH 1309/1894] update ceasar cipher in go --- Arrays/ceaser_cipher.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Arrays/ceaser_cipher.go b/Arrays/ceaser_cipher.go index beac8685..00890d17 100644 --- a/Arrays/ceaser_cipher.go +++ b/Arrays/ceaser_cipher.go @@ -1,16 +1,16 @@ /* - Given a non-empty string of lowercase letters and a non-negative integer - representing a key, write a function that returns a new string obtained by - shifting every letter in the input string by k positions in the alphabet, - where k is the key. + Given a non-empty string of lowercase letters and a non-negative integer + representing a key, write a function that returns a new string obtained by + shifting every letter in the input string by k positions in the alphabet, + where k is the key. - Note that letters should "wrap" around the alphabet; in other words, the - letter z shifted by one returns the letter a + Note that letters should "wrap" around the alphabet; in other words, the + letter z shifted by one returns the letter a - Sample Input : abz key: 3 - Output: dec + Sample Input : abz key: 3 + Output: dec - Explanation: + Explanation: The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string obtained by shifting each character of the input string by the key number of positions to the right in From 600972dd1627455815a22f93ba20207262f98ae6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:30:04 +0530 Subject: [PATCH 1310/1894] add ceasar cipher in java --- Arrays/ceaser_cipher.java | 89 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Arrays/ceaser_cipher.java diff --git a/Arrays/ceaser_cipher.java b/Arrays/ceaser_cipher.java new file mode 100644 index 00000000..ede0790f --- /dev/null +++ b/Arrays/ceaser_cipher.java @@ -0,0 +1,89 @@ +/* + Given a non-empty string of lowercase letters and a non-negative integer + representing a key, write a function that returns a new string obtained by + shifting every letter in the input string by k positions in the alphabet, + where k is the key. + + Note that letters should "wrap" around the alphabet; in other words, the + letter z shifted by one returns the letter a + + Sample Input : abz key: 3 + Output: dec + + Explanation: + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in + the alphabet, wrapping around if necessary. + + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + value is calculated by taking 26, which is the number of letters in the alphabet. + + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + character in a programming language. The rune type is used to represent characters in Go. + + The function then iterates over each character in the rune slice. For each character, the function checks + + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the + function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. + + The function then updates the character in the rune slice. + + The function then converts the resulting rune slice back to a string and returns it. + + The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function iterates over each character in the input string, performing a constant amount + of work for each character. + + The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function creates a new rune slice to store the encrypted string. The rune slice is the + same size as the input string, so the space complexity is O(n). +*/ +// Java + +import java.util.Scanner; + +public class CaesarCipherEncryptor { + + public static String encrypt(String str, int key) { + // Calculate the shift amount and offset value + int shift = key % 26; + int offset = 26; + + // Convert the input string to a char array + char[] chars = str.toCharArray(); + + // Iterate over each character in the char array + for (int i = 0; i < chars.length; i++) { + // If the character is a lowercase letter and shifting it will still be within the lowercase range + if (chars[i] >= 'a' && chars[i] + shift <= 'z') { + chars[i] += shift; + } else { + // If the character is outside of the lowercase range after shifting, wrap it around + chars[i] += shift - offset; + } + } + + // Convert the resulting char array back to a string and return it + return new String(chars); + } + + public static void main(String[] args) { + // Get the input string and key from the user + Scanner scanner = new Scanner(System.in); + System.out.println("Enter a string: "); + String str = scanner.nextLine(); + + System.out.println("Enter a key: "); + int key = scanner.nextInt(); + + // Encrypt the string using the Caesar cipher + String encrypted_str = encrypt(str, key); + + // Print the encrypted string + System.out.println("Encrypted string: " + encrypted_str); + } +} From 733f137ee2e164e0e28df83fee96086310ee6ade Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:30:10 +0530 Subject: [PATCH 1311/1894] add ceasar cipher in js --- Arrays/ceaser_cipher.js | 73 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Arrays/ceaser_cipher.js diff --git a/Arrays/ceaser_cipher.js b/Arrays/ceaser_cipher.js new file mode 100644 index 00000000..922c4075 --- /dev/null +++ b/Arrays/ceaser_cipher.js @@ -0,0 +1,73 @@ +/* + Given a non-empty string of lowercase letters and a non-negative integer + representing a key, write a function that returns a new string obtained by + shifting every letter in the input string by k positions in the alphabet, + where k is the key. + + Note that letters should "wrap" around the alphabet; in other words, the + letter z shifted by one returns the letter a + + Sample Input : abz key: 3 + Output: dec + + Explanation: + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in + the alphabet, wrapping around if necessary. + + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + value is calculated by taking 26, which is the number of letters in the alphabet. + + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + character in a programming language. The rune type is used to represent characters in Go. + + The function then iterates over each character in the rune slice. For each character, the function checks + + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the + function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. + + The function then updates the character in the rune slice. + + The function then converts the resulting rune slice back to a string and returns it. + + The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function iterates over each character in the input string, performing a constant amount + of work for each character. + + The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function creates a new rune slice to store the encrypted string. The rune slice is the + same size as the input string, so the space complexity is O(n). +*/ +function caesarCipherEncryptor(str, key) { + // Calculate the shift amount and offset value + let shift = key % 26; + let offset = 26; + + // Convert the input string to a lowercase string + str = str.toLowerCase(); + + // Iterate over each character in the string + for (let i = 0; i < str.length; i++) { + // If the character is a letter and shifting it will still be within the lowercase range + if (str[i] >= "a" && str[i] + shift <= "z") { + str[i] += shift; + } else { + // If the character is outside of the lowercase range after shifting, wrap it around + str[i] += shift - offset; + } + } + + // Return the encrypted string + return str; +} + +// Example usage +let str = "Hello, world!"; +let key = 3; + +let encryptedStr = caesarCipherEncryptor(str, key); +console.log(encryptedStr); // Output: "Khoor, zloor!" From c166ee9b8c68413142c6bcc8a9df75e0de6b8b70 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 6 Jun 2023 22:30:18 +0530 Subject: [PATCH 1312/1894] add ceasar cipher in python --- Arrays/ceaser_cipher.py | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Arrays/ceaser_cipher.py diff --git a/Arrays/ceaser_cipher.py b/Arrays/ceaser_cipher.py new file mode 100644 index 00000000..9dd07531 --- /dev/null +++ b/Arrays/ceaser_cipher.py @@ -0,0 +1,66 @@ +''' + Given a non-empty string of lowercase letters and a non-negative integer + representing a key, write a function that returns a new string obtained by + shifting every letter in the input string by k positions in the alphabet, + where k is the key. + + Note that letters should "wrap" around the alphabet; in other words, the + letter z shifted by one returns the letter a + + Sample Input : abz key: 3 + Output: dec + + Explanation: + + The CaesarCipherEncryptor function takes a string and a key (integer) as input and returns a new string + obtained by shifting each character of the input string by the key number of positions to the right in + the alphabet, wrapping around if necessary. + + The function first calculates the shift amount and offset value. The shift amount is calculated by taking + the key modulo 26, which ensures that the shift amount is always within the range of 0 to 25. The offset + value is calculated by taking 26, which is the number of letters in the alphabet. + + The function then converts the input string to a rune slice (for ease of manipulation). A rune is a single + character in a programming language. The rune type is used to represent characters in Go. + + The function then iterates over each character in the rune slice. For each character, the function checks + + if the character is a lowercase letter and if shifting it will still be within the lowercase range. + + If the character is a lowercase letter and shifting it will still be within the lowercase range, the + function simply adds the shift amount to the character. If the character is outside of the lowercase range after shifting, the function wraps it around by adding the shift amount - offset to the character. + + The function then updates the character in the rune slice. + + The function then converts the resulting rune slice back to a string and returns it. + + The time complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function iterates over each character in the input string, performing a constant amount + of work for each character. + + The space complexity of the CaesarCipherEncryptor function is O(n), where n is the length of the input string. + This is because the function creates a new rune slice to store the encrypted string. The rune slice is the + same size as the input string, so the space complexity is O(n). +''' +# Python + +def caesar_cipher_encryptor(str, key): + # Calculate the shift amount and offset value + shift = key % 26 + offset = 26 + + # Convert the input string to a list of characters + chars = list(str) + + # Iterate over each character in the list + for i in range(len(chars)): + # If the character is a lowercase letter and shifting it will still be within the lowercase range + if chars[i] >= 'a' and chars[i] + shift <= 'z': + chars[i] += shift + else: + # If the character is outside of the lowercase range after shifting, wrap it around + chars[i] += shift - offset + + # Convert the resulting list of characters back to a string and return it + return ''.join(chars) + From 35d3d92d7a1f15585fd84a03a30316cceff5b0c6 Mon Sep 17 00:00:00 2001 From: Anup Khismatrao Date: Wed, 7 Jun 2023 12:18:08 +0530 Subject: [PATCH 1313/1894] Update --- 2D Arrays (Matrix)/setMatrixZero.java | 109 +++++++++++--------------- 1 file changed, 45 insertions(+), 64 deletions(-) diff --git a/2D Arrays (Matrix)/setMatrixZero.java b/2D Arrays (Matrix)/setMatrixZero.java index ecf0b2cd..3fb28f41 100644 --- a/2D Arrays (Matrix)/setMatrixZero.java +++ b/2D Arrays (Matrix)/setMatrixZero.java @@ -14,22 +14,37 @@ | 0 0 0 | | 1 0 1 | --- Naive Approach for Set Matrix Zeroes +METHOD 1] Brute Force Approach for Set Matrix Zeroes Step 1. Create an array answer of size (n X m) and initialize every element as 1. Step 2. Traverse the matrix array row-wise and set the current row as 0 in answer array if the current row contains an element equals to 0. Step 3. Traverse the matrix array column-wise and set the current column as 0 in answer array if the current column contains an element equals to 0. Step 4. Now traverse the answer array, if the current element is 0, then set this element as 0 in a matrix array. Step 5. Return matrix array -Complexity Analysis +Complexity Analysis: Time Complexity = O(n * m) Space Complexity = O(n * m) where n is the number of rows in the matrix and m is the number of columns in the matrix. +METHOD 2] Optimal Approach for Set Matrix Zeroes +If we assume that -1, do not occur in the matrix array, then + +Step 1. Traverse the matrix array row-wise and set all the elements of current row which are not 0 as -1, if the current row contains an element equals to 0. +Step 2. Traverse the matrix array column-wise and set all the elements of the current column which are not 0 as -1, if the current column contains an element equals to 0. +Step 3. Again traverse the matrix and set all the elements that are -1 to 0. +Step 4. Return matrix array. + +Complexity Analysis: +Time Complexity = O(n * m) +Space Complexity = O(1) +where n is the number of rows in the matrix and m is the number of columns in the matrix. */ -/* + + public class setMatrixZero { - private static void setZeroes(int[][] matrix, int n, int m) { + + // Method 1] Brute Force Approach + private static void setZeroes_bruteForce(int[][] matrix, int n, int m) { int answer[][] = new int[n][m]; // Step 1 // Set all elements of answer array as 1 for (int i = 0; i < n; i++) { @@ -37,7 +52,7 @@ private static void setZeroes(int[][] matrix, int n, int m) { answer[i][j] = 1; // making each element as 1 } } - // Traverse row wise -- Step 2 + // Traverse row wise --> Step 2 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (matrix[i][j] == 0) { @@ -49,7 +64,7 @@ private static void setZeroes(int[][] matrix, int n, int m) { } } } - // Traverse column wise -- Step 3 + // Traverse column wise --> Step 3 for (int j = 0; j < m; j++) { for (int i = 0; i < n; i++) { if (matrix[i][j] == 0) { @@ -60,7 +75,7 @@ private static void setZeroes(int[][] matrix, int n, int m) { } } } - // Update the elements in matrix array -- Step 4 + // Update the elements in matrix array --> Step 4 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (answer[i][j] == 0) { @@ -69,51 +84,9 @@ private static void setZeroes(int[][] matrix, int n, int m) { } } } - public static void main(String[] args) { - // Example 1 - int[][] matrix = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; - int n = matrix.length; - int m = matrix[0].length; - setZeroes(matrix, n, m); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - System.out.print(matrix[i][j] + " "); - } - System.out.println(); - } - // Example 2 - matrix = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; - n = matrix.length; - m = matrix[0].length; - - setZeroes(matrix, n, m); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - System.out.print(matrix[i][j] + " "); - } - System.out.println(); - } - } -} -*/ -/* --- Optimal Approach for Set Matrix Zeroes -If we assume that -1, do not occur in the matrix array, then - -Step 1. Traverse the matrix array row-wise and set all the elements of current row which are not 0 as -1, if the current row contains an element equals to 0. -Step 2. Traverse the matrix array column-wise and set all the elements of the current column which are not 0 as -1, if the current column contains an element equals to 0. -Step 3. Again traverse the matrix and set all the elements that are -1 to 0. -Step 4. Return matrix array. - -Complexity Analysis -Time Complexity = O(n * m) -Space Complexity = O(1) -where n is the number of rows in the matrix and m is the number of columns in the matrix. -*/ - -public class setMatrixZero { - private static void setZeroes(int[][] matrix, int n, int m) { + // Method 2] Optimal Approach + private static void setZeroes_optimalMethod(int[][] matrix, int n, int m) { // Traverse row wise for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { @@ -150,26 +123,34 @@ private static void setZeroes(int[][] matrix, int n, int m) { } } } + public static void main(String[] args) { - // Example 1 - int[][] matrix = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; - int n = matrix.length; - int m = matrix[0].length; - setZeroes(matrix, n, m); + // Example using Method 1 - Brute Force + int[][] matrix1 = new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; // Defining Matrix + int n = matrix1.length; + int m = matrix1[0].length; + + setZeroes_bruteForce(matrix1, n, m); + for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { - System.out.print(matrix[i][j] + " "); + System.out.print(matrix1[i][j] + " "); // Printing Matrix } System.out.println(); } - // Example 2 - matrix = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; - n = matrix.length; - m = matrix[0].length; - setZeroes(matrix, n, m); - for (int i = 0; i < n; i++) { + + System.out.println("-----------------"); + + // Example using Method 2 - Optimal + int[][] matrix2 = new int[][] {{0, 0, 6, 0}, {1, 4, 9, 0}, {1, 8, 1, 8}}; // Defining Matrix + n = matrix2.length; + m = matrix2[0].length; + + setZeroes_optimalMethod(matrix2, n, m); + + for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { - System.out.print(matrix[i][j] + " "); + System.out.print(matrix2[i][j] + " "); // Printing Matrix } System.out.println(); } From b596414057fa782a5dddbf1a1cf15283ed5b7c5a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 8 Jun 2023 22:29:58 +0530 Subject: [PATCH 1314/1894] remove reverse integer --- Arrays/add_reverse_integer.cpp | 46 ---------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 Arrays/add_reverse_integer.cpp diff --git a/Arrays/add_reverse_integer.cpp b/Arrays/add_reverse_integer.cpp deleted file mode 100644 index a735f72d..00000000 --- a/Arrays/add_reverse_integer.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. - -Assume the environment does not allow you to store 64-bit integers (signed or unsigned). - - - -Example 1: - -Input: x = 123 -Output: 321 -Example 2: - -Input: x = -123 -Output: -321 -*/ - -/* - -APPROACH: The reverse function takes an integer as input and returns the reversed integer. The function first initializes a variable to store the reversed integer and then iterates over each digit of the input integer. In each iteration, the function extracts the rightmost digit of the input integer, checks if multiplying the reversed integer by 10 and adding the rightmost digit will cause integer overflow or underflow, adds the rightmost digit to the reversed integer, and removes the rightmost digit from the input integer. Finally, the function returns the reversed integer. - -Time Complexity: -The time complexity of the reverse function is O(log(x)), where x is the input integer. This is because the function needs to iterate over each digit of the input integer, which is proportional to the logarithm of the integer. - -Space Complexity: -The space complexity of the reverse function is O(1), because it only uses a constant amount of additional space to store the reversed integer and the remainder. - -*/ - -class Solution { - public boolean validPalindrome(String s) { - int i=0,j=s.length()-1; // initialize two pointers, i and j to the start and end of the string respectively - while(i Date: Thu, 8 Jun 2023 22:33:15 +0530 Subject: [PATCH 1315/1894] modify three largest numbers --- Arrays/find_three_largest_numbers.java | 105 +++++++++++++++++++------ 1 file changed, 81 insertions(+), 24 deletions(-) diff --git a/Arrays/find_three_largest_numbers.java b/Arrays/find_three_largest_numbers.java index 05007a09..edf485ef 100644 --- a/Arrays/find_three_largest_numbers.java +++ b/Arrays/find_three_largest_numbers.java @@ -1,36 +1,93 @@ /* + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. -Problem Statement : + Explanation: -Write a function that takes in an array of at least three integers and, without sorting the input array, returns a sorted array of the three largest integers in the input array. + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. -Explanation: + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. -Here's how the function works: + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. -1. We create a new array result with three elements to store the three largest integers. -2. We loop through the input array, and for each integer, we compare it to the largest integer in result. -3. If the integer is larger than the largest integer in result, we shift the elements in result down one position and add the integer to the end. -4. If the integer is larger than the second largest integer in result, we shift the elements in result down one position starting from the second position and add the integer to the second position. -5. If the integer is larger than the third largest integer in result, we add the integer to the third position. -6. At the end of the loop, result will contain the three largest integers in the input array, sorted in descending order. + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. + + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. + + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array */ -public static int[] findThreeLargest(int[] array) { - int[] result = new int[3]; - for (int num : array) { - if (num > result[2]) { - result[0] = result[1]; - result[1] = result[2]; - result[2] = num; - } else if (num > result[1]) { - result[0] = result[1]; - result[1] = num; - } else if (num > result[0]) { - result[0] = num; +import java.util.Arrays; + +public class Main { + // Function to find the three largest numbers in the input array + public static int[] findThreeLargestNumbers(int[] array) { + // Initialize an array to hold the three largest numbers, starting with negative infinity + int[] triplets = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE}; + + // Iterate through each number in the input array + for (int num : array) { + // Call the updateLargest function to determine if the number should be included in the triplet + updateLargest(triplets, num); } + + // Return the array containing the three largest numbers + return triplets; } - return result; -} + // Function to update the triplet if the input number is larger than any of its elements + private static void updateLargest(int[] triplets, int num) { + // If the number is larger than the third-largest element in the triplet + if (num > triplets[2]) { + // Shift the other elements to make room and add the number as the new third-largest element + shiftAndUpdate(triplets, num, 2); + } + // Otherwise, if the number is larger than the second-largest element + else if (num > triplets[1]) { + // Shift and update the triplet accordingly + shiftAndUpdate(triplets, num, 1); + } + // Otherwise, if the number is larger than the first-largest element + else if (num > triplets[0]) { + // Shift and update the triplet accordingly + shiftAndUpdate(triplets, num, 0); + } + } + + // Function to shift the elements of the triplet and add the new number to the specified index + private static void shiftAndUpdate(int[] triplets, int num, int idx) { + // Iterate through the elements of the triplet + for (int i = 0; i < idx + 1; i++) { + // If the loop reaches the specified index, add the new number to the triplet + if (i == idx) { + triplets[i] = num; + } + // Otherwise, shift the elements to the right + else { + triplets[i] = triplets[i + 1]; + } + } + } + + // Main function to test the findThreeLargestNumbers function + public static void main(String[] args) { + int[] array = {1, 5, 2, 9, 10, 3}; + int[] result = findThreeLargestNumbers(array); + System.out.println(Arrays.toString(result)); + } +} From 7aeee1b2f337d5fad38a9654d8d37466d39ca773 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 8 Jun 2023 22:35:13 +0530 Subject: [PATCH 1316/1894] add three largest numbers in py --- Arrays/find_three_largest_numbers.py | 77 ++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Arrays/find_three_largest_numbers.py diff --git a/Arrays/find_three_largest_numbers.py b/Arrays/find_three_largest_numbers.py new file mode 100644 index 00000000..dfc2d9f4 --- /dev/null +++ b/Arrays/find_three_largest_numbers.py @@ -0,0 +1,77 @@ +''' + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. + + Explanation: + + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. + + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. + + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. + + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. + + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. + + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. + + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array + +''' +def find_three_largest_numbers(array): + # Initialize a list to hold the three largest numbers, starting with negative infinity + triplets = [float('-inf'), float('-inf'), float('-inf')] + + # Iterate through each number in the input array + for num in array: + # Call the update_largest function to determine if the number should be included in the triplet + update_largest(triplets, num) + + # Return the list containing the three largest numbers + return triplets + + +def update_largest(triplets, num): + # If the number is larger than the third-largest element in the triplet + if num > triplets[2]: + # Shift the other elements to make room and add the number as the new third-largest element + shift_and_update(triplets, num, 2) + # Otherwise, if the number is larger than the second-largest element + elif num > triplets[1]: + # Shift and update the triplet accordingly + shift_and_update(triplets, num, 1) + # Otherwise, if the number is larger than the first-largest element + elif num > triplets[0]: + # Shift and update the triplet accordingly + shift_and_update(triplets, num, 0) + + +def shift_and_update(triplets, num, idx): + # Iterate through the elements of the triplet + for i in range(idx + 1): + # If the loop reaches the specified index, add the new number to the triplet + if i == idx: + triplets[i] = num + # Otherwise, shift the elements to the right + else: + triplets[i] = triplets[i + 1] + + +# Test the find_three_largest_numbers function +array = [1, 5, 2, 9, 10, 3] +result = find_three_largest_numbers(array) +print(result) From 5adfc9549e0f19571ba76a0520895eb101f61f03 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 8 Jun 2023 22:37:17 +0530 Subject: [PATCH 1317/1894] modify comments --- Arrays/find_three_largest_numbers.go | 47 ++++++++++++++-------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/Arrays/find_three_largest_numbers.go b/Arrays/find_three_largest_numbers.go index ebeeadd7..9491bb36 100644 --- a/Arrays/find_three_largest_numbers.go +++ b/Arrays/find_three_largest_numbers.go @@ -1,34 +1,35 @@ /* - Write a function that takes in an array of at least three integers and, - without sorting the input array, returns a sorted array of the three largest - integers in the input array. -*/ -/* Explanation - This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and - returns an array of the three largest integers in the input array. + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. + + Explanation: + + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. - The `triplets` array is initialized with three smallest possible values. Then, the function iterates through - the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with - the current number if it is larger than one of the values in the array. + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. - The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater - than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the - `triplets` array with the current number at the third index. + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. - If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. - If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at - the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` - array, it checks if `num` is greater than the first value in the `triplets` array. + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. - If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at - the first index. + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. - The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the - `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches - the `idx` index. Then it updates the value at the `idx` index with the current number `num`. + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. - Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array */ package main From 272fb6b4c07261df802ffa3647b8f82c53534bfc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 8 Jun 2023 22:37:28 +0530 Subject: [PATCH 1318/1894] modify three largest numbers in java --- Arrays/find_three_largest_integers.js | 132 +++++++++++++------------- 1 file changed, 67 insertions(+), 65 deletions(-) diff --git a/Arrays/find_three_largest_integers.js b/Arrays/find_three_largest_integers.js index 750ed1f0..54cedbbe 100644 --- a/Arrays/find_three_largest_integers.js +++ b/Arrays/find_three_largest_integers.js @@ -1,81 +1,83 @@ /* -Write a function that takes in an array of at least three integers and, -without sorting the input array, returns a sorted array of the three largest integers in the input array. + Write a function that takes in an array of at least three integers and, + without sorting the input array, returns a sorted array of the three largest + integers in the input array. + Explanation: -Approach: + This code defines a function called `FindThreeLargestNumbers` that takes an array of integers as input and + returns an array of the three largest integers in the input array. -Before implementing the task logic the array will be checked to see if it meets the criteria. -Here the input array will be checked to see if it´s at least 3 elements big and if it -only contains integers. + The `triplets` array is initialized with three smallest possible values. Then, the function iterates through + the input array using a `for` loop and calls the `updateLargest` function to update the `triplets` array with + the current number if it is larger than one of the values in the array. -After that the logic is implemented. -Because the given array should not be sorted for this task, the used logic works as following: -1. Initialize a result array with 3 values, each of these 3 is initialized as -Infinity -2. Check if first element of array is bigger than the third result value - 2.1 If value is bigger set new value (will be true for the first check as initialized with -Infinity) - 2.2 shift current numbers in result array - 2.3 checks if element is bigger than value 2, and also value 1 - following above logic -3. Sorty the result array in descending order and console logs the result. -*/ + The `updateLargest` function takes two arguments: `triplets` and `num`. It first checks if `num` is greater + than the third value in the `triplets` array. If so, it calls the `shiftAndUpdate` function to update the + `triplets` array with the current number at the third index. -function findThreeLargestInteger(array) { + If `num` is not greater than the third value in the `triplets` array, it checks if `num` is greater than the second value in the `triplets` array. - /************************************************************************ - * This block checks if given array matches the criteria * - ************************************************************************/ - let arrayLength = 0; - let onlyIntegers = true; - // iterate over given array and check each element - array.forEach(element => { - // is element an integer - if (!Number.isInteger(element)) { - onlyIntegers = false; - } - // count length of array - arrayLength++; - }); + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the second index. Finally, if `num` is not greater than either the third or second value in the `triplets` + array, it checks if `num` is greater than the first value in the `triplets` array. + If so, it calls the `shiftAndUpdate` function to update the `triplets` array with the current number at + the first index. - /************************************************************************ - * Implementing the task logic * - ************************************************************************/ - if (onlyIntegers && arrayLength >= 3) { - // initialize result array with -Infinite - let result = [-Infinity, -Infinity, -Infinity]; + The `shiftAndUpdate` function takes three arguments: `triplets`, `num`, and `idx`. It iterates through the + `triplets` array using a `for` loop and shifts each value to the left by one position until it reaches + the `idx` index. Then it updates the value at the `idx` index with the current number `num`. - // Loop through the input array - for (const num of array) { - // Check if the current number is larger than the third largest number - if (num > result[2]) { - // Shift the current numbers down the result array - result[0] = result[1]; - result[1] = result[2]; - result[2] = num; - } else if (num > result[1]) { - // Shift the current numbers down the result array - result[0] = result[1]; - result[1] = num; - } else if (num > result[0]) { - // Shift the current number down the result array - result[0] = num; - } - } - // sorts the result in descending order (big to small) - result.sort(function (a, b) { return b - a }); - console.log(result); + Time and Space complexity : O(n) time | O(1) space - where n is the length of the input array +*/ +function findThreeLargestNumbers(array) { + // Initialize an array to hold the three largest numbers, starting with negative infinity + let triplets = [-Infinity, -Infinity, -Infinity]; - } else { - console.log("The passed array does not match the expected criteria."); - } + // Iterate through each number in the input array + for (let num of array) { + // Call the updateLargest function to determine if the number should be included in the triplet + updateLargest(triplets, num); + } + // Return the array containing the three largest numbers + return triplets; } -const testArray = [5, -3, 5, 100, 3, 55, 999, -18]; -const functionCheck = findThreeLargestInteger(testArray); // prints [999, 100, 55] to console +function updateLargest(triplets, num) { + // If the number is larger than the third-largest element in the triplet + if (num > triplets[2]) { + // Shift the other elements to make room and add the number as the new third-largest element + shiftAndUpdate(triplets, num, 2); + } + // Otherwise, if the number is larger than the second-largest element + else if (num > triplets[1]) { + // Shift and update the triplet accordingly + shiftAndUpdate(triplets, num, 1); + } + // Otherwise, if the number is larger than the first-largest element + else if (num > triplets[0]) { + // Shift and update the triplet accordingly + shiftAndUpdate(triplets, num, 0); + } +} -const arrayToShort = [100, 999]; -const unctionCheck1 = findThreeLargestInteger(arrayToShort); // prints "The passed array does not match the expected criteria." to console +function shiftAndUpdate(triplets, num, idx) { + // Iterate through the elements of the triplet + for (let i = 0; i <= idx; i++) { + // If the loop reaches the specified index, add the new number to the triplet + if (i === idx) { + triplets[i] = num; + } + // Otherwise, shift the elements to the right + else { + triplets[i] = triplets[i + 1]; + } + } +} -const arrayNoInt = [100, 999, 8.5]; -const unctionCheck2 = findThreeLargestInteger(arrayNoInt); // prints "The passed array does not match the expected criteria." to console \ No newline at end of file +// Test the findThreeLargestNumbers function +const array = [1, 5, 2, 9, 10, 3]; +const result = findThreeLargestNumbers(array); +console.log(result); From 0be852a8b59f912b963d78bb74f1335a074a6380 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:19:03 +0530 Subject: [PATCH 1319/1894] remove good pairs and find First and Last Position --- ...ast_position_ofELement_inSorted_array.java | 95 ------------------- Arrays/Good_pairs.cpp | 64 ------------- 2 files changed, 159 deletions(-) delete mode 100644 Arrays/First_last_position_ofELement_inSorted_array.java delete mode 100644 Arrays/Good_pairs.cpp diff --git a/Arrays/First_last_position_ofELement_inSorted_array.java b/Arrays/First_last_position_ofELement_inSorted_array.java deleted file mode 100644 index 5a6bbecd..00000000 --- a/Arrays/First_last_position_ofELement_inSorted_array.java +++ /dev/null @@ -1,95 +0,0 @@ - -/** - * Problem :- Find First and Last Position of Element in Sorted Array - https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ - - * Problem Statement:- - - Given an array of integers nums sorted in non-decreasing order, - find the starting and ending position of a given target value. - - If target is not found in the array, return [-1, -1]. - - You must write an algorithm with O(log n) runtime complexity. - - * SAMPLE I/O - Input: nums = [5,7,7,8,8,10], target = 8 - Output: [3,4] - - * - */ - -/** - * APPROACH :- Binary Search - - 1. We make a function 'BS' that takes the input [nums,target,indexfirst] , - where if indexfirst=true i.e we want the first element else the last element, - ans return an integer - - 2. For the first index: - In this function 'BS' it will Apply Binary Search, pass the Argument 'indexfirst'=true. - And if(nums[mid]==target),then we save the indx in a variable 'ans' and make end=mid-1; - this will happen till we reach the first occurence of the element - when the loop is over, - return the 'ans' at last, and store this in "arr[0]" - - - - 3. For the Last index: - Apply Binary Search, - pass the Argument 'indexfirst'=false. - And if(nums[mid]==target),then we save the indx in a variable 'ans' and make start=mid+1; - this will happen till we reach the last occurence of the element - when the loop is over - return the 'ans' at last, and store this in "arr[1]" - - Time Complexity :- O(log n) - Because of the application of binary search. - - Space Complexity :- O(1) - There is no extra space is used. - (the arr we return at last is always- arr.length==2, Hence Constant space ) - - */ - - - - -class Solution { - public int[] searchRange(int[] nums, int target) { - - int [] arr= {-1,-1};//return this if target is not found - arr[0]=BS(nums, target, true); - if(arr[0]==1) return arr; //means the target doesn't exist hence return {-1,-1} - - arr[1]=BS(nums, target, false); - - return arr; -} -static int BS(int []nums,int target,boolean indexfirst) { - int ans=-1;//potential ans - int start=0,end=nums.length-1; - while(start<=end) { - int mid=start+(end-start)/2; - - if(target>nums[mid]) { - start=mid+1; - } - - else if(target -using namespace std; - -int main() { - int n; - cin>>n; - vector v; - map m; - for(int i = 0; i < n; i++) { - int x; - cin >> x; - v.push_back(x); - m[x]++; - } - int count = 0; - for(auto it: m) - { - count = count + (it.second - 1) * (it.second) / 2; - } - cout << count << endl; - return 0; -} From 67ccdb50da9ee54e5a6bf13bc6934cf94216fc33 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:21:23 +0530 Subject: [PATCH 1320/1894] add ismonotonic in java --- Arrays/is_monotonic.java | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Arrays/is_monotonic.java diff --git a/Arrays/is_monotonic.java b/Arrays/is_monotonic.java new file mode 100644 index 00000000..5df0b3f3 --- /dev/null +++ b/Arrays/is_monotonic.java @@ -0,0 +1,44 @@ +/* + An array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing. + Mathematically, An array A is continuously increasing if for all i <= j, A[i] <= A[j]. + + The IsMonotonic function takes an array of integers and returns a boolean value indicating whether the array + is monotonic or not. A monotonic array is one in which the elements are either non-increasing or non-decreasing. + + The function works by initializing two boolean variables, isNonDecreasing and isNonIncreasing, to true. + It then iterates over the array from the first element to the second-to-last element, comparing each element to the next one. + + If the current element is less than the next element, it sets isNonDecreasing to false, indicating that the + array is not non-decreasing. If the current element is greater than the next element, it sets isNonIncreasing to false, + indicating that the array is not non-increasing. + + At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, + indicating that the array is monotonic. Otherwise, it returns false. + + O(n) time | O(1) space - where n is the length of the array +*/ +public class Main { + public static boolean isMonotonic(int[] array) { + boolean isNonDecreasing = true; // Assume the array is non-decreasing until we find a decreasing element + boolean isNonIncreasing = true; // Assume the array is non-increasing until we find an increasing element + for (int i = 1; i < array.length; i++) { + if (array[i] < array[i - 1]) { + // If the current element is less than the previous element, the array is not non-decreasing + isNonDecreasing = false; + } + if (array[i] > array[i - 1]) { + // If the current element is greater than the previous element, the array is not non-increasing + isNonIncreasing = false; + } + } + // Return true if the array is either non-decreasing or non-increasing + return isNonDecreasing || isNonIncreasing; + } + + public static void main(String[] args) { + int[] arr = { 1, 2, 3, 4, 5 }; + int[] arr2 = { 5, 4, 3, 2, 1 }; + System.out.println(isMonotonic(arr)); + System.out.println(isMonotonic(arr2)); + } +} From b4d4c0f0bff46a2f7706472138425df1d05d6867 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:21:51 +0530 Subject: [PATCH 1321/1894] add is monotonic in javascript --- Arrays/is_monotonic.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Arrays/is_monotonic.js diff --git a/Arrays/is_monotonic.js b/Arrays/is_monotonic.js new file mode 100644 index 00000000..fccdd243 --- /dev/null +++ b/Arrays/is_monotonic.js @@ -0,0 +1,38 @@ +/* + An array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing. + Mathematically, An array A is continuously increasing if for all i <= j, A[i] <= A[j]. + + The IsMonotonic function takes an array of integers and returns a boolean value indicating whether the array + is monotonic or not. A monotonic array is one in which the elements are either non-increasing or non-decreasing. + + The function works by initializing two boolean variables, isNonDecreasing and isNonIncreasing, to true. + It then iterates over the array from the first element to the second-to-last element, comparing each element to the next one. + + If the current element is less than the next element, it sets isNonDecreasing to false, indicating that the + array is not non-decreasing. If the current element is greater than the next element, it sets isNonIncreasing to false, + indicating that the array is not non-increasing. + + At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, + indicating that the array is monotonic. Otherwise, it returns false. + + O(n) time | O(1) space - where n is the length of the array +*/ +function isMonotonic(array) { + let isNonDecreasing = true; // Assume the array is non-decreasing until we find a decreasing element + let isNonIncreasing = true; // Assume the array is non-increasing until we find an increasing element + for (let i = 1; i < array.length; i++) { + if (array[i] < array[i - 1]) { + // If the current element is less than the previous element, the array is not non-decreasing + isNonDecreasing = false; + } + if (array[i] > array[i - 1]) { + // If the current element is greater than the previous element, the array is not non-increasing + isNonIncreasing = false; + } + } + // Return true if the array is either non-decreasing or non-increasing + return isNonDecreasing || isNonIncreasing; +} + +const arr = [1, 2, 3, 4, 5]; +const arr2 = [ From 5ba647378bbb1b35629ec6fc8b45675adae310c6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:22:16 +0530 Subject: [PATCH 1322/1894] add is monotonic in python --- Arrays/is_monotonic.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Arrays/is_monotonic.py diff --git a/Arrays/is_monotonic.py b/Arrays/is_monotonic.py new file mode 100644 index 00000000..d464bb1b --- /dev/null +++ b/Arrays/is_monotonic.py @@ -0,0 +1,36 @@ +''' + An array is said to be monotonic in nature if it is either continuously increasing or continuously decreasing. + Mathematically, An array A is continuously increasing if for all i <= j, A[i] <= A[j]. + + The IsMonotonic function takes an array of integers and returns a boolean value indicating whether the array + is monotonic or not. A monotonic array is one in which the elements are either non-increasing or non-decreasing. + + The function works by initializing two boolean variables, isNonDecreasing and isNonIncreasing, to true. + It then iterates over the array from the first element to the second-to-last element, comparing each element to the next one. + + If the current element is less than the next element, it sets isNonDecreasing to false, indicating that the + array is not non-decreasing. If the current element is greater than the next element, it sets isNonIncreasing to false, + indicating that the array is not non-increasing. + + At the end of the loop, the function returns true if either isNonDecreasing or isNonIncreasing is still true, + indicating that the array is monotonic. Otherwise, it returns false. + + O(n) time | O(1) space - where n is the length of the array +''' +def is_monotonic(array): + is_non_decreasing = True # Assume the array is non-decreasing until we find a decreasing element + is_non_increasing = True # Assume the array is non-increasing until we find an increasing element + for i in range(1, len(array)): + if array[i] < array[i - 1]: + # If the current element is less than the previous element, the array is not non-decreasing + is_non_decreasing = False + if array[i] > array[i - 1]: + # If the current element is greater than the previous element, the array is not non-increasing + is_non_increasing = False + # Return true if the array is either non-decreasing or non-increasing + return is_non_decreasing or is_non_increasing + +arr = [1, 2, 3, 4, 5] +arr2 = [5, 4, 3, 2, 1] +print(is_monotonic(arr)) +print(is_monotonic(arr2)) From 29b66ba737836f826aa47d656520996fb2b8460c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:24:46 +0530 Subject: [PATCH 1323/1894] remove dupl;icate file --- Arrays/Merge_sortedArrays.java | 73 ---------------------------------- Arrays/Monotonic_Array.cpp | 45 --------------------- 2 files changed, 118 deletions(-) delete mode 100644 Arrays/Merge_sortedArrays.java delete mode 100644 Arrays/Monotonic_Array.cpp diff --git a/Arrays/Merge_sortedArrays.java b/Arrays/Merge_sortedArrays.java deleted file mode 100644 index 7181e64c..00000000 --- a/Arrays/Merge_sortedArrays.java +++ /dev/null @@ -1,73 +0,0 @@ - -// PROBLEM:- MERGE SORTED ARRAY -// https://leetcode.com/problems/merge-sorted-array/description/ - -// Question: - -// You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, -// and two integers m and n, representing the number of elements in nums1 and nums2 respectively. - -// Merge nums1 and nums2 into a single array sorted in non-decreasing order. - -// The final sorted array should not be returned by the function, -// but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, -// where the first m elements denote the elements that should be merged, -// and the last n elements are set to 0 and should be ignored. nums2 has a length of n. -/**SAMPLE I/O - Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 - Output: [1,2,2,3,5,6] - -Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. -The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. - */ - - /** - APPROACH:- - 1. Use the 'm' and 'n' as the pointer of both the arrays. - 2. Loop through the array set the other pointer('shift') at last of nums1 to keep the track of empty array. - 3. Now compare nums1[m] to nums2[n], the bigger among them will be at nums1[shift](decrement the variables also). - 4. if m<0 or n<0 break. - 5. it is possible that there will be remaing element is nums2[] so copy them with the pointer 'shift'. - (The code is also well documented as well) - - - Time Complexity: O(N) because we iterate nums1[] which also contain the space for nums2[] - Space Complexity: O(1) Not extra array required, Hence constant space. - - */ - -class Solution { - public void merge(int[] nums1, int m, int[] nums2, int n) { - if (n == 0) // If nums2 is empty, no merging required - return; - - if (m == 0) { // If nums1 is empty, simply copy nums2 to nums1 - int shift = nums1.length - 1; - for (int i = 0; i < n; i++) { - nums1[i] = nums2[i]; - } - return; - } - - int shift = m + n - 1; // Index to track the current position while merging - m -= 1; // Decrement m to access the last element in nums1 - n -= 1; // Decrement n to access the last element in nums2 - - while (n >= 0 && m >= 0) { // Merge elements from the end of both arrays - if (nums2[n] > nums1[m]) { // If current element in nums2 is greater - nums1[shift] = nums2[n]; // Place it in the current position in nums1 - shift -= 1; // Decrement the position index - n -= 1; // Decrement n to move to the previous element in nums2 - } else if (nums2[n] <= nums1[m]) { // If current element in nums2 is less than or equal to the current element in nums1 - nums1[shift] = nums1[m]; // Place the current element in nums1 in the current position in nums1 - nums1[m] = 0; // Set the current element in nums1 to 0 (to be ignored during merging) - shift -= 1; // Decrement the position index - m -= 1; // Decrement m to move to the previous element in nums1 - } - } - - while (n >= 0) { // If there are remaining elements in nums2 - nums1[shift--] = nums2[n--]; // Copy them to the beginning of nums1 - } - } -} diff --git a/Arrays/Monotonic_Array.cpp b/Arrays/Monotonic_Array.cpp deleted file mode 100644 index c8975760..00000000 --- a/Arrays/Monotonic_Array.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/*The problem is about determining whether an array is monotonic. A monotonic array is defined as an array that is either entirely non-increasing or non-decreasing.*/ -/*The time complexity of the isMonotonic function is O(n) -The space complexity of the isMonotonic function is O(1)*/ - -#include -#include - -using namespace std; - -// Function to check if an array is monotonic -bool isMonotonic(const vector& array) { - const int size = array.size(); - bool increasing = true; - bool decreasing = true; - - // Iterate over the array - for (int i = 1; i < size; i++) { - // Check for non-increasing condition - if (array[i] < array[i - 1]) - increasing = false; - - // Check for non-decreasing condition - if (array[i] > array[i - 1]) - decreasing = false; - } - - // Return true if either increasing or decreasing condition holds - return increasing || decreasing; -} - -int main() { - vector arr1 = {1, 2, 3, 4, 5}; // Monotonic (Increasing) - vector arr2 = {5, 4, 3, 2, 1}; // Monotonic (Decreasing) - vector arr3 = {1, 2, 2, 3, 1}; // Not Monotonic - vector arr4 = {1, 1, 1, 1, 1}; // Monotonic (Increasing) - vector arr5 = {5, 5, 5, 5, 5}; // Monotonic (Increasing) - - cout << "Array 1 is monotonic: " << boolalpha << isMonotonic(arr1) << endl; - cout << "Array 2 is monotonic: " << boolalpha << isMonotonic(arr2) << endl; - cout << "Array 3 is monotonic: " << boolalpha << isMonotonic(arr3) << endl; - cout << "Array 4 is monotonic: " << boolalpha << isMonotonic(arr4) << endl; - cout << "Array 5 is monotonic: " << boolalpha << isMonotonic(arr5) << endl; - - return 0; -} From 23b5181c3924b7c36260603d7fb6fd0b5f4ca045 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:25:14 +0530 Subject: [PATCH 1324/1894] remove duplicate program --- Arrays/valid_palindrome.java | 46 ------------------------------------ 1 file changed, 46 deletions(-) delete mode 100644 Arrays/valid_palindrome.java diff --git a/Arrays/valid_palindrome.java b/Arrays/valid_palindrome.java deleted file mode 100644 index 0f4361b4..00000000 --- a/Arrays/valid_palindrome.java +++ /dev/null @@ -1,46 +0,0 @@ -/* -Two Pointers: Check whether a given string is a Valid Palindrome in Java -*/ - - -/* EXPLAINATION: -The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not. - -The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx. - -Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome. - -If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome. - -The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case. - -The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices. -*/ - - - -public static boolean isPalindrome(String str) -{ - // initialize startIdx to 0 and endIdx to the last index in the string - int startIdx = 0; - int endIdx = str.length() - 1; - - // loop through the string while the start index is less than the end index - while(startIdx < endIdx) - { - // get the characters at the start and end indices - char start = str.charAt(startIdx); - char end = str.charAt(endIdx); - - // if the lowercase versions of the characters do not match, return false - if(Character.toLowerCase(start) != Character.toLowerCase(end)) - return false; - - // increment the start index and decrement the end index - startIdx += 1; - endIdx -= 1; - } - - // if the loop completes without returning false, the string is a palindrome so return true - return true; -} From 6457b8b3c824d41c6c531a5eb947f8db94e6896d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:30:13 +0530 Subject: [PATCH 1325/1894] rename file and move to strings --- Arrays/arrays_strings_is_unique.go => Strings/is_unique.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Arrays/arrays_strings_is_unique.go => Strings/is_unique.go (100%) diff --git a/Arrays/arrays_strings_is_unique.go b/Strings/is_unique.go similarity index 100% rename from Arrays/arrays_strings_is_unique.go rename to Strings/is_unique.go From 22ee74f67d66800a7ad4c5ee96c9f02ad453791c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:30:19 +0530 Subject: [PATCH 1326/1894] add is unique in java --- Strings/is_unique.java | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Strings/is_unique.java diff --git a/Strings/is_unique.java b/Strings/is_unique.java new file mode 100644 index 00000000..ea3f8e98 --- /dev/null +++ b/Strings/is_unique.java @@ -0,0 +1,43 @@ +/* + // Implement an algorithm to determine if a string has all unique characters. + // what if you cannot use additional data structures? + + Explanation: + - The `isUniqueUsingBitVector` function takes a string `s` as input and returns a boolean value indicating whether the string has all unique characters. + - The variable `checker` is initialized as an integer, representing the bit vector to keep track of character occurrences. + - The function iterates over each character `c` in the string using a foreach loop. + - For each character, the variable `val` is computed by subtracting the ASCII value of `'a'` from the ASCII value of the character. This gives the corresponding index (0-25) for lowercase alphabetic characters. + - The program checks if the bit at position `val` in `checker` is already set. If it is, it means the character has occurred before, and the function returns `false`. + - If the character is unique, the bit at position `val` in `checker` is set by performing a bitwise OR operation with `(1 << val)`. This marks the occurrence of the character in the bit vector. + - After iterating through all the characters, if no duplicate characters are found, the function returns `true`. + - In the `main` function, a few test cases are provided, and the result of calling `isUniqueUsingBitVector` with each test case is printed. +*/ +public class Main { + public static boolean isUniqueUsingBitVector(String s) { + int checker = 0; // Bit vector to keep track of character occurrences + for (char c : s.toCharArray()) { + int val = c - 'a'; // Convert character to corresponding index (0-25) + if ((checker & (1 << val)) > 0) { + // If the bit corresponding to the character is already set, it means the character has occurred before + return false; + } + checker |= (1 << val); // Set the bit corresponding to the character to mark its occurrence + } + return true; + } + + public static void main(String[] args) { + String s = "ABCDD"; + String t = "ABCD"; + String u = "AAAAAABCD"; + boolean msg = isUniqueUsingBitVector(s); + System.out.println(msg); + msg = isUniqueUsingBitVector(t); + System.out.println(msg); + msg = isUniqueUsingBitVector(u); + System.out.println(msg); + + msg = isUniqueUsingBitVector("aa"); + System.out.println(msg); + } +} From 6f6e17005d3bd8b842a661567d915e1d75867041 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:31:12 +0530 Subject: [PATCH 1327/1894] add is unique in python --- Strings/is_unique.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Strings/is_unique.py diff --git a/Strings/is_unique.py b/Strings/is_unique.py new file mode 100644 index 00000000..750b5feb --- /dev/null +++ b/Strings/is_unique.py @@ -0,0 +1,34 @@ +''' + Implement an algorithm to determine if a string has all unique characters. + what if you cannot use additional data structures? + + Explanation: + - The `is_unique_using_bit_vector` function takes a string `s` as input and returns a boolean value indicating whether the string has all unique characters. + - The variable `checker` is initialized as an integer, representing the bit vector to keep track of character occurrences. + - The function iterates over each character `c` in the string using a for loop. + - For each character, the variable `val` is computed by subtracting the ASCII value of `'a'` from the ASCII value of the character. This gives the corresponding index (0-25) for lowercase alphabetic characters. + - The program checks if the bit at position `val` in `checker` is already set. If it is, it means the character has occurred before, and the function returns `False`. + - If the character is unique, the bit at position `val` in +''' +def is_unique_using_bit_vector(s): + checker = 0 # Bit vector to keep track of character occurrences + for c in s: + val = ord(c) - ord('a') # Convert character to corresponding index (0-25) + if (checker & (1 << val)) > 0: + # If the bit corresponding to the character is already set, it means the character has occurred before + return False + checker |= (1 << val) # Set the bit corresponding to the character to mark its occurrence + return True + +s = "ABCDD" +t = "ABCD" +u = "AAAAAABCD" +msg = is_unique_using_bit_vector(s) +print(msg) +msg = is_unique_using_bit_vector(t) +print(msg) +msg = is_unique_using_bit_vector(u) +print(msg) + +msg = is_unique_using_bit_vector("aa") +print(msg) From a05ec9471f0fae0b15b2f168b52d2abf2c98c18a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:32:31 +0530 Subject: [PATCH 1328/1894] add is unique in c++ --- Strings/is_unique.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++ Strings/is_unique.java | 4 ++-- 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 Strings/is_unique.cpp diff --git a/Strings/is_unique.cpp b/Strings/is_unique.cpp new file mode 100644 index 00000000..bc7c674e --- /dev/null +++ b/Strings/is_unique.cpp @@ -0,0 +1,47 @@ +/* + Implement an algorithm to determine if a string has all unique characters. + what if you cannot use additional data structures? + + Explanation: + - The `isUniqueUsingBitVector` function takes a constant reference to a string `s` as input and returns a boolean value indicating whether the string has all unique characters. + - The variable `checker` is initialized as an integer, representing the bit vector to keep track of character occurrences. + - The function iterates over each character `c` in the string using a range-based for loop. + - For each character, the variable `val` is computed by subtracting the ASCII value of `'a'` from the ASCII value of the character. This gives the corresponding index (0-25) for lowercase alphabetic characters. + - The program checks if the bit at position `val` in `checker` is already set. If it is, it means the character has occurred before, and the function returns `false`. + - If the character is unique, the bit at position `val` in `checker` is set by performing a bitwise OR operation with `(1 << val)`. This marks the occurrence of the character in the bit vector. + - After iterating through all the characters, if no duplicate characters are found, the function returns `true`. + - In the `main` function, a few test cases are provided, and the result of calling `isUniqueUsingBitVector` with each test case is printed. + +*/ +#include +#include + +bool isUniqueUsingBitVector(const std::string& s) { + int checker = 0; // Bit vector to keep track of character occurrences + for (char c : s) { + int val = c - 'a'; // Convert character to corresponding index (0-25) + if ((checker & (1 << val)) > 0) { + // If the bit corresponding to the character is already set, it means the character has occurred before + return false; + } + checker |= (1 << val); // Set the bit corresponding to the character to mark its occurrence + } + return true; +} + +int main() { + std::string s = "ABCDD"; + std::string t = "ABCD"; + std::string u = "AAAAAABCD"; + bool msg = isUniqueUsingBitVector(s); + std::cout << std::boolalpha << msg << std::endl; + msg = isUniqueUsingBitVector(t); + std::cout << std::boolalpha << msg << std::endl; + msg = isUniqueUsingBitVector(u); + std::cout << std::boolalpha << msg << std::endl; + + msg = isUniqueUsingBitVector("aa"); + std::cout << std::boolalpha << msg << std::endl; + + return 0; +} diff --git a/Strings/is_unique.java b/Strings/is_unique.java index ea3f8e98..66da5e2e 100644 --- a/Strings/is_unique.java +++ b/Strings/is_unique.java @@ -1,6 +1,6 @@ /* - // Implement an algorithm to determine if a string has all unique characters. - // what if you cannot use additional data structures? + Implement an algorithm to determine if a string has all unique characters. + what if you cannot use additional data structures? Explanation: - The `isUniqueUsingBitVector` function takes a string `s` as input and returns a boolean value indicating whether the string has all unique characters. From a58c0aa95c32622028de612a17fc03f9d04f8e7e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 9 Jun 2023 22:34:55 +0530 Subject: [PATCH 1329/1894] add is unique in javascript --- Strings/is_unique.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Strings/is_unique.js diff --git a/Strings/is_unique.js b/Strings/is_unique.js new file mode 100644 index 00000000..a66c8bb1 --- /dev/null +++ b/Strings/is_unique.js @@ -0,0 +1,43 @@ +/* + Implement an algorithm to determine if a string has all unique characters. + what if you cannot use additional data structures? + + Explanation: + + 1. The `isUniqueUsingBitVector` function takes a string `s` as input and returns a boolean value indicating whether the string has all unique characters. + 2. The variable `checker` is initialized as 0, representing the bit vector to keep track of character occurrences. + 3. The function iterates over each character in the string using a for loop. + 4. For each character, the variable `val` is computed by subtracting the ASCII value of `'a'` from the ASCII value of the character. This calculates the corresponding index (0-25) for lowercase alphabetic characters. + 5. The program checks if the bit at position `val` in the `checker` is already set. If it is, it means the character has occurred before, and the function returns `false`. + 6. If the character is unique, the bit at position `val` in the `checker` is set by performing a bitwise OR operation with `(1 << val)`. This marks the occurrence of the character in the bit vector. + 7. After iterating through all the characters, if no duplicate characters are found, the function returns `true`. + 8. In the test cases section, a few sample strings (`s`, `t`, `u`, and `"aa"`) are provided, and the result of calling `isUniqueUsingBitVector` with each test case is printed using `console.log()`. +*/ + +function isUniqueUsingBitVector(s) { + let checker = 0; // Bit vector to keep track of character occurrences + + for (let i = 0; i < s.length; i++) { + const val = s.charCodeAt(i) - "a".charCodeAt(0); // Convert character to corresponding index (0-25) + + if ((checker & (1 << val)) > 0) { + // If the bit corresponding to the character is already set, it means the character has occurred before + return false; + } + + checker |= 1 << val; // Set the bit corresponding to the character to mark its occurrence + } + + return true; +} + +// Test cases +const s = "ABCDD"; +const t = "ABCD"; +const u = "AAAAAABCD"; + +console.log(isUniqueUsingBitVector(s)); // false, 'D' appears more than once +console.log(isUniqueUsingBitVector(t)); // true, all characters are unique +console.log(isUniqueUsingBitVector(u)); // false, 'A' appears more than once + +console.log(isUniqueUsingBitVector("aa")); // false, 'a' appears more than once From 9974e5cc239a85ebf3342a8d569f837d90e65376 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Sat, 10 Jun 2023 13:17:10 +0530 Subject: [PATCH 1330/1894] Delete Merge_Sorted_array.go --- Arrays/Merge_Sorted_array.go | 34 ---------------------------------- 1 file changed, 34 deletions(-) delete mode 100644 Arrays/Merge_Sorted_array.go diff --git a/Arrays/Merge_Sorted_array.go b/Arrays/Merge_Sorted_array.go deleted file mode 100644 index 809106e7..00000000 --- a/Arrays/Merge_Sorted_array.go +++ /dev/null @@ -1,34 +0,0 @@ -Example: -Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 -Output: [1,2,2,3,5,6] - -Here's an implementation in Go to merge two sorted arrays: - -func merge(nums1 []int, m int, nums2 []int, n int) { - i := m - 1 // Index of last element in nums1 - j := n - 1 // Index of last element in nums2 - - // Merge from the end of the arrays to avoid overwriting - for k := m + n - 1; k >= 0; k-- { - if j < 0 { - // No more elements in nums2, nums1 already sorted - return - } - if i >= 0 && nums1[i] > nums2[j] { - nums1[k] = nums1[i] - i-- - } else { - nums1[k] = nums2[j] - j-- - } - } -} - -The merge function takes in two sorted arrays nums1 and nums2, where nums1 has m elements and nums2 has n elements. -The function then merges nums2 into nums1 in-place, resulting in a single sorted array. - -Starting from the end of both arrays, the function compares the last elements of nums1 and nums2, -and puts the larger one at the end of nums1. This process continues until all elements in nums2 have been merged into nums1. - -Note that since nums1 has enough space to accommodate all elements, we don't need to create a new array to store the merged elements. -We can just overwrite the 0 elements at the end of nums1 with the merged elements. From fb642f6970ce9072947387d4d8713d2f6a099460 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:22:42 +0530 Subject: [PATCH 1331/1894] add longest peak in c++ --- Arrays/longest_peak.cpp | 76 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Arrays/longest_peak.cpp diff --git a/Arrays/longest_peak.cpp b/Arrays/longest_peak.cpp new file mode 100644 index 00000000..fa4e0104 --- /dev/null +++ b/Arrays/longest_peak.cpp @@ -0,0 +1,76 @@ +/* + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), + at which point they become strictly decreasing. At least three integers are required to form a peak. + + The code defines a function named LongestPeak that takes an array of integers as an argument and returns an integer + representing the length of the longest "peak" in the array. + + A "peak" is defined as a sequence of integers in the array that begins with an increasing sequence of integers, + reaches a maximum value (the "peak"), and ends with a decreasing sequence of integers. + + The function first initializes a variable longestPeak to 0, which will be used to store the length of the longest + peak found so far. It then initializes a variable i to 1, which will be used to iterate over the elements of the array. + + The function then enters a loop that continues until i is less than len(array) - 1. Inside the loop, the function checks + whether the current element at i is a peak, by comparing it to its neighboring elements. If it is not a peak, the loop continues by incrementing i. + + If the current element at i is a peak, the function searches to the left and right of the peak to find the beginning + and end of the peak. It does this by iterating left and right from the peak until it finds a decreasing sequence of + integers, using the variables leftIndex and rightIndex. + + Once the function has found the beginning and end of the peak, it calculates the length of the peak using the formula + rightIndex - leftIndex - 1. If the length of the current peak is greater than the current longest peak, it updates + longestPeak to the length of the current peak. + + Finally, the function updates the value of i to be the end of the peak (rightIndex), so that the loop will skip over + the entire peak and continue iterating from the end of the peak. + + The function returns the value of longestPeak once it has finished iterating over the array. + + The time complexity of the LongestPeak function is O(n), where n is the length of the input array, because it iterates through the array only once. + + The space complexity of the function is O(1), because it uses a constant amount of extra space, regardless of the size of the input array. +*/ +#include + +int LongestPeak(std::vector& array) { + int longestPeak = 0; + int i = 1; + + while (i < array.size() - 1) { + // Check if i is a peak (i.e., it's greater than its neighbors) + bool isPeak = array[i - 1] < array[i] && array[i] > array[i + 1]; + + if (!isPeak) { + // If i is not a peak, move to the next element + i += 1; + continue; + } + + // Search left of i to find the beginning of the peak + int leftIndex = i - 2; + while (leftIndex >= 0 && array[leftIndex] < array[leftIndex + 1]) { + leftIndex--; + } + + // Search right of i to find the end of the peak + int rightIndex = i + 2; + while (rightIndex < array.size() && array[rightIndex] < array[rightIndex - 1]) { + rightIndex++; + } + + // Calculate the length of the current peak + int currentPeak = rightIndex - leftIndex - 1; + + // Update longestPeak if currentPeak is longer + if (currentPeak > longestPeak) { + longestPeak = currentPeak; + } + + // Move i to the end of the current peak + i = rightIndex; + } + + return longestPeak; +} From 43870a5eb7eba27f26bf3e3958228516336addd9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:22:51 +0530 Subject: [PATCH 1332/1894] add longest peak in java --- Arrays/longest_peak.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Arrays/longest_peak.java diff --git a/Arrays/longest_peak.java b/Arrays/longest_peak.java new file mode 100644 index 00000000..7f156bc2 --- /dev/null +++ b/Arrays/longest_peak.java @@ -0,0 +1,34 @@ +/* + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), + at which point they become strictly decreasing. At least three integers are required to form a peak. + + The code defines a function named LongestPeak that takes an array of integers as an argument and returns an integer + representing the length of the longest "peak" in the array. + + A "peak" is defined as a sequence of integers in the array that begins with an increasing sequence of integers, + reaches a maximum value (the "peak"), and ends with a decreasing sequence of integers. + + The function first initializes a variable longestPeak to 0, which will be used to store the length of the longest + peak found so far. It then initializes a variable i to 1, which will be used to iterate over the elements of the array. + + The function then enters a loop that continues until i is less than len(array) - 1. Inside the loop, the function checks + whether the current element at i is a peak, by comparing it to its neighboring elements. If it is not a peak, the loop continues by incrementing i. + + If the current element at i is a peak, the function searches to the left and right of the peak to find the beginning + and end of the peak. It does this by iterating left and right from the peak until it finds a decreasing sequence of + integers, using the variables leftIndex and rightIndex. + + Once the function has found the beginning and end of the peak, it calculates the length of the peak using the formula + rightIndex - leftIndex - 1. If the length of the current peak is greater than the current longest peak, it updates + longestPeak to the length of the current peak. + + Finally, the function updates the value of i to be the end of the peak (rightIndex), so that the loop will skip over + the entire peak and continue iterating from the end of the peak. + + The function returns the value of longestPeak once it has finished iterating over the array. + + The time complexity of the LongestPeak function is O(n), where n is the length of the input array, because it iterates through the array only once. + + The space complexity of the function is O(1), because it uses a constant amount of extra space, regardless of the size of the input array. +*/ \ No newline at end of file From 810e91ed28f1270c10479abb10b34c92d55c1eb4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:22:59 +0530 Subject: [PATCH 1333/1894] add longest peak in javascript --- Arrays/longest_peak.js | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Arrays/longest_peak.js diff --git a/Arrays/longest_peak.js b/Arrays/longest_peak.js new file mode 100644 index 00000000..c26bc2f3 --- /dev/null +++ b/Arrays/longest_peak.js @@ -0,0 +1,82 @@ +/* + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), + at which point they become strictly decreasing. At least three integers are required to form a peak. + + The code defines a function named LongestPeak that takes an array of integers as an argument and returns an integer + representing the length of the longest "peak" in the array. + + A "peak" is defined as a sequence of integers in the array that begins with an increasing sequence of integers, + reaches a maximum value (the "peak"), and ends with a decreasing sequence of integers. + + The function first initializes a variable longestPeak to 0, which will be used to store the length of the longest + peak found so far. It then initializes a variable i to 1, which will be used to iterate over the elements of the array. + + The function then enters a loop that continues until i is less than len(array) - 1. Inside the loop, the function checks + whether the current element at i is a peak, by comparing it to its neighboring elements. If it is not a peak, the loop continues by incrementing i. + + If the current element at i is a peak, the function searches to the left and right of the peak to find the beginning + and end of the peak. It does this by iterating left and right from the peak until it finds a decreasing sequence of + integers, using the variables leftIndex and rightIndex. + + Once the function has found the beginning and end of the peak, it calculates the length of the peak using the formula + rightIndex - leftIndex - 1. If the length of the current peak is greater than the current longest peak, it updates + longestPeak to the length of the current peak. + + Finally, the function updates the value of i to be the end of the peak (rightIndex), so that the loop will skip over + the entire peak and continue iterating from the end of the peak. + + The function returns the value of longestPeak once it has finished iterating over the array. + + The time complexity of the LongestPeak function is O(n), where n is the length of the input array, because it iterates through the array only once. + + The space complexity of the function is O(1), because it uses a constant amount of extra space, regardless of the size of the input array. +*/ +function longestPeak(array) { + let longestPeak = 0; + let i = 1; + + while (i < array.length - 1) { + // Check if i is a peak (i.e., it's greater than its neighbors) + const isPeak = array[i - 1] < array[i] && array[i] > array[i + 1]; + + if (!isPeak) { + // If i is not a peak, move to the next element + i += 1; + continue; + } + + // Search left of i to find the beginning of the peak + let leftIndex = i - 2; + while (leftIndex >= 0 && array[leftIndex] < array[leftIndex + 1]) { + leftIndex--; + } + + // Search right of i to find the end of the peak + let rightIndex = i + 2; + while ( + rightIndex < array.length && + array[rightIndex] < array[rightIndex - 1] + ) { + rightIndex++; + } + + // Calculate the length of the current peak + const currentPeak = rightIndex - leftIndex - 1; + + // Update longestPeak if currentPeak is longer + if (currentPeak > longestPeak) { + longestPeak = currentPeak; + } + + // Move i to the end of the current peak + i = rightIndex; + } + + return longestPeak; +} + +// Test the function +const array = [1, 3, 2, 1, 4, 7, 3, 2, 1]; +const result = longestPeak(array); +console.log(result); // Output: 6 From 020dc87845eb924f2bb7775191c89a9cafea70c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:23:08 +0530 Subject: [PATCH 1334/1894] modify longest peak in python --- Arrays/longest_peak.go | 1 - Arrays/longest_peak.py | 95 +++++++++++++++++++++++++++++++++--------- 2 files changed, 75 insertions(+), 21 deletions(-) diff --git a/Arrays/longest_peak.go b/Arrays/longest_peak.go index cefc7e08..42d1fa8f 100644 --- a/Arrays/longest_peak.go +++ b/Arrays/longest_peak.go @@ -1,5 +1,4 @@ /* - Write a function that takes in an array of integers and returns the length of the longest peak in the array. A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak. diff --git a/Arrays/longest_peak.py b/Arrays/longest_peak.py index 07a32281..0debdf75 100644 --- a/Arrays/longest_peak.py +++ b/Arrays/longest_peak.py @@ -1,23 +1,78 @@ -""" -Write a function that takes in an array of integers and returns the length of the longest peak -in the array.A peak is defined as adjacent integers in the array that are strictly increasing -until they reach a tip (the highest value in the peak), at which point they become strictly -decreasing. At least three integers are required to form a peak. -""" - - - -#approach -""" -1. iterate through the array from index 1 to len(arr) - 1 -2. check if the current element is a peak -3. if it is a peak, then find the length of the peak -4. go to the uphill start -5. go to the downhill end -6. update the ans -""" -# Time Complexity: O(n) -# Space Complexity: O(1) +''' + Write a function that takes in an array of integers and returns the length of the longest peak in the array. + A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), + at which point they become strictly decreasing. At least three integers are required to form a peak. + + The code defines a function named LongestPeak that takes an array of integers as an argument and returns an integer + representing the length of the longest "peak" in the array. + + A "peak" is defined as a sequence of integers in the array that begins with an increasing sequence of integers, + reaches a maximum value (the "peak"), and ends with a decreasing sequence of integers. + + The function first initializes a variable longestPeak to 0, which will be used to store the length of the longest + peak found so far. It then initializes a variable i to 1, which will be used to iterate over the elements of the array. + + The function then enters a loop that continues until i is less than len(array) - 1. Inside the loop, the function checks + whether the current element at i is a peak, by comparing it to its neighboring elements. If it is not a peak, the loop continues by incrementing i. + + If the current element at i is a peak, the function searches to the left and right of the peak to find the beginning + and end of the peak. It does this by iterating left and right from the peak until it finds a decreasing sequence of + integers, using the variables leftIndex and rightIndex. + + Once the function has found the beginning and end of the peak, it calculates the length of the peak using the formula + rightIndex - leftIndex - 1. If the length of the current peak is greater than the current longest peak, it updates + longestPeak to the length of the current peak. + + Finally, the function updates the value of i to be the end of the peak (rightIndex), so that the loop will skip over + the entire peak and continue iterating from the end of the peak. + + The function returns the value of longestPeak once it has finished iterating over the array. + + The time complexity of the LongestPeak function is O(n), where n is the length of the input array, because it iterates through the array only once. + + The space complexity of the function is O(1), because it uses a constant amount of extra space, regardless of the size of the input array. + +''' + +def longest_peak(array): + longest_peak = 0 + i = 1 + + while i < len(array) - 1: + # Check if i is a peak (i.e., it's greater than its neighbors) + is_peak = array[i - 1] < array[i] > array[i + 1] + + if not is_peak: + # If i is not a peak, move to the next element + i += 1 + continue + + # Search left of i to find the beginning of the peak + left_index = i - 2 + while left_index >= 0 and array[left_index] < array[left_index + 1]: + left_index -= 1 + + # Search right of i to find the end of the peak + right_index = i + 2 + while right_index < len(array) and array[right_index] < array[right_index - 1]: + right_index += 1 + + # Calculate the length of the current peak + current_peak = right_index - left_index - 1 + + # Update longest_peak if current_peak is longer + if current_peak > longest_peak: + longest_peak = current_peak + + # Move i to the end of the current peak + i = right_index + + return longest_peak + +# Test the function +array = [1, 3, 2, 1, 4, 7, 3, 2, 1] +result = longest_peak(array) +print(result) # Output: 6 From 3bf8a2fa456be1b6d07b4dbb25e2e3eaa911aa87 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:23:26 +0530 Subject: [PATCH 1335/1894] remove duplicate --- Arrays/find_longest_peak_of_an_array.cpp | 62 ------------------------ 1 file changed, 62 deletions(-) delete mode 100644 Arrays/find_longest_peak_of_an_array.cpp diff --git a/Arrays/find_longest_peak_of_an_array.cpp b/Arrays/find_longest_peak_of_an_array.cpp deleted file mode 100644 index c27986ea..00000000 --- a/Arrays/find_longest_peak_of_an_array.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - Write a function that takes in an array of integers and returns the length of the longest peak in the array. - A peak is defined as adjacent integers in the array that are strictly increasing until they reach a tip (the highest value in the peak), at which point they become strictly decreasing. At least three integers are required to form a peak. - - Sample Input = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3] - Output = 6 // 0, 10, 6, 5, -1, -3 -*/ -#include -using namespace std; -class Solution{ - public: - int maxPeakLength(vector nums) - { - - // Intitialize the required variables - bool beforePeak=true; - int maxLen=0; - int curLen=0; - - // Traverse through the array to find peaks - for(int i=0;inums[i+1]) - { - // Transiting into the latter strictly decreasing part of the peak - if(curLen<1){ - curLen=0; - beforePeak=true; - } - curLen++; - beforePeak=false; - } - else if(!beforePeak && nums[i]nums[i-1]) i-=2; - else if(nums[i]==nums[i-1]) i-=1; - beforePeak=true; - } - } - - // Return the final answer - return maxLen; - } -}; \ No newline at end of file From 44651e225727bba315789a6d3bdb3213f9646aa1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:24:27 +0530 Subject: [PATCH 1336/1894] rename file --- 2D Arrays (Matrix)/{setMatrixZero.java => set_matrix_0.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{setMatrixZero.java => set_matrix_0.java} (100%) diff --git a/2D Arrays (Matrix)/setMatrixZero.java b/2D Arrays (Matrix)/set_matrix_0.java similarity index 100% rename from 2D Arrays (Matrix)/setMatrixZero.java rename to 2D Arrays (Matrix)/set_matrix_0.java From be3add73716ad0e5f34598bead173915a29f47bd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:27:49 +0530 Subject: [PATCH 1337/1894] add smallest difference in java --- Arrays/smallest_difference.java | 93 +++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Arrays/smallest_difference.java diff --git a/Arrays/smallest_difference.java b/Arrays/smallest_difference.java new file mode 100644 index 00000000..84b926d7 --- /dev/null +++ b/Arrays/smallest_difference.java @@ -0,0 +1,93 @@ +/* + Write a function that takes in two non-empty arrays of integers, finds the pair of numbers (one from each array) + whose absolute difference is closest to zero, and returns an array containing these two numbers, with the number from + the first array in the first position. + + Note that the absolute difference of two integers is the distance between them on the real number line. + For example, the absolute difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. + + You can assume that there will only be one pair of numbers with the smallest difference. + + Sample Input Array1 = [-1, 5, 10, 20, 28, 3] + Sample Input Array2 = [26, 134, 135, 15, 17] + + Sample Output = [28, 26] + + + This code implements the Smallest Difference problem which takes two arrays of integers as input and returns a pair of integers, + one from each array, with the smallest absolute difference between them. + + The function first initializes two variables current and smallest to the maximum integer value. It then sorts both input arrays + in ascending order using the sort.Ints function from the sort package. + + The function then iterates through both arrays using two pointers, idx1 and idx2, initialized to 0. Inside the loop, it compares + the elements at the current indices of the two arrays, first and second, and calculates the absolute difference between + them in the current variable. + + If current is smaller than the smallest variable, it updates smallest to current and assigns the current pair of integers + to the result variable. + + The function returns the result variable, which contains the pair of integers with the smallest absolute difference. + + If there are identical integers in the two input arrays, the function will return them immediately, without any further comparisons. + + O(nlog(n) + mlog(m)) time | O(1) space - where n is the length of the first input array and m is the length of the second input array +*/ +import java.util.Arrays; + +public class Main { + + public static int[] smallestDifference(int[] array1, int[] array2) { + // Initialize variables for the smallest difference and the current difference being calculated + int current = Integer.MAX_VALUE; + int smallest = Integer.MAX_VALUE; + + // Sort the input arrays + Arrays.sort(array1); + Arrays.sort(array2); + + // Initialize variables for the indices for the two arrays + int idx1 = 0; + int idx2 = 0; + + // Initialize an empty array for the result + int[] result = new int[2]; + + // Loop through the two arrays until we reach the end of one of the arrays + while (idx1 < array1.length && idx2 < array2.length) { + // Get the values at the current indices for the two arrays + int first = array1[idx1]; + int second = array2[idx2]; + + // Calculate the current difference between the two values + if (first < second) { + current = second - first; + idx1++; + } else if (second < first) { + current = first - second; + idx2++; + } else { + // If the two values are equal, we can return the pair + return new int[]{first, second}; + } + + // Update the smallest difference and result array if the current difference is smaller + if (smallest > current) { + smallest = current; + result[0] = first; + result[1] = second; + } + } + + // Return the pair with the smallest absolute difference + return result; + } + + public static void main(String[] args) { + int[] array1 = {1, 3, 5, 23, 11, 2}; + int[] array2 = {8, 19, 3, 15, 9}; + + int[] result = smallestDifference(array1, array2); + System.out.println(Arrays.toString(result)); // Output: [3, 3] + } +} From 45658f48dba6b560ef7effe315985ada0d75c405 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:30:44 +0530 Subject: [PATCH 1338/1894] remove sorted square for py c++ and java --- Arrays/sorted_square_array.py | 24 ------- Arrays/squares_of_a_sorted_array.cpp | 69 -------------------- Arrays/squares_of_a_sorted_array.java | 91 --------------------------- 3 files changed, 184 deletions(-) delete mode 100644 Arrays/sorted_square_array.py delete mode 100644 Arrays/squares_of_a_sorted_array.cpp delete mode 100644 Arrays/squares_of_a_sorted_array.java diff --git a/Arrays/sorted_square_array.py b/Arrays/sorted_square_array.py deleted file mode 100644 index a2628041..00000000 --- a/Arrays/sorted_square_array.py +++ /dev/null @@ -1,24 +0,0 @@ -''' - Write a function that takes in a non-empty array of integers that are sorted - in ascending order and returns a new array of the same length with the squares - of the original integers also sorted in ascending order. - - Sample Input: [-6, 1, 2, 3, 4] - Output: [1, 4, 6, 16, 36] -''' -class Solution: - def sortedSquares(self, nums: List[int]) -> List[int]: - #Considering two pointer approach - i,j=0,len(nums)-1 - final_array=[] - while(i<=j): - #comparing absolute values of the starting and the ending elements - #if the second-pointer element is greateer, we add it to the list. If not, we add the first-pointer element - if(abs(nums[i]) 1 <= nums.length <= 104 - > -104 <= nums[i] <= 104 - > nums is sorted in non-decreasing order. -*/ - -/*class Solution { -public: - int N=10001; - vector sortedSquares(vector& nums) { - // Initialize variables - vector trk(N,0); - - // Store the frquency of the absolute of each number from the list - for(int i=0;i0) - { - int square=i*i; - while(trk[i]) - { - ans.push_back(square); - trk[i]--; - } - } - } - - // Return the final ans - return ans; - } -}; -*/ -class Solution { -public: - vector sortedSquares(vector& nums) { - int n = nums.size(); - vector res(n); // Create a vector to store the squared values - int left = 0, right = n - 1; // Initialize two pointers at the start and end of the array - - for (int i = n - 1; i >= 0; i--) { - if (abs(nums[left]) > abs(nums[right])) { - // If the absolute value of the number at the left pointer is greater than the absolute value of the number at the right pointer - res[i] = nums[left] * nums[left]; // Square the number at the left pointer and store it in the result array - left++; // Move the left pointer to the right - } else { - // If the absolute value of the number at the left pointer is less than or equal to the absolute value of the number at the right pointer - res[i] = nums[right] * nums[right]; // Square the number at the right pointer and store it in the result array - right--; // Move the right pointer to the left - } - } - - return res; // Return the result array - } -}; diff --git a/Arrays/squares_of_a_sorted_array.java b/Arrays/squares_of_a_sorted_array.java deleted file mode 100644 index c252997f..00000000 --- a/Arrays/squares_of_a_sorted_array.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - - Time Complexity: O(n), Space Complexity O(n). - - Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. - - Input: nums = [-4,-1,0,3,10] - Output: [0,1,9,16,100] - - Input: nums = [-7,-3,2,3,11] - Output: [4,9,9,49,121] - - - Input: nums = [2,3,11] - Output: [4,9,121] - -**/ - -class Solution { - public int[] sortedSquares(int[] nums) { - - int hasNegative = -1; // -1 Indcating that are no negative values in the input array. - int len = nums.length; - - // Find the index of the last negative value. - for(int i = 0; i < len; ++i) - { - if(nums[i] < 0) - { - nums[i] = Math.abs(nums[i]); // If there is a negative value make it positive. - hasNegative = i; - } - } - - - int []ans = new int[nums.length]; - - if(hasNegative != -1) // check if the array have negative values - { - - /** - If there are negative values, - that's divide the input array into two halfs. - both halfs are sorted in increasing order if: - - -first half start from a and end at index 0, Where a is the index of the last negative value. - -second half start from (b) and end at (size of the array - 1 (n - 1)) [b, n-1] iclusive, Where b is the index a + 1. - - At every step we choose the minimun value between the vlaues at index a and b then, - square the value and store it in array []ans. - **/ - int a = hasNegative, b = hasNegative + 1; - int k = 0; - - while(a >= 0 && b < len) - { - if(nums[a] <= nums[b]) // Value at index a is the minimum value so we choosed. - { - ans[k] = nums[a] * nums[a]; - a--; - } - else - { - ans[k] = nums[b] * nums[b]; - b++; - } - k++; - } - - while(a >= 0) - { - ans[k++] = nums[a] * nums[a]; - a--; - } - - while(b < len) - { - ans[k++] = nums[b] * nums[b]; - b++; - } - } - else //If there are no negative values, the sloution is straight forward. - { - - for(int i = 0; i < len; ++i) - ans[i] = nums[i] * nums[i]; - } - return ans; - } - -} \ No newline at end of file From 1770443ac29df74e6e4aa71ca6eaff57b8baada6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:36:43 +0530 Subject: [PATCH 1339/1894] add sorted square array in javascript --- Arrays/sorted_square_array,js | 70 +++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Arrays/sorted_square_array,js diff --git a/Arrays/sorted_square_array,js b/Arrays/sorted_square_array,js new file mode 100644 index 00000000..fbcd5671 --- /dev/null +++ b/Arrays/sorted_square_array,js @@ -0,0 +1,70 @@ +/* + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. + + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] + + Explanation: + + The `SortedSquaredArray` function takes an integer array as input and returns a new array where each element is the square of the corresponding element in the input array. The new array is sorted in non-decreasing order. + + Here's a step-by-step explanation of the code: + + 1. Initialize an empty result array of the same length as the original array: `result := make([]int, len(array))`. + 2. Initialize variables to mark the start and end positions of the array, as well as the end_pos, which is the + index of the last element in the result array: `end_pos := len(array) - 1`, `start := 0`, `end := len(array) - 1`. + 3. Inside the loop, calculate the square of the absolute value for the elements at the current start and + end positions: `sq1 = array[start] * array[start]`, `sq2 = array[end] * array[end]`. + 4. Compare `sq1` and `sq2` to determine which one is greater. If `sq1` is greater, assign it to the `end_pos` + index of the result array and increment the start position by 1: `result[end_pos] = sq1`, `start++`. + This ensures that the greater squared value is placed at the end of the result array. + 5. If `sq2` is greater, assign it to the `end_pos` index of the result array and decrement the end position + by 1: `result[end_pos] = sq2`, `end--`. This ensures that the greater squared value is still placed at the + end of the result array. + 6. Decrement the `end_pos` variable to move to the previous index in the result array: `end_pos--`. + 7. Repeat the process until the start and end positions cross each other. + 8. Finally, return the result array, which contains the squared values of the input array elements + in non-decreasing order. + + The code effectively uses a two-pointer approach to compare the squared values of the elements at the start and end positions and places the greater squared value at the end of the result array. This ensures that the result array is sorted in non-decreasing order. + + The time complexity of the `SortedSquaredArray` function is O(n), where n is the length of the input array. This is because the function performs a single pass through the array to calculate the squares and populate the result array. + + The space complexity of the function is O(n) as well. This is because it creates a new result array of the same length as the input array to store the squared values. Therefore, the space required is proportional to the size of the input array. + + Overall, the function has a linear time complexity and linear space complexity. +*/ +function sortedSquaredArray(array) { + // Initialize an empty result array of the same length as the original array + const result = Array(array.length).fill(0); + + // Set the start and end positions and the end_pos + let end_pos = array.length - 1; + let start = 0; + let sq1 = 0; + let sq2 = 0; + let end = array.length - 1; + + // Using the two-pointer approach, calculate the square of the absolute value and add the greatest value to the end of the result array + while (start <= end) { + sq1 = array[start] * array[start]; + sq2 = array[end] * array[end]; + + if (sq1 > sq2) { + result[end_pos] = sq1; + start++; // Square of the start pointer is greater, so increment start by 1 + } else { + result[end_pos] = sq2; + end--; // Square of the end pointer is greater, so decrement end by 1 + } + end_pos--; + } + + return result; +} + +const arr = [-6, 1, 2, 3, 4, 5]; +const result = sortedSquaredArray(arr); +console.log(result); From 9c0ea6fc012a61376173ec68fad642c5907d5a68 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:36:50 +0530 Subject: [PATCH 1340/1894] add sorted square array in c++ --- Arrays/sorted_square_array.cpp | 81 ++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Arrays/sorted_square_array.cpp diff --git a/Arrays/sorted_square_array.cpp b/Arrays/sorted_square_array.cpp new file mode 100644 index 00000000..d7405bc6 --- /dev/null +++ b/Arrays/sorted_square_array.cpp @@ -0,0 +1,81 @@ +/* + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. + + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] + + Explanation: + + The `SortedSquaredArray` function takes an integer array as input and returns a new array where each element is the square of the corresponding element in the input array. The new array is sorted in non-decreasing order. + + Here's a step-by-step explanation of the code: + + 1. Initialize an empty result array of the same length as the original array: `result := make([]int, len(array))`. + 2. Initialize variables to mark the start and end positions of the array, as well as the end_pos, which is the + index of the last element in the result array: `end_pos := len(array) - 1`, `start := 0`, `end := len(array) - 1`. + 3. Inside the loop, calculate the square of the absolute value for the elements at the current start and + end positions: `sq1 = array[start] * array[start]`, `sq2 = array[end] * array[end]`. + 4. Compare `sq1` and `sq2` to determine which one is greater. If `sq1` is greater, assign it to the `end_pos` + index of the result array and increment the start position by 1: `result[end_pos] = sq1`, `start++`. + This ensures that the greater squared value is placed at the end of the result array. + 5. If `sq2` is greater, assign it to the `end_pos` index of the result array and decrement the end position + by 1: `result[end_pos] = sq2`, `end--`. This ensures that the greater squared value is still placed at the + end of the result array. + 6. Decrement the `end_pos` variable to move to the previous index in the result array: `end_pos--`. + 7. Repeat the process until the start and end positions cross each other. + 8. Finally, return the result array, which contains the squared values of the input array elements + in non-decreasing order. + + The code effectively uses a two-pointer approach to compare the squared values of the elements at the start and end positions and places the greater squared value at the end of the result array. This ensures that the result array is sorted in non-decreasing order. + + The time complexity of the `SortedSquaredArray` function is O(n), where n is the length of the input array. This is because the function performs a single pass through the array to calculate the squares and populate the result array. + + The space complexity of the function is O(n) as well. This is because it creates a new result array of the same length as the input array to store the squared values. Therefore, the space required is proportional to the size of the input array. + + Overall, the function has a linear time complexity and linear space complexity. +*/ +#include +#include + +std::vector sortedSquaredArray(std::vector& array) { + // Initialize an empty result vector of the same length as the original array + std::vector result(array.size()); + + // Set the start and end positions and the end_pos + int end_pos = array.size() - 1; + int start = 0; + int sq1 = 0; + int sq2 = 0; + int end = array.size() - 1; + + // Using the two-pointer approach, calculate the square of the absolute value and add the greatest value to the end of the result vector + while (start <= end) { + sq1 = array[start] * array[start]; + sq2 = array[end] * array[end]; + + if (sq1 > sq2) { + result[end_pos] = sq1; + start++; // Square of the start pointer is greater, so increment start by 1 + } else { + result[end_pos] = sq2; + end--; // Square of the end pointer is greater, so decrement end by 1 + } + end_pos--; + } + + return result; +} + +int main() { + std::vector arr = {-6, 1, 2, 3, 4, 5}; + std::vector result = sortedSquaredArray(arr); + + for (int num : result) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} From c607fb54a538d1887cbf2e049147521138fc3044 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:37:00 +0530 Subject: [PATCH 1341/1894] modify documentation --- Arrays/sorted_square_array.go | 40 ++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/Arrays/sorted_square_array.go b/Arrays/sorted_square_array.go index cf31a0e5..9de8bb25 100644 --- a/Arrays/sorted_square_array.go +++ b/Arrays/sorted_square_array.go @@ -1,10 +1,40 @@ /* - Write a function that takes in a non-empty array of integers that are sorted - in ascending order and returns a new array of the same length with the squares - of the original integers also sorted in ascending order. + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. - Sample Input: [-6, 1, 2, 3, 4] - Output: [1, 4, 6, 16, 36] + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] + + Explanation: + + The `SortedSquaredArray` function takes an integer array as input and returns a new array where each element is the square of the corresponding element in the input array. The new array is sorted in non-decreasing order. + + Here's a step-by-step explanation of the code: + + 1. Initialize an empty result array of the same length as the original array: `result := make([]int, len(array))`. + 2. Initialize variables to mark the start and end positions of the array, as well as the end_pos, which is the + index of the last element in the result array: `end_pos := len(array) - 1`, `start := 0`, `end := len(array) - 1`. + 3. Inside the loop, calculate the square of the absolute value for the elements at the current start and + end positions: `sq1 = array[start] * array[start]`, `sq2 = array[end] * array[end]`. + 4. Compare `sq1` and `sq2` to determine which one is greater. If `sq1` is greater, assign it to the `end_pos` + index of the result array and increment the start position by 1: `result[end_pos] = sq1`, `start++`. + This ensures that the greater squared value is placed at the end of the result array. + 5. If `sq2` is greater, assign it to the `end_pos` index of the result array and decrement the end position + by 1: `result[end_pos] = sq2`, `end--`. This ensures that the greater squared value is still placed at the + end of the result array. + 6. Decrement the `end_pos` variable to move to the previous index in the result array: `end_pos--`. + 7. Repeat the process until the start and end positions cross each other. + 8. Finally, return the result array, which contains the squared values of the input array elements + in non-decreasing order. + + The code effectively uses a two-pointer approach to compare the squared values of the elements at the start and end positions and places the greater squared value at the end of the result array. This ensures that the result array is sorted in non-decreasing order. + + The time complexity of the `SortedSquaredArray` function is O(n), where n is the length of the input array. This is because the function performs a single pass through the array to calculate the squares and populate the result array. + + The space complexity of the function is O(n) as well. This is because it creates a new result array of the same length as the input array to store the squared values. Therefore, the space required is proportional to the size of the input array. + + Overall, the function has a linear time complexity and linear space complexity. */ package main From 873de800820e40c2d4fb61ca5a135a454a532a1e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:37:05 +0530 Subject: [PATCH 1342/1894] add sorted square array in java --- Arrays/sorted_square_array.java | 81 +++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Arrays/sorted_square_array.java diff --git a/Arrays/sorted_square_array.java b/Arrays/sorted_square_array.java new file mode 100644 index 00000000..a2c5526f --- /dev/null +++ b/Arrays/sorted_square_array.java @@ -0,0 +1,81 @@ +/* + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. + + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] + + Explanation: + + The `SortedSquaredArray` function takes an integer array as input and returns a new array where each element is the square of the corresponding element in the input array. The new array is sorted in non-decreasing order. + + Here's a step-by-step explanation of the code: + + 1. Initialize an empty result array of the same length as the original array: `result := make([]int, len(array))`. + 2. Initialize variables to mark the start and end positions of the array, as well as the end_pos, which is the + index of the last element in the result array: `end_pos := len(array) - 1`, `start := 0`, `end := len(array) - 1`. + 3. Inside the loop, calculate the square of the absolute value for the elements at the current start and + end positions: `sq1 = array[start] * array[start]`, `sq2 = array[end] * array[end]`. + 4. Compare `sq1` and `sq2` to determine which one is greater. If `sq1` is greater, assign it to the `end_pos` + index of the result array and increment the start position by 1: `result[end_pos] = sq1`, `start++`. + This ensures that the greater squared value is placed at the end of the result array. + 5. If `sq2` is greater, assign it to the `end_pos` index of the result array and decrement the end position + by 1: `result[end_pos] = sq2`, `end--`. This ensures that the greater squared value is still placed at the + end of the result array. + 6. Decrement the `end_pos` variable to move to the previous index in the result array: `end_pos--`. + 7. Repeat the process until the start and end positions cross each other. + 8. Finally, return the result array, which contains the squared values of the input array elements + in non-decreasing order. + + The code effectively uses a two-pointer approach to compare the squared values of the elements at the start and end positions and places the greater squared value at the end of the result array. This ensures that the result array is sorted in non-decreasing order. + + The time complexity of the `SortedSquaredArray` function is O(n), where n is the length of the input array. This is because the function performs a single pass through the array to calculate the squares and populate the result array. + + The space complexity of the function is O(n) as well. This is because it creates a new result array of the same length as the input array to store the squared values. Therefore, the space required is proportional to the size of the input array. + + Overall, the function has a linear time complexity and linear space complexity. +*/ +import java.util.Arrays; + +public class Main { + + public static int[] sortedSquaredArray(int[] array) { + // Initialize an empty result array of the same length as the original array + int[] result = new int[array.length]; + + // Set the start and end positions and the end_pos + int end_pos = array.length - 1; + int start = 0; + int sq1 = 0; + int sq2 = 0; + int end = array.length - 1; + + // Using the two-pointer approach, calculate the square of the absolute value and add the greatest value to the end of the result array + while (start <= end) { + sq1 = array[start] * array[start]; + sq2 = array[end] * array[end]; + + if (sq1 > sq2) { + result[end_pos] = sq1; + start++; // Square of the start pointer is greater, so increment start by 1 + } else { + result[end_pos] = sq2; + end--; // Square of the end pointer is greater, so decrement end by 1 + } + end_pos--; + } + + return result; + } + + public static void main(String[] args) { + int[] arr = {-6, 1, 2, 3, 4, 5}; + int[] result = sortedSquaredArray(arr); + + for (int num : result) { + System.out.print(num + " "); + } + System.out.println(); + } +} From 6ec8d9e46568470b9f0d0a44eab9f7854059cceb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 10 Jun 2023 13:37:11 +0530 Subject: [PATCH 1343/1894] add sorted square array in python --- Arrays/sorted_square_array.py | 67 +++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Arrays/sorted_square_array.py diff --git a/Arrays/sorted_square_array.py b/Arrays/sorted_square_array.py new file mode 100644 index 00000000..c2024b4c --- /dev/null +++ b/Arrays/sorted_square_array.py @@ -0,0 +1,67 @@ +''' + Write a function that takes in a non-empty array of integers that are sorted + in ascending order and returns a new array of the same length with the squares + of the original integers also sorted in ascending order. + + Sample Input: [-6, 1, 2, 3, 4] + Output: [1, 4, 6, 16, 36] + + Explanation: + + The `SortedSquaredArray` function takes an integer array as input and returns a new array where each element is the square of the corresponding element in the input array. The new array is sorted in non-decreasing order. + + Here's a step-by-step explanation of the code: + + 1. Initialize an empty result array of the same length as the original array: `result := make([]int, len(array))`. + 2. Initialize variables to mark the start and end positions of the array, as well as the end_pos, which is the + index of the last element in the result array: `end_pos := len(array) - 1`, `start := 0`, `end := len(array) - 1`. + 3. Inside the loop, calculate the square of the absolute value for the elements at the current start and + end positions: `sq1 = array[start] * array[start]`, `sq2 = array[end] * array[end]`. + 4. Compare `sq1` and `sq2` to determine which one is greater. If `sq1` is greater, assign it to the `end_pos` + index of the result array and increment the start position by 1: `result[end_pos] = sq1`, `start++`. + This ensures that the greater squared value is placed at the end of the result array. + 5. If `sq2` is greater, assign it to the `end_pos` index of the result array and decrement the end position + by 1: `result[end_pos] = sq2`, `end--`. This ensures that the greater squared value is still placed at the + end of the result array. + 6. Decrement the `end_pos` variable to move to the previous index in the result array: `end_pos--`. + 7. Repeat the process until the start and end positions cross each other. + 8. Finally, return the result array, which contains the squared values of the input array elements + in non-decreasing order. + + The code effectively uses a two-pointer approach to compare the squared values of the elements at the start and end positions and places the greater squared value at the end of the result array. This ensures that the result array is sorted in non-decreasing order. + + The time complexity of the `SortedSquaredArray` function is O(n), where n is the length of the input array. This is because the function performs a single pass through the array to calculate the squares and populate the result array. + + The space complexity of the function is O(n) as well. This is because it creates a new result array of the same length as the input array to store the squared values. Therefore, the space required is proportional to the size of the input array. + + Overall, the function has a linear time complexity and linear space complexity. +''' +def sortedSquaredArray(array): + # Initialize an empty result array of the same length as the original array + result = [0] * len(array) + + # Set the start and end positions and the end_pos + end_pos = len(array) - 1 + start = 0 + sq1 = 0 + sq2 = 0 + end = len(array) - 1 + + # Using the two-pointer approach, calculate the square of the absolute value and add the greatest value to the end of the result array + while start <= end: + sq1 = array[start] * array[start] + sq2 = array[end] * array[end] + + if sq1 > sq2: + result[end_pos] = sq1 + start += 1 # Square of the start pointer is greater, so increment start by 1 + else: + result[end_pos] = sq2 + end -= 1 # Square of the end pointer is greater, so decrement end by 1 + end_pos -= 1 + + return result + +arr = [-6, 1, 2, 3, 4, 5] +result = sortedSquaredArray(arr) +print(result) From cf63a147c971c93e0d8a281caa0b7e12add6d1d6 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Sat, 10 Jun 2023 22:42:12 +0530 Subject: [PATCH 1344/1894] Create search in 2d sorted array in java a clear approach towards solution by optimizing the time complexity. --- search in 2d sorted array | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 search in 2d sorted array diff --git a/search in 2d sorted array b/search in 2d sorted array new file mode 100644 index 00000000..bbeddd4a --- /dev/null +++ b/search in 2d sorted array @@ -0,0 +1,42 @@ + +/* Issue 271 +##Assignee:Mani1881 +About:Search in 2D sorted array in Java +Input: +You are given an m x n integer matrix matrix with the following two properties: +Each row is sorted in non-decreasing order. +The first integer of each row is greater than the last integer of the previous row. +Given an integer target, return true if target is in matrix or false otherwise. +time +You must write a solution in O(log(m * n)) time complexity. +Explanation: +In this code, we have the Solution class with the searchMatrix method that takes a 2D matrix and a target value as parameters. It iterates through each element in the matrix and checks if the current element is equal to the target value. If a match is found, it returns true. If no match is found after checking all elements, it returns false. + +In the main function, we create an instance of the Solution class and define a sample matrix and target value. We then call the searchMatrix method with the provided matrix and target, and store the result in the found variable. Finally, we print whether the target was found or not. In this example, the output will be "Target found: true" since the target value 5 exists in the matrix. */ +class Solution { +public boolean searchMatrix(int[][] matrix, int target) { +int m = matrix.length; +int i = 0; +for (i = 0; i < m; i++) { +for (int j = 0; j < matrix[i].length; j++) { +if (matrix[i][j] == target) +return true; +} +} +return false; +} + +public static void main(String[] args) { + Solution solution = new Solution(); + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + int target = 5; + + boolean found = solution.searchMatrix(matrix, target); + System.out.println("Target found: " + found); +} +} + From 429637fab5cab2bcc4603f3f189c7f723baaa197 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Sat, 10 Jun 2023 22:55:41 +0530 Subject: [PATCH 1345/1894] Update search in 2d sorted array created search in 2d array file along with examples --- search in 2d sorted array | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/search in 2d sorted array b/search in 2d sorted array index bbeddd4a..4e6bb2b9 100644 --- a/search in 2d sorted array +++ b/search in 2d sorted array @@ -7,8 +7,16 @@ You are given an m x n integer matrix matrix with the following two properties: Each row is sorted in non-decreasing order. The first integer of each row is greater than the last integer of the previous row. Given an integer target, return true if target is in matrix or false otherwise. -time +Time: You must write a solution in O(log(m * n)) time complexity. +Example 1: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true + +Example 2: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false + Explanation: In this code, we have the Solution class with the searchMatrix method that takes a 2D matrix and a target value as parameters. It iterates through each element in the matrix and checks if the current element is equal to the target value. If a match is found, it returns true. If no match is found after checking all elements, it returns false. From 72e30d84d68b5385a8bc021a128fe07f39322612 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Sat, 10 Jun 2023 23:14:39 +0530 Subject: [PATCH 1346/1894] Update search in 2d sorted array --- search in 2d sorted array | 2 ++ 1 file changed, 2 insertions(+) diff --git a/search in 2d sorted array b/search in 2d sorted array index 4e6bb2b9..223d7ade 100644 --- a/search in 2d sorted array +++ b/search in 2d sorted array @@ -1,5 +1,7 @@ /* Issue 271 +Author:maneesha +Date:10/06/2023 ##Assignee:Mani1881 About:Search in 2D sorted array in Java Input: From 59fbeb92ba86013f77585d61292ebb6803fe1f45 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Sun, 11 Jun 2023 00:01:38 +0530 Subject: [PATCH 1347/1894] renamed to search in 2d sorted array.java >>updated time complexity >>and made line comments --- search in 2d sorted array | 52 --------------------------- search in 2d sorted array.java | 64 ++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 52 deletions(-) delete mode 100644 search in 2d sorted array create mode 100644 search in 2d sorted array.java diff --git a/search in 2d sorted array b/search in 2d sorted array deleted file mode 100644 index 223d7ade..00000000 --- a/search in 2d sorted array +++ /dev/null @@ -1,52 +0,0 @@ - -/* Issue 271 -Author:maneesha -Date:10/06/2023 -##Assignee:Mani1881 -About:Search in 2D sorted array in Java -Input: -You are given an m x n integer matrix matrix with the following two properties: -Each row is sorted in non-decreasing order. -The first integer of each row is greater than the last integer of the previous row. -Given an integer target, return true if target is in matrix or false otherwise. -Time: -You must write a solution in O(log(m * n)) time complexity. -Example 1: -Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 -Output: true - -Example 2: -Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 -Output: false - -Explanation: -In this code, we have the Solution class with the searchMatrix method that takes a 2D matrix and a target value as parameters. It iterates through each element in the matrix and checks if the current element is equal to the target value. If a match is found, it returns true. If no match is found after checking all elements, it returns false. - -In the main function, we create an instance of the Solution class and define a sample matrix and target value. We then call the searchMatrix method with the provided matrix and target, and store the result in the found variable. Finally, we print whether the target was found or not. In this example, the output will be "Target found: true" since the target value 5 exists in the matrix. */ -class Solution { -public boolean searchMatrix(int[][] matrix, int target) { -int m = matrix.length; -int i = 0; -for (i = 0; i < m; i++) { -for (int j = 0; j < matrix[i].length; j++) { -if (matrix[i][j] == target) -return true; -} -} -return false; -} - -public static void main(String[] args) { - Solution solution = new Solution(); - int[][] matrix = { - {1, 2, 3}, - {4, 5, 6}, - {7, 8, 9} - }; - int target = 5; - - boolean found = solution.searchMatrix(matrix, target); - System.out.println("Target found: " + found); -} -} - diff --git a/search in 2d sorted array.java b/search in 2d sorted array.java new file mode 100644 index 00000000..e860eed1 --- /dev/null +++ b/search in 2d sorted array.java @@ -0,0 +1,64 @@ + +/* Issue 271 +Author:maneesha +Date:10/06/2023 +##Assignee:Mani1881 + +//About:Search in 2D sorted array in Java +//Input: +You are given an m x n integer matrix matrix with the following two properties: +Each row is sorted in non-decreasing order. +The first integer of each row is greater than the last integer of the previous row. +Given an integer target, return true if target is in matrix or false otherwise. +//Time Complexity:O(log(m * n)) +//Space Complexity:O(1) +//Example 1: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true + +//Example 2: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false + +//Explanation: +>>In this code, we have the Solution class with the searchMatrix method that takes a 2D matrix and a target value as parameters. +>>It iterates through each element in the matrix and checks if the current element is equal to the target value. +>>If a match is found, it returns true. If no match is found after checking all elements, it returns false. +>>In the main function, we create an instance of the Solution class and define a sample matrix and target value. +>>We then call the searchMatrix method with the provided matrix and target, and store the result in the found variable. +>>Finally, we print whether the target was found or not. +>>In this example, the output will be "Target found: true" since the target value 5 exists in the matrix. +*/ + +class Solution +{ +public boolean searchMatrix(int[][] matrix, int target) +{ + int m = matrix.length; + int i = 0; + for (i = 0; i < m; i++) + { + for (int j = 0; j < matrix[i].length; j++) + { + if (matrix[i][j] == target) + return true; + } + } +return false; +} + +public static void main(String[] args) +{ + Solution solution = new Solution(); + int[][] matrix = { + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} + }; + int target = 5; + + boolean found = solution.searchMatrix(matrix, target); + System.out.println("Target found: " + found); +} +} + From 057781a48b6cf991bc60c5d1e472f3e70409d375 Mon Sep 17 00:00:00 2001 From: Tanvii26 Date: Sun, 11 Jun 2023 01:37:15 +0530 Subject: [PATCH 1348/1894] First and Last Position of element --- Binary Search/first_and_last_pos.js | 105 ++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Binary Search/first_and_last_pos.js diff --git a/Binary Search/first_and_last_pos.js b/Binary Search/first_and_last_pos.js new file mode 100644 index 00000000..da2e1fbf --- /dev/null +++ b/Binary Search/first_and_last_pos.js @@ -0,0 +1,105 @@ +/* + -----------QUESTION-------------- + +Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. +If target is not found in the array, return [-1, -1]. Devise an algorithm with O(log n) runtime complexity. + +Example 1: + Input: nums = [5,7,7,8,8,10], target = 8 + Output: [3,4] + +Example 2: + Input: nums = [5,7,7,8,8,10], target = 6 + Output: [-1,-1] + +Example 3: + Input: nums = [], target = 0 + Output: [-1,-1] + + +Constraints: + 0 <= nums.length <= 105 + -109 <= nums[i] <= 109 + nums is a non-decreasing array (increasing order) + -109 <= target <= 109 +*/ + + +// ------------SOLUTION------------- + +/* +An intuitive Binary Search algorithm is used to find target value indices of occurence since it is given an increasing array. We perform two searches one for first occurence and second for last occurence. + +Two pointer start and end for 0th and (N-1)th index to iteratively find the mid of array. + +First follow the common left-based binary search to find the target value first occurence. +If found we proceed further check in left subarray as target may still be presnt either to left or right of mid. + +To find last occurence index we again iterate to right subarray from start as the current value but reset last to N-1. + +(start does not require to begin again from 0th index as in first pass we have covered upto start index. This does not affect overall complexity but reduces number of comparisions.) +*/ + + +/* + +Time Complexity: + O(log N) - Each time the sub-array reduces to half as + N/2 -> N/4 -> N/8 ... after k iterations this results to O(1) + N/ 2^k = 1 + N = 2^k (take a log) + k = log(N) (the complexity is defined by how many times the loop executes which is k times) + + T.C = O(log N) + +Space Complexity: + O(1) - Constant space for storing variables + +*/ + +var searchRange = function(nums, target) { + + let ans = [-1, -1]; + // array of resulting indices pre-initialised with -1 in case the target is not found + + let start = 0, end = nums.length - 1, mid; + + + //First Occurence + while (start <= end) { + mid = Math.floor((start + end) / 2); + + if (nums[mid] === target) { + ans[0] = mid; + end = mid - 1; + //we continue to search in left subarray to find the first occurence position of target value + } + else if (nums[mid] > target) { + end = mid - 1; + } + else { + start = mid + 1; + } + } + + + //Last Occurence + end = nums.length - 1; + while (start <= end) { + mid = Math.floor((start + end) / 2); + + if (nums[mid] === target) { + ans[1] = mid; + start = mid + 1; + //for last occurence we search the subarray right to the middle index + } + else if (nums[mid] > target) { + end = mid - 1; + } + else { + start = mid + 1; + } + } + + return ans; +}; \ No newline at end of file From 63e785adc83c6da727179e5237a261aa6cdf5dbb Mon Sep 17 00:00:00 2001 From: Krishna Dutt Panchagnula Date: Mon, 12 Jun 2023 13:10:16 +0530 Subject: [PATCH 1349/1894] Implemented DutchNationalFlag in go --- sorting/DutchNationalFlag.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 sorting/DutchNationalFlag.go diff --git a/sorting/DutchNationalFlag.go b/sorting/DutchNationalFlag.go new file mode 100644 index 00000000..c5935f46 --- /dev/null +++ b/sorting/DutchNationalFlag.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +// [1,2,0,2,0,1,2,1,0] --> [0,0,0,1,1,1,2,2,2] + +func main() { + array := []int64{2, 0, 1, 2, 1, 0} + result := DutchNationalFlag(array) + fmt.Println(result) + +} + +func DutchNationalFlag(array []int64) []int64 { + + var ( + Low = 0 + Mid = 0 + High = len(array) - 1 + ) + for Mid <= High { + switch array[Mid] { + case 0: + array[Low], array[Mid] = array[Mid], array[Low] + Low++ + Mid++ + case 1: + Mid++ + case 2: + array[Mid], array[High] = array[High], array[Mid] + High-- + } + } + return array + +} From ffdfe22437a11942be8dedcdf30e44c5ca277d44 Mon Sep 17 00:00:00 2001 From: Veena4512 <84694171+Veena4512@users.noreply.github.com> Date: Mon, 12 Jun 2023 19:58:17 +0530 Subject: [PATCH 1350/1894] missing number in py --- Math/Missing_number.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Math/Missing_number.py diff --git a/Math/Missing_number.py b/Math/Missing_number.py new file mode 100644 index 00000000..ee547a88 --- /dev/null +++ b/Math/Missing_number.py @@ -0,0 +1,20 @@ +# Given an array arr[] of size N with integers in the range of [0, N], the task is to find the missing number +# from the first N integers. +# Note: There are no duplicates in the list + +#ISSUE 1445 + +# This code calculates the sum of the given list and the sum of consecutive numbers up to the +# maximum value. The missing number is obtained by subtracting the list sum from the calculated sum, +# and it is printed as the output. + +# input the list +list1=list(map(int,input().split())) +# calculate sum of the list +s=sum(list1) +#find the max of the array and calculate sum of n natural numbers +n=max(list1) +ans=(n*(n+1))//2 +print(ans-s) + +# Time complexity is O(n) \ No newline at end of file From 658314e38204401180f2201d8f7f103126675fdc Mon Sep 17 00:00:00 2001 From: Krishna Dutt Panchagnula Date: Mon, 12 Jun 2023 20:47:47 +0530 Subject: [PATCH 1351/1894] Updated DutchNationalFlag.go with comments and algorithm explanation --- sorting/DutchNationalFlag.go | 56 ++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/sorting/DutchNationalFlag.go b/sorting/DutchNationalFlag.go index c5935f46..151df7f7 100644 --- a/sorting/DutchNationalFlag.go +++ b/sorting/DutchNationalFlag.go @@ -1,36 +1,74 @@ -package main +/* -import "fmt" +The Dutch National Flag algorithm is used to sort an array containing elements with values of 0, 1, and 2. The goal is to rearrange the elements in-place so that all the 0s are grouped at the beginning, followed by all the 1s, and finally all the 2s. -// [1,2,0,2,0,1,2,1,0] --> [0,0,0,1,1,1,2,2,2] +The algorithm uses three pointers: low, mid, and high. The low pointer represents the boundary of the 0s section, the mid pointer scans the array, and the high pointer represents the boundary of the 2s section. -func main() { - array := []int64{2, 0, 1, 2, 1, 0} - result := DutchNationalFlag(array) - fmt.Println(result) +The algorithm iterates through the array and performs the following operations: -} + 1. If the element at the mid pointer is 0, it is swapped with the element at the low pointer, and both pointers are incremented. + 2. If the element at the mid pointer is 1, it is already in the correct section, so the mid pointer is simply incremented. + 3. If the element at the mid pointer is 2, it is swapped with the element at the high pointer, and the high pointer is decremented. + +The iteration continues until the mid pointer crosses the high pointer, indicating that all elements have been processed. + +After the algorithm finishes, the array will be sorted according to the Dutch National Flag problem requirements, with all 0s at the beginning, followed by 1s, and finally 2s. The sorting is done in-place, meaning it does not require any additional space. + +The time complexity of the Dutch National Flag algorithm is O(n), where n is the length of the array, as we only need to iterate through the array once. The space complexity is O(1) since no extra space is used apart from the input array. + +Consider an array: [1, 2, 0, 2, 1, 0]. + +The algorithm uses three pointers: low, mid, and high. Initially, low = 0, mid = 0, and high = 5. + + Iterate while mid <= high: + If the element at mid is 0, swap it with the element at low, increment both low and mid. + If the element at mid is 1, increment mid. + If the element at mid is 2, swap it with the element at high, decrement high. + +After applying the algorithm, the sorted array will be: [0, 0, 1, 1, 2, 2]. + +In this example, the algorithm moves all the 0s to the beginning, followed by the 1s, and finally the 2s, achieving the desired sorting according to the Dutch National Flag problem requirements. +*/ +package main + +import "fmt" func DutchNationalFlag(array []int64) []int64 { + // Initialize Low, Mid, and High pointers var ( Low = 0 Mid = 0 High = len(array) - 1 ) + + // Iterate while Mid pointer is less than or equal to High pointer for Mid <= High { + + // Check the value at Mid pointer switch array[Mid] { + + // Case 0: Value is 0, so swap it with the value at Low pointer + // Increment both Low and Mid pointers to move forward case 0: array[Low], array[Mid] = array[Mid], array[Low] Low++ Mid++ + + // Case 1: Value is 1, no swapping needed + // Increment Mid pointer to move forward case 1: Mid++ + + // Case 2: Value is 2, so swap it with the value at High pointer + // Decrement High pointer to move backward case 2: array[Mid], array[High] = array[High], array[Mid] High-- } } - return array + // Return the sorted array + return array } + From 3c0fbcf0e4eaa7bfc9fd6b6d876317fc9e6ce21f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 12 Jun 2023 23:04:17 +0530 Subject: [PATCH 1352/1894] add explanation --- Arrays/dutch_national_flag.cpp | 39 ++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/Arrays/dutch_national_flag.cpp b/Arrays/dutch_national_flag.cpp index fe4d1a00..47aaa46f 100644 --- a/Arrays/dutch_national_flag.cpp +++ b/Arrays/dutch_national_flag.cpp @@ -1,16 +1,41 @@ +/* + Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. -// Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. -// We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + Input: nums = [2,0,2,1,1,0] + Output: [0,0,1,1,2,2] -// Input: nums = [2,0,2,1,1,0] -// Output: [0,0,1,1,2,2] + Explanation: -// Time and space complexity of the solution -// Time complexity: O(n) -// Space complexity: O(1) + The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements + with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections. + The algorithm iterates through the array using the `low` pointer. Here's how it works: + + 1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element + with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the + next element to process. + + 2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments + the `low` pointer and moves to the next element to process. + + 3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element + with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1. + + The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have + been processed. + + The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array. + It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections. + + Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place + to achieve the sorted order. + + Time complexity: O(n) + Space complexity: O(1) +*/ From dd2ff77896e7fc580b432211969dc8bda2361875 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 12 Jun 2023 23:07:02 +0530 Subject: [PATCH 1353/1894] add dnf in go --- Arrays/dutch_national_flag.go | 68 +++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Arrays/dutch_national_flag.go diff --git a/Arrays/dutch_national_flag.go b/Arrays/dutch_national_flag.go new file mode 100644 index 00000000..bd10ccd7 --- /dev/null +++ b/Arrays/dutch_national_flag.go @@ -0,0 +1,68 @@ +/* + Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + + We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + + Input: nums = [2,0,2,1,1,0] + Output: [0,0,1,1,2,2] + + Explanation: + + The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements + with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections. + + The algorithm iterates through the array using the `low` pointer. Here's how it works: + + 1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element + with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the + next element to process. + + 2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments + the `low` pointer and moves to the next element to process. + + 3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element + with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1. + + The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have + been processed. + + The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array. + It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections. + + Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place + to achieve the sorted order. + + Time complexity: O(n) + Space complexity: O(1) +*/ +package main + +import "fmt" + +func sortColors(nums []int) { + start := 0 + low := 0 + end := len(nums) - 1 + + for low <= end { + if nums[low] == 0 { + // Swap the element at low with the element at start + nums[low], nums[start] = nums[start], nums[low] + start++ + low++ + } else if nums[low] == 1 { + // Move to the next element + low++ + } else { + // Swap the element at low with the element at end + nums[low], nums[end] = nums[end], nums[low] + end-- + } + } +} + +func main() { + nums := []int{2, 0, 2, 1, 1, 0} + sortColors(nums) + fmt.Println(nums) +} From 00167432beb8e5b9f9789804c018911ea0055169 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 12 Jun 2023 23:07:07 +0530 Subject: [PATCH 1354/1894] add dnf in js --- Arrays/dutch_national_flag.java | 72 +++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Arrays/dutch_national_flag.java diff --git a/Arrays/dutch_national_flag.java b/Arrays/dutch_national_flag.java new file mode 100644 index 00000000..04a5a4b3 --- /dev/null +++ b/Arrays/dutch_national_flag.java @@ -0,0 +1,72 @@ +/* + Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + + We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + + Input: nums = [2,0,2,1,1,0] + Output: [0,0,1,1,2,2] + + Explanation: + + The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements + with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections. + + The algorithm iterates through the array using the `low` pointer. Here's how it works: + + 1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element + with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the + next element to process. + + 2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments + the `low` pointer and moves to the next element to process. + + 3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element + with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1. + + The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have + been processed. + + The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array. + It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections. + + Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place + to achieve the sorted order. + + Time complexity: O(n) + Space complexity: O(1) +*/ +public class Main { + public static void sortColors(int[] nums) { + int start = 0; + int low = 0; + int end = nums.length - 1; + + while (low <= end) { + if (nums[low] == 0) { + // Swap the element at low with the element at start + int temp = nums[low]; + nums[low] = nums[start]; + nums[start] = temp; + start++; + low++; + } else if (nums[low] == 1) { + // Move to the next element + low++; + } else { + // Swap the element at low with the element at end + int temp = nums[low]; + nums[low] = nums[end]; + nums[end] = temp; + end--; + } + } + } + + public static void main(String[] args) { + int[] nums = {2, 0, 2, 1, 1, 0}; + sortColors(nums); + for (int num : nums) { + System.out.print(num + " "); + } + } +} From 9dbf6b0fa4dcfc3e47f715654b4ff04819401ba4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 12 Jun 2023 23:07:20 +0530 Subject: [PATCH 1355/1894] add dnf in js --- Arrays/dutch_national_flag.js | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Arrays/dutch_national_flag.js diff --git a/Arrays/dutch_national_flag.js b/Arrays/dutch_national_flag.js new file mode 100644 index 00000000..b153a626 --- /dev/null +++ b/Arrays/dutch_national_flag.js @@ -0,0 +1,63 @@ +/* + Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + + We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + + Input: nums = [2,0,2,1,1,0] + Output: [0,0,1,1,2,2] + + Explanation: + + The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements + with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections. + + The algorithm iterates through the array using the `low` pointer. Here's how it works: + + 1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element + with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the + next element to process. + + 2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments + the `low` pointer and moves to the next element to process. + + 3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element + with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1. + + The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have + been processed. + + The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array. + It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections. + + Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place + to achieve the sorted order. + + Time complexity: O(n) + Space complexity: O(1) +*/ +function sortColors(nums) { + let start = 0; + let low = 0; + let end = nums.length - 1; + + while (low <= end) { + if (nums[low] === 0) { + // Swap the element at low with the element at start + [nums[low], nums[start]] = [nums[start], nums[low]]; + start++; + low++; + } else if (nums[low] === 1) { + // Move to the next element + low++; + } else { + // Swap the element at low with the element at end + [nums[low], nums[end]] = [nums[end], nums[low]]; + end--; + } + } +} + +// Example usage: +const nums = [2, 0, 2, 1, 1, 0]; +sortColors(nums); +console.log(nums); From 0d5dbd561acbb4d7a404d9e6e8192388b37073a3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 12 Jun 2023 23:07:28 +0530 Subject: [PATCH 1356/1894] add dnf in python --- Arrays/dutch_national_flag.py | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Arrays/dutch_national_flag.py diff --git a/Arrays/dutch_national_flag.py b/Arrays/dutch_national_flag.py new file mode 100644 index 00000000..405e264b --- /dev/null +++ b/Arrays/dutch_national_flag.py @@ -0,0 +1,60 @@ +''' + Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. + + We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. + + Input: nums = [2,0,2,1,1,0] + Output: [0,0,1,1,2,2] + + Explanation: + + The algorithm partitions the array into three sections: elements with the value 0, elements with the value 1, and elements + with the value 2. It uses three pointers, `start`, `low`, and `end`, to keep track of the boundaries between these sections. + + The algorithm iterates through the array using the `low` pointer. Here's how it works: + + 1. If the element at `low` is 0, it means it should be in the first section. In this case, the algorithm swaps the element + with the element at the `start` position, increments both `start` and `low` pointers, and moves the `low` pointer to the + next element to process. + + 2. If the element at `low` is 1, it means it should be in the second section. In this case, the algorithm simply increments + the `low` pointer and moves to the next element to process. + + 3. If the element at `low` is 2, it means it should be in the third section. In this case, the algorithm swaps the element + with the element at the `end` position, decrements the `end` pointer, and moves the `low` pointer to the next element to process. The reason for moving the `low` pointer to the next element is to recheck the value after the swap, as the swapped element could be 0 or 1. + + The algorithm continues these steps until the `low` pointer surpasses the `end` pointer, indicating that all elements have + been processed. + + The "Dutch National Flag" algorithm has a time complexity of O(n), where n is the size of the input array. + It performs a single pass through the array, ensuring that all elements are correctly placed in their respective sections. + + Note that the code assumes the input vector `nums` contains only values 0, 1, and 2, and it modifies the vector in-place + to achieve the sorted order. + + Time complexity: O(n) + Space complexity: O(1) +''' +def sortColors(nums): + start = 0 + low = 0 + end = len(nums) - 1 + + while low <= end: + if nums[low] == 0: + # Swap the element at low with the element at start + nums[low], nums[start] = nums[start], nums[low] + start += 1 + low += 1 + elif nums[low] == 1: + # Move to the next element + low += 1 + else: + # Swap the element at low with the element at end + nums[low], nums[end] = nums[end], nums[low] + end -= 1 + +# Example usage: +nums = [2, 0, 2, 1, 1, 0] +sortColors(nums) +print(nums) From 790607176e00090fbb59e5e0ac968f82467ad6d1 Mon Sep 17 00:00:00 2001 From: Veena4512 <84694171+Veena4512@users.noreply.github.com> Date: Tue, 13 Jun 2023 06:50:11 +0530 Subject: [PATCH 1357/1894] missing number in python --- Math/{Missing_number.py => missing_number.py} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename Math/{Missing_number.py => missing_number.py} (84%) diff --git a/Math/Missing_number.py b/Math/missing_number.py similarity index 84% rename from Math/Missing_number.py rename to Math/missing_number.py index ee547a88..7f8959e1 100644 --- a/Math/Missing_number.py +++ b/Math/missing_number.py @@ -9,12 +9,12 @@ # and it is printed as the output. # input the list -list1=list(map(int,input().split())) +list1 = list(map(int, input().split())) # calculate sum of the list -s=sum(list1) +s = sum(list1) #find the max of the array and calculate sum of n natural numbers -n=max(list1) -ans=(n*(n+1))//2 +n = max(list1) +ans = (n*(n+1))//2 print(ans-s) # Time complexity is O(n) \ No newline at end of file From f383344f1002e6cde4504276a8aa7a2ca1e0a4c0 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Tue, 13 Jun 2023 07:41:08 +0530 Subject: [PATCH 1358/1894] Create Queue using stack.java >>added time and space complexity >>added line comments to understand code --- Queue using stack.java | 96 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Queue using stack.java diff --git a/Queue using stack.java b/Queue using stack.java new file mode 100644 index 00000000..3923ed75 --- /dev/null +++ b/Queue using stack.java @@ -0,0 +1,96 @@ +/* +Issue:#253 +Author:maneesha +Date:13/06/2023 +##Assignee:Mani1881 +//About: + +Implement Queue using Stacks in java +//Input: + +>>Implement a first in first out (FIFO) queue using only two stacks. +>>The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). +Implement the MyQueue class: +~void push(int x) Pushes element x to the back of the queue. +~int pop() Removes the element from the front of the queue and returns it. +~int peek() Returns the element at the front of the queue. +~boolean empty() Returns true if the queue is empty, false . +//Complexity: + +>>Time Complexity +push:O(n) +pop:O(1) +peek:O(1) +empty:O(1) +>>Space Complexity:O(n) +//Explanation + +>>The provided code implements a queue using two stacks (`s1` and `s2`). +>>The `push()` method transfers elements from `s1` to `s2`, adds the new element to `s1`, and then transfers elements back to `s1`. +>>The `pop()` method removes and returns the top element of `s1`. +>>The `peek()` method returns the top element of `s1` without removing it. +>>The `empty()` method checks if `s1` is empty. +>>This implementation maintains FIFO order. +*/ +class MyQueue +{ +Stacks1=new Stack(); +Stacks2=new Stack(); + + public void push(int x) + { + while(!s1.isEmpty()) + { + s2.push(s1.pop()); + } + s1.push(x); + while(!s2.empty()) + { + s1.push(s2.pop()); + } + } + + public int pop() + { + return s1.pop(); + } + + public int peek() + { + return s1.peek(); + } + + public boolean empty() + { + return s1.isEmpty(); + } + public static void main(String[] args) + { + MyQueue queue = new MyQueue(); + + // Pushing elements into the queue + queue.push(1); + queue.push(2); + queue.push(3); + + // Checking the front element of the queue + System.out.println("Front element: " + queue.peek()); // Output: Front element: 1 + + // Removing elements from the queue + System.out.println("Removed element: " + queue.pop()); // Output: Removed element: 1 + System.out.println("Removed element: " + queue.pop()); // Output: Removed element: 2 + + // Checking if the queue is empty + System.out.println("Is the queue empty? " + queue.empty()); // Output: Is the queue empty? false + + // Pushing another element into the queue + queue.push(4); + + // Removing the remaining elements from the queue + System.out.println("Removed element: " + queue.pop()); // Output: Removed element: 3 + System.out.println("Removed element: " + queue.pop()); // Output: Removed element: 4 + + // Checking if the queue is empty after removing all elements + System.out.println("Is the queue empty? " + queue.empty()); // Output: Is the queue empty? true +} +} From b6738e8c9187178f0980e7db3205cda9551e647e Mon Sep 17 00:00:00 2001 From: Aryan2314 <100805168+Aryan2314@users.noreply.github.com> Date: Tue, 13 Jun 2023 19:23:22 +0530 Subject: [PATCH 1359/1894] Add Dutch National Flag problem implementation in JavaScript --- sorting/dutch_national_flag_problem.js | 52 ++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 sorting/dutch_national_flag_problem.js diff --git a/sorting/dutch_national_flag_problem.js b/sorting/dutch_national_flag_problem.js new file mode 100644 index 00000000..063ab875 --- /dev/null +++ b/sorting/dutch_national_flag_problem.js @@ -0,0 +1,52 @@ +/* + Dutch National Flag Problem + + Given an array containing only 0s, 1s, and 2s, sort the array in a single traversal. + + Sample Input: [0, 2, 1, 2, 0] + Sample Output: [0, 0, 1, 2, 2] + + Approach: + - We can use three pointers, low, mid, and high, to divide the array into three regions: + 1. 0s region: elements before the low pointer (excluding low) are 0s + 2. 1s region: elements between the low and mid pointers (excluding mid) are 1s + 3. 2s region: elements after the high pointer (excluding high) are 2s + - Initialize low and mid pointers to the start of the array (0 index) and high pointer to the end of the array (array.length - 1). + - Iterate while the mid pointer is less than or equal to the high pointer: + - If the current element at mid is 0, swap it with the element at low and increment both low and mid pointers. + - If the current element at mid is 1, it is already in the correct region, so we just increment the mid pointer. + - If the current element at mid is 2, swap it with the element at high and decrement the high pointer. + - Repeat the above steps until the mid pointer crosses the high pointer. + - At the end, the array will be sorted in place. + + Time Complexity: O(n), where n is the length of the array. + Space Complexity: O(1), no additional space is used. + + Further Reading: https://en.wikipedia.org/wiki/Dutch_national_flag_problem +*/ + +function dutchNationalFlagProblem(arr) { + let low = 0; + let mid = 0; + let high = arr.length - 1; + + while (mid <= high) { + if (arr[mid] === 0) { + [arr[mid], arr[low]] = [arr[low], arr[mid]]; + low++; + mid++; + } else if (arr[mid] === 1) { + mid++; + } else { + [arr[mid], arr[high]] = [arr[high], arr[mid]]; + high--; + } + } + + return arr; +} + +// Test the function +const input = [0, 2, 1, 2, 0]; +const output = dutchNationalFlagProblem(input); +console.log(output); From 444e4c965c7f9dae1c4c40ac5a6427accd67547e Mon Sep 17 00:00:00 2001 From: Aryan Sharma <128261659+Aryan-d13@users.noreply.github.com> Date: Tue, 13 Jun 2023 19:42:11 +0530 Subject: [PATCH 1360/1894] Update dutch_national_flag_problem.js --- sorting/dutch_national_flag_problem.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sorting/dutch_national_flag_problem.js b/sorting/dutch_national_flag_problem.js index 063ab875..e30836e3 100644 --- a/sorting/dutch_national_flag_problem.js +++ b/sorting/dutch_national_flag_problem.js @@ -32,13 +32,18 @@ function dutchNationalFlagProblem(arr) { while (mid <= high) { if (arr[mid] === 0) { + // Swap current element at mid with element at low [arr[mid], arr[low]] = [arr[low], arr[mid]]; + // Increment both low and mid pointers low++; mid++; } else if (arr[mid] === 1) { + // Move to the next element in the 1s region mid++; } else { + // Swap current element at mid with element at high [arr[mid], arr[high]] = [arr[high], arr[mid]]; + // Decrement the high pointer high--; } } From 04503ab27393aa1538ede01bc60ec4d208c06eb2 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Tue, 13 Jun 2023 20:12:24 +0530 Subject: [PATCH 1361/1894] renamed as queue using stack.java >>added sample io --- ...e using stack.java => queue using stack.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) rename Queue using stack.java => queue using stack.java (85%) diff --git a/Queue using stack.java b/queue using stack.java similarity index 85% rename from Queue using stack.java rename to queue using stack.java index 3923ed75..c6d8fe66 100644 --- a/Queue using stack.java +++ b/queue using stack.java @@ -15,6 +15,20 @@ >>The implemented queue should support all the functions of a normal queue (push ~int pop() Removes the element from the front of the queue and returns it. ~int peek() Returns the element at the front of the queue. ~boolean empty() Returns true if the queue is empty, false . +//Example: + +>> Sample Input: +["MyQueue", "push", "push", "peek", "pop", "empty"] +[[], [1], [2], [], [], []] +>>Sample Output: +[null, null, null, 1, 1, false] +Explanation +MyQueue myQueue = new MyQueue(); +myQueue.push(1); // queue is: [1](here we are not returning push element so in output we got null) +myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) +myQueue.peek(); // return 1 +myQueue.pop(); // return 1, queue is [2] +myQueue.empty(); // return false //Complexity: >>Time Complexity @@ -23,6 +37,8 @@ >>The implemented queue should support all the functions of a normal queue (push peek:O(1) empty:O(1) >>Space Complexity:O(n) +//Example: + //Explanation >>The provided code implements a queue using two stacks (`s1` and `s2`). From 85da3558e5b0f65773848baa570b4f9639be0323 Mon Sep 17 00:00:00 2001 From: Harxsh Date: Wed, 14 Jun 2023 00:23:37 +0530 Subject: [PATCH 1362/1894] Dutch National Flag Problem Implemented in Python #1441 --- sorting/dutch_national_flag_problem.py | 57 ++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 sorting/dutch_national_flag_problem.py diff --git a/sorting/dutch_national_flag_problem.py b/sorting/dutch_national_flag_problem.py new file mode 100644 index 00000000..b12c42d5 --- /dev/null +++ b/sorting/dutch_national_flag_problem.py @@ -0,0 +1,57 @@ +# Approach Explanation: +# The code implements the Dutch National Flag problem, which is a sorting problem where we need to sort an array consisting of 0s, 1s, and 2s in ascending order. The approach used is called the "Three Pointers" approach. + +# We initialize three pointers, low, mid, and high, which represent the boundaries of three sections in the array: + +# All elements before low are 0s (left section). +# All elements between low and mid are 1s (middle section). +# All elements after high are 2s (right section). +# We iterate through the array using the mid pointer: + +# If the element at mid is 0, we swap it with the element at low and increment both low and mid pointers. +# If the element at mid is 1, we increment the mid pointer. +# If the element at mid is 2, we swap it with the element at high and decrement the high pointer. +# By doing this, we move all the 0s to the left section, 1s to the middle section, and 2s to the right section, effectively sorting the array. + +# Time Complexity: O(n), where n is the length of the input array. +# Space Complexity: O(1) (constant space), as we are sorting the array in-place + +# Sample Input: +# arr = [2, 0, 1, 2, 1, 0] + +# Sample Output: +# Input Array: [2, 0, 1, 2, 1, 0] +# Output Array: [0, 0, 1, 1, 2, 2] + + +def dutch_national_flag_problem(arr): + # Initialize variables for the three pointers + low = 0 + mid = 0 + high = len(arr) - 1 + + # Loop through the array until mid and high pointers meet + while mid <= high: + if arr[mid] == 0: + # Swap the element at mid with the element at low + arr[mid], arr[low] = arr[low], arr[mid] + # Move the low and mid pointers to the right + low += 1 + mid += 1 + elif arr[mid] == 1: + # Increment the mid pointer + mid += 1 + else: + # Swap the element at mid with the element at high + arr[mid], arr[high] = arr[high], arr[mid] + # Move the high pointer to the left + high -= 1 + + return arr + + +# Test the function +arr = [2, 0, 1, 2, 1, 0] +result = dutch_national_flag_problem(arr) +print("Input Array:", arr) +print("Output Array:", result) \ No newline at end of file From 3ccf3274e53fa85e7146ad8ee329cc0363681970 Mon Sep 17 00:00:00 2001 From: Aryan2314 <100805168+Aryan2314@users.noreply.github.com> Date: Wed, 14 Jun 2023 00:38:36 +0530 Subject: [PATCH 1363/1894] Implemented Dutch National Flag Problem in Java --- sorting/DutchNationalFlag.java | 74 ++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 sorting/DutchNationalFlag.java diff --git a/sorting/DutchNationalFlag.java b/sorting/DutchNationalFlag.java new file mode 100644 index 00000000..8601dddf --- /dev/null +++ b/sorting/DutchNationalFlag.java @@ -0,0 +1,74 @@ +package sorting; + +/* + *Explanation: +The code above solves the Dutch National Flag problem. It takes an array of integers and a pivot element as input, and sorts the array in the Dutch National Flag order. The Dutch National Flag problem involves partitioning the array into three sections based on the pivot element. + +The dutchNationalFlagSort method uses three pointers: low, mid, and high. The low pointer represents the boundary for elements less than the pivot, the mid pointer represents the boundary for elements equal to the pivot, and the high pointer represents the boundary for elements greater than the pivot. + +The method uses a while loop that continues until the mid pointer surpasses the high pointer. Inside the loop, it compares the element at the mid index with the pivot. If the element is less than the pivot, it swaps it with the element at the low index and increments both low and mid. If the element is greater than the pivot, it swaps it with the element at the high index and decrements high. If the element is equal to the pivot, it increments mid. + +The swap method is a helper function that swaps two elements in the array. + +In the main method, an example array and pivot value are provided. The dutchNationalFlagSort method is called with these values, and the sorted array is printed. + +Time Complexity: The time complexity of the Dutch National Flag algorithm is O(n), where n is the length of the input array. + +Space Complexity: The space complexity is O(1) as the algorithm sorts the array in-place without using any additional data structures. +**/ +import java.util.Arrays; + +public class DutchNationalFlag { + + /** + * Sorts an array of integers in the Dutch National Flag order. + * The Dutch National Flag problem partitions the array into three sections: + * - All elements less than the pivot are placed before it. + * - All elements greater than the pivot are placed after it. + * - All elements equal to the pivot are placed in the middle. + * + * @param array the array of integers to be sorted + * @param pivot the pivot element + */ + public static void main(String[] args) { + int[] array = {2, 2, 1, 1, 0, 0, 2, 1, 0}; + int pivot = 1; + + dutchNationalFlagSort(array, pivot); + + System.out.println("Sorted Array: " + Arrays.toString(array)); + } + + public static void dutchNationalFlagSort(int[] array, int pivot) { + int low = 0; // Pointer for elements less than the pivot + int mid = 0; // Pointer for elements equal to the pivot + int high = array.length - 1; // Pointer for elements greater than the pivot + + while (mid <= high) { + if (array[mid] < pivot) { // Current element is less than the pivot + swap(array, low, mid); // Swap current element with element at the low index + low++; // Increment low pointer + mid++; // Increment mid pointer + } else if (array[mid] > pivot) { // Current element is greater than the pivot + swap(array, mid, high); // Swap current element with element at the high index + high--; // Decrement high pointer + } else { // Current element is equal to the pivot + mid++; // Increment mid pointer + } + } + } + + /** + * Swaps two elements in an array. + * + * @param array the array + * @param i the index of the first element + * @param j the index of the second element + */ + private static void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} + From a803faa8b06af192e6fddc1dc4fe08aa36875921 Mon Sep 17 00:00:00 2001 From: JustHarxsh <114770088+JustHarxsh@users.noreply.github.com> Date: Wed, 14 Jun 2023 00:38:40 +0530 Subject: [PATCH 1364/1894] Minimum insertion steps to make a palindrome --- ...insertion_steps_for_string_palindrome.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Dynamic Programming/min_insertion_steps_for_string_palindrome.java diff --git a/Dynamic Programming/min_insertion_steps_for_string_palindrome.java b/Dynamic Programming/min_insertion_steps_for_string_palindrome.java new file mode 100644 index 00000000..741e77dd --- /dev/null +++ b/Dynamic Programming/min_insertion_steps_for_string_palindrome.java @@ -0,0 +1,45 @@ +/* + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) +*/ + +public class PalindromeInsertion { + public static int findMinInsertions(String s) { + int n = s.length(); + int[][] dp = new int[n][n]; + + for (int len = 2; len <= n; len++) { + for (int i = 0; i <= n - len; i++) { + int j = i + len - 1; + if (s.charAt(i) == s.charAt(j)) + dp[i][j] = dp[i + 1][j - 1]; + else + dp[i][j] = Math.min(dp[i][j - 1], dp[i + 1][j]) + 1; + } + } + + return dp[0][n - 1]; + } + + public static void main(String[] args) { + String input = "abcde"; + int minInsertions = findMinInsertions(input); + System.out.println("Minimum insertions required: " + minInsertions); + } +} From 87819ed075094c0ed4b86cfe58e2ac6dfcbd0648 Mon Sep 17 00:00:00 2001 From: Sumit Dethe <91131672+sumitdethe27@users.noreply.github.com> Date: Wed, 14 Jun 2023 15:21:04 +0000 Subject: [PATCH 1365/1894] n-queens resolved #364 --- Backtracking/N-queens.java | 112 +++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 Backtracking/N-queens.java diff --git a/Backtracking/N-queens.java b/Backtracking/N-queens.java new file mode 100644 index 00000000..5070d2c0 --- /dev/null +++ b/Backtracking/N-queens.java @@ -0,0 +1,112 @@ +/** + * Problem :- N-Queens + https://leetcode.com/problems/n-queens/description/ + + + Approach:- + The approach uses backtracking to generate all possible configurations of queens on the board and checks the validity of each configuration. + It maintains a boolean board to represent the placement of queens, where `true` indicates the presence of a queen in a particular cell. + The algorithm starts by placing a queen in the first row and proceeds recursively to the next row, checking all possible column positions for the queen. + If a valid position is found, the algorithm moves to the next row and repeats the process. If all N queens are placed on the board, + a valid solution is found and added to the list of solutions. + + +To check the validity of a queen's position, the algorithm verifies three conditions: +1. Vertical Check: It checks the columns of the previous rows to ensure that there are no queens in the same column. +2. Left Diagonal Check: It checks the diagonal elements on the left side of the current position to ensure that there are no queens present. +3. Right Diagonal Check: It checks the diagonal elements on the right side of the current position to ensure that there are no queens present. + +The algorithm continues this process, backtracking whenever it encounters an invalid position or explores all possibilities. Once all valid configurations are found, they are converted into a list of strings representing the board configurations, and the list of solutions is returned. + + + + +Time Complexity: O(N!) + In the worst case, the backtracking algorithm explores all possible configurations,. However, with pruning techniques, the actual runtime is significantly lower. + +Space Complexity: O(N^2) + because the boolean board of size NxN is used to represent the placement of queens, and the list of solutions also occupies additional space. + + */ + +class Solution { + public List> solveNQueens(int n) { + List> list = new ArrayList<>(); + + // If the board size is 2 or 3, no solution is possible, so return an empty list + if (n == 2 || n == 3) { + return list; + } + + // If the board size is 1, there is only one solution with a single queen in the only cell + if (n == 1) { + String ans = "Q"; + ArrayList a = new ArrayList<>(); + a.add(ans); + list.add(a); + return list; + } + + boolean arr[][] = new boolean[n][n]; // Create a boolean board to represent the placement of queens + queens(arr, 0, list); // Solve the N-queens problem recursively + return list; // Return the list of solutions + } + + // Recursive function to solve the N-queens problem + static void queens(boolean board[][], int row, List> list) { + if (row == board.length) { + ArrayList arr = new ArrayList<>(); + + // Convert the boolean board to a list of strings representing the board configuration + for (int j = 0; j < board.length; j++) { + String ans = ""; + for (int i = 0; i < board[j].length; i++) { + if (board[j][i] == false) { + ans += "."; + } else { + ans += "Q"; + } + } + arr.add(ans); + } + list.add(arr); // Add the board configuration to the list of solutions + return; + } + + for (int col = 0; col < board.length; col++) { + if (isSafe(board, row, col)) { + board[row][col] = true; // Place a queen in the current position + queens(board, row + 1, list); // Recursively solve the problem for the next row + board[row][col] = false; // Backtrack and remove the queen from the current position + } + } + } + + // Function to check if it is safe to place a queen in a given position + private static boolean isSafe(boolean[][] board, int row, int col) { + // Check the vertical column for any previously placed queens + for (int i = 1; i <= row; i++) { + if (board[row - i][col]) { + return false; + } + } + + // Check the left diagonal for any previously placed queens + int max = Math.min(row, col); + for (int i = 1; i <= max; i++) { + if (board[row - i][col - i]) { + return false; + } + } + + // Check the right diagonal for any previously placed queens + int maxtimes = Math.min(row, board.length - col - 1); + for (int i = 1; i <= maxtimes; i++) { + if (board[row - i][col + i]) { + return false; + } + } + + return true; // It is safe to place a queen in the given position + } +} From 3869a2b9d669cf02b1692e512319673ca252fddb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Wed, 14 Jun 2023 23:25:36 +0530 Subject: [PATCH 1366/1894] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4bd62e8a..0c2bc378 100644 --- a/README.md +++ b/README.md @@ -545,7 +545,7 @@ The pointers can be used to iterate the data structure in one or both directions - Valid Pallindrome [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.js) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.py) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/is_pallindrome.java) -- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_word_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.js) +- Reverse Word in a String [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.go) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.jd) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.cpp) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/reverse_words_in_a_string.java) - Valid Pallindrome II [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.go) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.py) [Javascript](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.js) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Strings/valid_pallindrome2.java) From 43a0b06aa95c7adaddbe49fe4f0438b2fbfef674 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 14 Jun 2023 23:26:31 +0530 Subject: [PATCH 1367/1894] rename file --- Strings/{Knuth_Morris_Pratt_Algorithm.js => kmp.js} | 0 Strings/{KnuthMorrisPratt Algorithm.py => kmp.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Strings/{Knuth_Morris_Pratt_Algorithm.js => kmp.js} (100%) rename Strings/{KnuthMorrisPratt Algorithm.py => kmp.py} (100%) diff --git a/Strings/Knuth_Morris_Pratt_Algorithm.js b/Strings/kmp.js similarity index 100% rename from Strings/Knuth_Morris_Pratt_Algorithm.js rename to Strings/kmp.js diff --git a/Strings/KnuthMorrisPratt Algorithm.py b/Strings/kmp.py similarity index 100% rename from Strings/KnuthMorrisPratt Algorithm.py rename to Strings/kmp.py From d1574046b5685e77ee3ddfcca288c37efec029ae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 14 Jun 2023 23:26:57 +0530 Subject: [PATCH 1368/1894] move to famous algo folder --- {Strings => Famous Algorithms}/kmp.js | 0 {Strings => Famous Algorithms}/kmp.py | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {Strings => Famous Algorithms}/kmp.js (100%) rename {Strings => Famous Algorithms}/kmp.py (100%) diff --git a/Strings/kmp.js b/Famous Algorithms/kmp.js similarity index 100% rename from Strings/kmp.js rename to Famous Algorithms/kmp.js diff --git a/Strings/kmp.py b/Famous Algorithms/kmp.py similarity index 100% rename from Strings/kmp.py rename to Famous Algorithms/kmp.py From 5be7bff606070a4a4ad77eb5693c496548027509 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:28:35 +0530 Subject: [PATCH 1369/1894] add kadanes in go --- Famous Algorithms/kadanes.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Famous Algorithms/kadanes.go diff --git a/Famous Algorithms/kadanes.go b/Famous Algorithms/kadanes.go new file mode 100644 index 00000000..e490c760 --- /dev/null +++ b/Famous Algorithms/kadanes.go @@ -0,0 +1,28 @@ +package main + +// KadanesAlgorithm computes the maximum sum subarray using Kadane's algorithm +func KadanesAlgorithm(array []int) int { + // Initialize maxEndingHere and maxSoFar to the first element of the array + maxEndingHere, maxSoFar := array[0], array[0] + + // Loop through the array starting from the second element + for _, num := range array[1:] { + // Compute the maximum subarray sum ending at the current element + maxEndingHere = max(maxEndingHere+num, num) + + // Update maxSoFar if the current maximum subarray sum is greater + maxSoFar = max(maxEndingHere, maxSoFar) + } + + // Return the maximum subarray sum + return maxSoFar +} + +// max returns the maximum of two integers +func max(a, b int) int { + if a > b { + return a + } + return b +} + q \ No newline at end of file From dac8ea8b37c57639b423cdfc400136827ec2ed71 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:30:09 +0530 Subject: [PATCH 1370/1894] add question --- Famous Algorithms/kadanes.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Famous Algorithms/kadanes.go b/Famous Algorithms/kadanes.go index e490c760..ff45df66 100644 --- a/Famous Algorithms/kadanes.go +++ b/Famous Algorithms/kadanes.go @@ -1,3 +1,10 @@ +/* + Write a function that takes in a non-empty array of integers and returns the + maximum sum that can be obtained by summing up all of the integers in a + non-empty subarray of the input array. A subarray must only contain adjacent + numbers (numbers next to each other in the input array). + +*/ package main // KadanesAlgorithm computes the maximum sum subarray using Kadane's algorithm From 1f898d0b8e8d973a9b6ae699743ee097069e5d84 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:31:51 +0530 Subject: [PATCH 1371/1894] add explanation and time space complexity --- Famous Algorithms/kadanes.go | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/Famous Algorithms/kadanes.go b/Famous Algorithms/kadanes.go index ff45df66..c26e5c17 100644 --- a/Famous Algorithms/kadanes.go +++ b/Famous Algorithms/kadanes.go @@ -1,8 +1,28 @@ /* - Write a function that takes in a non-empty array of integers and returns the - maximum sum that can be obtained by summing up all of the integers in a - non-empty subarray of the input array. A subarray must only contain adjacent - numbers (numbers next to each other in the input array). + Write a function that takes in a non-empty array of integers and returns the + maximum sum that can be obtained by summing up all of the integers in a + non-empty subarray of the input array. A subarray must only contain adjacent + numbers (numbers next to each other in the input array). + + Sample Input: [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4] + Output: 19 + + Explanation: + + The function takes an array of integers as input, and initializes two variables: `maxEndingHere` and `maxSoFar`. + `maxEndingHere` keeps track of the maximum subarray sum that ends at the current element, and `maxSoFar` keeps track + of the maximum subarray sum seen so far. + + The function then iterates through the array starting at the second element, and for each element, it calculates the + maximum subarray sum that ends at that element by adding the current element to the maximum subarray sum that ends at + the previous element (`maxEndingHere + num`). If this sum is greater than the current element itself (`num`), then `maxEndingHere` is updated to the sum. Otherwise, `maxEndingHere` is updated to `num`. + + After each iteration, `maxSoFar` is updated to the maximum value seen so far, which is either `maxEndingHere` or `maxSoFar`. + + The function finally returns `maxSoFar`, which represents the maximum subarray sum of the input array. The `max` function + is a helper function used to compare two integers and return the maximum of the two. + + O(n) time | O(1) space - where n is the length of the input array */ package main From 9f765861005d17d7294e4b1497465edc25c2f837 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:32:12 +0530 Subject: [PATCH 1372/1894] rename file --- Famous Algorithms/{kadanes.go => kadanes_algorithm.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Famous Algorithms/{kadanes.go => kadanes_algorithm.go} (100%) diff --git a/Famous Algorithms/kadanes.go b/Famous Algorithms/kadanes_algorithm.go similarity index 100% rename from Famous Algorithms/kadanes.go rename to Famous Algorithms/kadanes_algorithm.go From df228913b2f0af5d347fb9e94f716c237f55b84f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:34:53 +0530 Subject: [PATCH 1373/1894] rename file --- .../{Knight -Probability.go => knight_probability_chessboard.go} | 0 ...bability_in_Chessboard.js => knight_probability_chessboard.js} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{Knight -Probability.go => knight_probability_chessboard.go} (100%) rename Dynamic Programming/{Knight_Probability_in_Chessboard.js => knight_probability_chessboard.js} (100%) diff --git a/Dynamic Programming/Knight -Probability.go b/Dynamic Programming/knight_probability_chessboard.go similarity index 100% rename from Dynamic Programming/Knight -Probability.go rename to Dynamic Programming/knight_probability_chessboard.go diff --git a/Dynamic Programming/Knight_Probability_in_Chessboard.js b/Dynamic Programming/knight_probability_chessboard.js similarity index 100% rename from Dynamic Programming/Knight_Probability_in_Chessboard.js rename to Dynamic Programming/knight_probability_chessboard.js From 1d9d53f07798f5970c846a4b39c1554515edbd88 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:37:03 +0530 Subject: [PATCH 1374/1894] remove duplicate --- Linked List/Floyd_cycle_detection_algo.java | 56 --------------------- 1 file changed, 56 deletions(-) delete mode 100644 Linked List/Floyd_cycle_detection_algo.java diff --git a/Linked List/Floyd_cycle_detection_algo.java b/Linked List/Floyd_cycle_detection_algo.java deleted file mode 100644 index 47f3da29..00000000 --- a/Linked List/Floyd_cycle_detection_algo.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - Problem :- Linked list cycle - https://leetcode.com/problems/linked-list-cycle/description/ - - Approach:- - 1. Set two pointer on head, slow 's' and a fast 'f' pointer . - 2. The slow pointer will move one step and the fast pointer will move twice the speed of slow pointer. - 3. If the slow and fast pointer meet i.e s==f , it means there is a cycle present. - Hence they will meet a some point(return true if(s==f)). - 4. If the fast pointer is null or its next is null means there is no cycle(return false). - - - - Time Complexity:- O(N) - Even if there is a cycle exists we traverse the given list, Hence * linear time *. - - Space Complexity:- O(1) - No extra space is required. - - - - */ - - - -// Easy Solution will well documented code . - -/** - * Definition for singly-linked list. - * class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { - * val = x; - * next = null; - * } - * } - */ -public class Solution { - public boolean hasCycle(ListNode head) { - if (head == null || head.next == null) - return false; - ListNode s = head; // slow pointer - ListNode f = head; // fast pointer - - while (f != null && f.next != null) { - s = s.next; // move slow pointer by 1 step - f = f.next.next; // move fast pointer by 2 steps - - if (s == f) // if slow and fast pointers meet, there is a cycle - return true; - } - - return false; // if fast pointer reaches the end, there is no cycle - } -} From a43279e0f0ce52f297127e2ab6ed8c0fef5ceeba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 15 Jun 2023 19:37:08 +0530 Subject: [PATCH 1375/1894] rename file --- .../{floydsCycleDetection.cpp => floyds_cycle_detection.cpp} | 0 .../{floydsCycleDetection.java => floyds_cycle_detection.java} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Linked List/{floydsCycleDetection.cpp => floyds_cycle_detection.cpp} (100%) rename Linked List/{floydsCycleDetection.java => floyds_cycle_detection.java} (100%) diff --git a/Linked List/floydsCycleDetection.cpp b/Linked List/floyds_cycle_detection.cpp similarity index 100% rename from Linked List/floydsCycleDetection.cpp rename to Linked List/floyds_cycle_detection.cpp diff --git a/Linked List/floydsCycleDetection.java b/Linked List/floyds_cycle_detection.java similarity index 100% rename from Linked List/floydsCycleDetection.java rename to Linked List/floyds_cycle_detection.java From c22db865af2e7185bea2cbd18d56619762d24e7b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Thu, 15 Jun 2023 19:39:46 +0530 Subject: [PATCH 1376/1894] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c2bc378..f37eddb1 100644 --- a/README.md +++ b/README.md @@ -563,7 +563,7 @@ The key idea is that the pointers start at the same location, but they move forw ## Practice problems for fast and slow pointers -- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) +- Linked List cycle detection [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_floyds_cycle_detection.cpp) [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/floyds_cycle_detection.go) [Java](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/floyds_cycle_detection.java) - Find middle of Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_compute_midpoint.cpp) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/linked_list_find_middle.py) - Happy Number [Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Fast%20and%20Slow%20Pointers/happy_number.go) - Pallindrome Linked List [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Linked%20List/linked_list_pallindrome.cpp) From 8481099852593f48c658122f6c664cfe06dc9ffa Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Thu, 15 Jun 2023 20:33:04 +0530 Subject: [PATCH 1377/1894] Create Kruskal's_Algorithm.java --- Graphs/Kruskal's_Algorithm.java | 155 ++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 Graphs/Kruskal's_Algorithm.java diff --git a/Graphs/Kruskal's_Algorithm.java b/Graphs/Kruskal's_Algorithm.java new file mode 100644 index 00000000..9913a8fd --- /dev/null +++ b/Graphs/Kruskal's_Algorithm.java @@ -0,0 +1,155 @@ +/* +What is a minimum spanning tree? +A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. + +What is Kruskal’s algorithm? +In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on adding new edges and nodes in the MST if the newly added edge does not form a cycle. It picks the minimum weighted edge at first at the maximum weighted edge at last. Thus we can say that it makes a locally optimal choice in each step in order to find the optimal solution. + +Time Complexity: O(E * logE) or O(E * logV) +Auxiliary Space: O(V + E), where V is the number of vertices and E is the number of edges in the graph. +*/ + +// Java program for Kruskal's algorithm + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class KruskalsMST { + + // Defines edge structure + static class Edge { + int src, dest, weight; + + public Edge(int src, int dest, int weight) + { + this.src = src; + this.dest = dest; + this.weight = weight; + } + } + + // Defines subset element structure + static class Subset { + int parent, rank; + + public Subset(int parent, int rank) + { + this.parent = parent; + this.rank = rank; + } + } + + // Starting point of program execution + public static void main(String[] args) + { + int V = 4; + List graphEdges = new ArrayList( + List.of(new Edge(0, 1, 10), new Edge(0, 2, 6), + new Edge(0, 3, 5), new Edge(1, 3, 15), + new Edge(2, 3, 4))); + + // Sort the edges in non-decreasing order + // (increasing with repetition allowed) + graphEdges.sort(new Comparator() { + @Override public int compare(Edge o1, Edge o2) + { + return o1.weight - o2.weight; + } + }); + + kruskals(V, graphEdges); + } + + // Function to find the MST + private static void kruskals(int V, List edges) + { + int j = 0; + int noOfEdges = 0; + + // Allocate memory for creating V subsets + Subset subsets[] = new Subset[V]; + + // Allocate memory for results + Edge results[] = new Edge[V]; + + // Create V subsets with single elements + for (int i = 0; i < V; i++) { + subsets[i] = new Subset(i, 0); + } + + // Number of edges to be taken is equal to V-1 + while (noOfEdges < V - 1) { + + // Pick the smallest edge. And increment + // the index for next iteration + Edge nextEdge = edges.get(j); + int x = findRoot(subsets, nextEdge.src); + int y = findRoot(subsets, nextEdge.dest); + + // If including this edge doesn't cause cycle, + // include it in result and increment the index + // of result for next edge + if (x != y) { + results[noOfEdges] = nextEdge; + union(subsets, x, y); + noOfEdges++; + } + + j++; + } + + // Print the contents of result[] to display the + // built MST + System.out.println( + "Following are the edges of the constructed MST:"); + int minCost = 0; + for (int i = 0; i < noOfEdges; i++) { + System.out.println(results[i].src + " -- " + + results[i].dest + " == " + + results[i].weight); + minCost += results[i].weight; + } + System.out.println("Total cost of MST: " + minCost); + } + + // Function to unite two disjoint sets + private static void union(Subset[] subsets, int x, + int y) + { + int rootX = findRoot(subsets, x); + int rootY = findRoot(subsets, y); + + if (subsets[rootY].rank < subsets[rootX].rank) { + subsets[rootY].parent = rootX; + } + else if (subsets[rootX].rank + < subsets[rootY].rank) { + subsets[rootX].parent = rootY; + } + else { + subsets[rootY].parent = rootX; + subsets[rootX].rank++; + } + } + + // Function to find parent of a set + private static int findRoot(Subset[] subsets, int i) + { + if (subsets[i].parent == i) + return subsets[i].parent; + + subsets[i].parent + = findRoot(subsets, subsets[i].parent); + return subsets[i].parent; + } +} + +/* Output +Following are the edges in the constructed MST +2 -- 3 == 4 +0 -- 3 == 5 +0 -- 1 == 10 +Minimum Cost Spanning Tree: 19 +*/ + From 529719787d663923411902a95caad14a8513adce Mon Sep 17 00:00:00 2001 From: Munyao Kelvin Date: Fri, 16 Jun 2023 04:36:06 +0300 Subject: [PATCH 1378/1894] create a Go script that finds the maximum path sum in binary tree --- Dynamic Programming/max_path_sum.go | 54 +++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Dynamic Programming/max_path_sum.go diff --git a/Dynamic Programming/max_path_sum.go b/Dynamic Programming/max_path_sum.go new file mode 100644 index 00000000..0474a05f --- /dev/null +++ b/Dynamic Programming/max_path_sum.go @@ -0,0 +1,54 @@ +// Dynamic Programming: Find Binary Tree Maximum Path Sum in Go +package main + +import ( + "fmt" + "math" +) + +type treenode struct { + Val int + Left *treenode + Right *treenode +} + +// Function to find the maximum path sum in a binary tree +func pathMaxSum(root *treenode) int{ + maxSum := math.MinInt32 + findMaxSum(root, &maxSum) + return maxSum +} + +// finding the maximum path sum starting from a given node +func findMaxSum(node *treenode, maxSum *int) int { + if node == nil { + return 0 + } + + leftSum := max(0, findMaxSum(node.Left,maxSum)) + rightSum := max(0,findMaxSum(node.Right,maxSum)) + + *maxSum = max(*maxSum,node.Val+leftSum+rightSum) + + // returning the max sum plus the current node + return node.Val + max(leftSum,rightSum) +} + +// function to find the maximum of two numbers +func max(a,b int) int { + if a >b { + return a + } + return b +} + +func main() { + // creating sample binary tree + root := &treenode{Val: 1} + root.Left = &treenode{Val: 2} + root.Right = &treenode{Val: 3} + + // Calculate the maximum path sum + maxSum := pathMaxSum(root) + fmt.Println("Maximum Path Sum:", maxSum) +} \ No newline at end of file From 702a56f7e106644a20782eb2af27542b199f9a30 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Fri, 16 Jun 2023 18:52:58 +0530 Subject: [PATCH 1379/1894] Update Kruskal's_Algorithm.java --- Graphs/Kruskal's_Algorithm.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Graphs/Kruskal's_Algorithm.java b/Graphs/Kruskal's_Algorithm.java index 9913a8fd..397acfd5 100644 --- a/Graphs/Kruskal's_Algorithm.java +++ b/Graphs/Kruskal's_Algorithm.java @@ -5,6 +5,13 @@ A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, co What is Kruskal’s algorithm? In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on adding new edges and nodes in the MST if the newly added edge does not form a cycle. It picks the minimum weighted edge at first at the maximum weighted edge at last. Thus we can say that it makes a locally optimal choice in each step in order to find the optimal solution. +How Kruskal's algorithm works +It falls under a class of algorithms called greedy algorithms that find the local optimum in the hopes of finding a global optimum. We start from the edges with the lowest weight and keep adding edges until we reach our goal. +The steps for implementing Kruskal's algorithm are as follows: +1. Sort all the edges from low weight to high +2. Take the edge with the lowest weight and add it to the spanning tree. If adding the edge created a cycle, then reject this edge. +3. Keep adding edges until we reach all vertices. + Time Complexity: O(E * logE) or O(E * logV) Auxiliary Space: O(V + E), where V is the number of vertices and E is the number of edges in the graph. */ From 6649dc520d2e4de7ea8951fbb15f43aadb5a7520 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Fri, 16 Jun 2023 19:06:39 +0530 Subject: [PATCH 1380/1894] Create recursive and iterative in singly linkedlist.py >>mentioned time and space complexity >>added sample io --- ...ive and iterative in singly linkedlist.py | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 recursive and iterative in singly linkedlist.py diff --git a/recursive and iterative in singly linkedlist.py b/recursive and iterative in singly linkedlist.py new file mode 100644 index 00000000..61f0db6f --- /dev/null +++ b/recursive and iterative in singly linkedlist.py @@ -0,0 +1,116 @@ +''' +Issue#528 +Date:16/06/2023 +Input: +Linked List: Reverse Linked List Recursively and Iteratively in Python + +Example 1: +Enter the values for the linked list (space-separated): 1 2 3 4 5 +Choose the reversal method (iterative or recursive): iterative +5 4 3 2 1 + +Explanation: +*The `create_linked_list()` function: + - This function prompts the user to enter values for the linked list, which are expected to be space-separated. + - The input values are split into a list of strings using the `split()` method. + - The function then iterates over the input values, creating a new `ListNode` object for each value. + - The `next` pointers of the nodes are appropriately set to form the linked list. + - Finally, the function returns the head of the linked list. + +* The `reverse_linked_list_iterative()` function: + - This function takes the head of a linked list as input. + - It initializes two pointers: `prev` and `current`. `prev` is initially set to `None`, and `current` is set to the head. + - The function iterates over the linked list using a while loop. + - In each iteration, it stores the next node in a variable called `next_node`. + - Then, it updates the `next` pointer of the current node to point to the previous node (`prev`). + - The `prev` pointer is updated to the current node, and the `current` pointer is updated to the next node (`next_node`). + - This process continues until `current` becomes `None`, which means the end of the original linked list has been reached. + - Finally, the function returns the new head of the reversed linked list, which is stored in `prev`. + +* The `reverse_linked_list_recursive()` function: + - This function is a recursive implementation of reversing a linked list. + - It takes the head of a linked list as input. + - First, it checks two base cases: if the head is `None` or the head's `next` pointer is `None`. In these cases, it simply returns the head as it is. + - If the base cases are not met, it recursively calls itself on the next node (`head.next`) to reverse the remaining sublist. + - Once the recursion reaches the last node in the original linked list, it starts updating the `next` pointers to reverse the sublist. + - The `next` pointer of the current node (`head`) is set to the previous node (`head.next.next`), effectively reversing the connection. + - The `next` pointer of the current node is then set to `None` to complete the reversal. + - Finally, the function returns the new head of the reversed linked list. + +Time Complexity: +O(n)(both recursive and iterative method) +Space Complexity: +Iterative approach: O(1) space complexity. +Recursive approach: O(n) space complexity. +''' +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +def create_linked_list(): + # Take user input for the linked list values + values = input("Enter the values for the linked list (space-separated): ").split() + + # Create the linked list from the input values + head = None + prev = None + + for val in values: + node = ListNode(int(val)) + + if not head: + head = node + else: + prev.next = node + + prev = node + + return head + +def reverse_linked_list_iterative(head): + prev = None + current = head + + while current: + next_node = current.next + current.next = prev + prev = current + current = next_node + + return prev + +def reverse_linked_list_recursive(head): + if not head or not head.next: + return head + + reversed_list = reverse_linked_list_recursive(head.next) + head.next.next = head + head.next = None + + return reversed_list + +def reverse_linked_list(head, method='iterative'): + if method == 'iterative': + return reverse_linked_list_iterative(head) + elif method == 'recursive': + return reverse_linked_list_recursive(head) + else: + raise ValueError('Invalid method specified.') + +# Create the linked list based on user input +head = create_linked_list() + +# Ask the user to choose the reversal method +method = input("Choose the reversal method (iterative or recursive): ") + +# Reverse the linked list using the chosen method +reversed_list = reverse_linked_list(head, method=method) + +# Traverse the reversed linked list and print the values +current = reversed_list +while current: + print(current.val, end=' ') + current = current.next + + From 54d850783a042d95cdab7a6e462275fc42f5dcf3 Mon Sep 17 00:00:00 2001 From: gargvarunjec Date: Fri, 16 Jun 2023 19:31:46 +0530 Subject: [PATCH 1381/1894] minimum_insertions_steps_to_make_string_pallindrom is added by varun --- ...rtion_steps_to_make_string_pallindrome.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp diff --git a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp new file mode 100644 index 00000000..e8587822 --- /dev/null +++ b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp @@ -0,0 +1,45 @@ +/* + Program author: Varun Garg +*/ + +#include +using namespace std; + +int lcs(string s1,string s2){ + int n=s1.size(),m=s2.size(); + vector> dp(n+1,vector(m+1,-1)); + + for(int i=0;i<=n;i++){ + dp[i][0]=0; + } + + for(int i=0;i<=m;i++){ + dp[0][i]=0; + } + + for(int i=1;i<=n;i++){ + for(int j=1;j<=m;j++){ + if(s1[i-1]==s2[j-1]){ + dp[i][j]=1+dp[i-1][j-1]; + } + else{ + dp[i][j]=0+max(dp[i-1][j],dp[i][j-1]); + } + } + } + + return dp[n][m]; +} + +int main(){ + string s; + cin>>s; + string reverse_s; + for(int i=s.size()-1;i>=0;i--){ + reverse_s.push_back(s[i]); + } + + int ans=lcs(s,reverse_s); + ans=s.size()-ans; + cout< Date: Fri, 16 Jun 2023 19:38:58 +0530 Subject: [PATCH 1382/1894] Create longest palindromic substring.java >>added time and space complexity >>added sample io --- longest palindromic substring.java | 77 ++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 longest palindromic substring.java diff --git a/longest palindromic substring.java b/longest palindromic substring.java new file mode 100644 index 00000000..72ed0e5c --- /dev/null +++ b/longest palindromic substring.java @@ -0,0 +1,77 @@ +/* +Issue#415 +//Input: +Given a string s, return the longest palindromic substring in s. + +//Palindrome:A palindrome is a word, phrase, or sequence that reads the same forward and backward, like "level" or "A man, a plan, a canal, Panama." + +//Example 1: +Input: s = "babad" +Output: "bab" +Explanation: "aba" is also a valid answer. +//Example 2: +Input: s = "cbbd" +Output: "bb" + +//Time complexity: +>>Time Complexity: O(n2) +as there is two recursion calls which are applied as two pointers so here Complexity would be O(n2). +>>Space Complexity: O(n) which is nothing but the storage consumed in this process. + +//Explanation: +>>The function first converts the input string into a character array. +>>If the length of the string is less than 2, it means the string itself is a palindrome, so it returns the string as is. +>>The function then iterates through each character of the string. +>>For each character, it expands outwards from that character and checks if it forms a palindrome. +>>It does this by calling the expandPalindrome function twice: once for odd-length palindromes with the current character as the center, +and once for even-length palindromes with the current character and the next character as centers. +>>The expandPalindrome function checks if the characters at positions j and k are equal, and if so, it expands the palindrome by decrementing j and incrementing k. +>>It continues this process until the characters at positions j and k are no longer equal or reach the boundaries of the string. +>>If a longer palindrome is found, the maxLen and lo variables are updated accordingly. +maxLen stores the length of the longest palindrome found so far, and lo stores the starting position of the longest palindrome. +>>Finally, the function returns the substring of the original string from the starting position lo to lo + maxLen, which represents the longest palindrome found. + +*/ + +class Solution +{ + int maxLen = 0; + int lo = 0; + + public String longestPalindrome(String s) + { + char[] input = s.toCharArray(); + if (s.length() < 2) { + return s; + } + + for (int i = 0; i < input.length; i++) + { + expandPalindrome(input, i, i); + expandPalindrome(input, i, i + 1); + } + return s.substring(lo, lo + maxLen); + } + + public void expandPalindrome(char[] s, int j, int k) { + while (j >= 0 && k < s.length && s[j] == s[k]) { + j--; + k++; + } + if (maxLen < k - j - 1) { + maxLen = k - j - 1; + lo = j + 1; + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + String input = "babad"; + String longestPalindrome = solution.longestPalindrome(input); + System.out.println("Longest Palindrome: " + longestPalindrome); + } +} + + + + From 8a2f60f1350b84d371c522b432a1e3d38b09cc3d Mon Sep 17 00:00:00 2001 From: gargvarunjec Date: Fri, 16 Jun 2023 19:47:46 +0530 Subject: [PATCH 1383/1894] added explanation to the code --- ...imum_insertion_steps_to_make_string_pallindrome.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp index e8587822..e0eab5f7 100644 --- a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp +++ b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp @@ -9,6 +9,8 @@ int lcs(string s1,string s2){ int n=s1.size(),m=s2.size(); vector> dp(n+1,vector(m+1,-1)); + // bottom up approach to calculate lcs + // base conditions for(int i=0;i<=n;i++){ dp[i][0]=0; } @@ -17,10 +19,11 @@ int lcs(string s1,string s2){ dp[0][i]=0; } + // filling the table to calculate the longest common subsequence for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ - if(s1[i-1]==s2[j-1]){ - dp[i][j]=1+dp[i-1][j-1]; + if(s1[i-1]==s2[j-1]){ // checking if the characters at both the string are same + dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=0+max(dp[i-1][j],dp[i][j-1]); @@ -38,7 +41,8 @@ int main(){ for(int i=s.size()-1;i>=0;i--){ reverse_s.push_back(s[i]); } - + // the minimum steps to make a string pallindrome will require to calculate the + // longest common subsequence in the given string and the reverse of the string int ans=lcs(s,reverse_s); ans=s.size()-ans; cout< Date: Fri, 16 Jun 2023 20:15:43 +0530 Subject: [PATCH 1384/1894] find optimal partition of string c++ --- Hash Table/find_optimal_partion_of_string.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Hash Table/find_optimal_partion_of_string.cpp diff --git a/Hash Table/find_optimal_partion_of_string.cpp b/Hash Table/find_optimal_partion_of_string.cpp new file mode 100644 index 00000000..65528f77 --- /dev/null +++ b/Hash Table/find_optimal_partion_of_string.cpp @@ -0,0 +1,28 @@ +/* OPTIMAL PARTITION OF STRING */ +/* PROGRAM AUTHOR : VARUN GARG */ +#include +using namespace std; + +int main(){ + string s; + cin>>s; + + int cnt=0; + int n=s.size(); + for(int i=0;i sub; + // taking the unique substrings in a set + while(i Date: Fri, 16 Jun 2023 20:22:55 +0530 Subject: [PATCH 1385/1894] added sample input and output --- Hash Table/find_optimal_partion_of_string.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Hash Table/find_optimal_partion_of_string.cpp b/Hash Table/find_optimal_partion_of_string.cpp index 65528f77..76857fef 100644 --- a/Hash Table/find_optimal_partion_of_string.cpp +++ b/Hash Table/find_optimal_partion_of_string.cpp @@ -1,5 +1,15 @@ /* OPTIMAL PARTITION OF STRING */ /* PROGRAM AUTHOR : VARUN GARG */ + +/* + sample input : abacaba + sample output : a b + a c + a b + a + The minimum number of substrings required for partition + 4 +*/ #include using namespace std; @@ -20,7 +30,7 @@ int main(){ cout< Date: Fri, 16 Jun 2023 20:26:48 +0530 Subject: [PATCH 1386/1894] added sample input and output --- ...rtion_steps_to_make_string_pallindrome.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp index e0eab5f7..7bbbb49d 100644 --- a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp +++ b/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp @@ -1,5 +1,22 @@ /* - Program author: Varun Garg + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) */ #include From f6b856da97831a2a88b8a79a734a246d0f597420 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Fri, 16 Jun 2023 22:33:39 +0530 Subject: [PATCH 1387/1894] Create Snakes_and_Ladders.java --- Graphs/Snakes_and_Ladders.java | 92 ++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Graphs/Snakes_and_Ladders.java diff --git a/Graphs/Snakes_and_Ladders.java b/Graphs/Snakes_and_Ladders.java new file mode 100644 index 00000000..6d7521c6 --- /dev/null +++ b/Graphs/Snakes_and_Ladders.java @@ -0,0 +1,92 @@ +Here's the Java implementation of the solution along with an explanation: + +import java.util.ArrayDeque; +import java.util.HashSet; +import java.util.Queue; +import java.util.Set; + +public class SnakesAndLadders { + + private static class Position { + int square; + int moves; + + public Position(int square, int moves) { + this.square = square; + this.moves = moves; + } + } + + private static int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + private static int[][] getBoardPosition(int square, int n) { + int row = n - 1 - (square - 1) / n; + int col = (row % 2 == n % 2) ? (square - 1) % n : n - 1 - (square - 1) % n; + return new int[]{row, col}; + } + + public static int snakesAndLadders(int[][] board) { + int n = board.length; + int destination = n * n; + + Queue queue = new ArrayDeque<>(); + Set visited = new HashSet<>(); + + queue.add(new Position(1, 0)); // Start position + visited.add(1); // Mark the start position as visited + + while (!queue.isEmpty()) { + Position position = queue.poll(); + int square = position.square; + int moves = position.moves; + + if (square == destination) { + return moves; + } + + for (int roll = 1; roll <= 6; roll++) { + int nextSquare = square + roll; + + if (nextSquare > destination) { + break; + } + + int[] pos = getBoardPosition(nextSquare, n); + int row = pos[0]; + int col = pos[1]; + + if (!visited.contains(nextSquare)) { + visited.add(nextSquare); + + if (board[row][col] != -1) { + queue.add(new Position(board[row][col], moves + 1)); + } else { + queue.add(new Position(nextSquare, moves + 1)); + } + } + } + } + + return -1; + } + + public static void main(String[] args) { + int[][] board = { + {-1, 4}, + {-1, 3} + }; + + System.out.println(snakesAndLadders(board)); // Output: 1 + } +} + +Explanation: + +The Position class is used to store the square number and the number of moves taken to reach that square. +The getBoardPosition function is used to convert a square number to its corresponding (row, column) position on the board. +The snakesAndLadders function implements the breadth-first search (BFS) algorithm to find the shortest path from square 1 to square n^2. +The function uses a queue (ArrayDeque) to store the positions to be explored during BFS and a set (HashSet) to keep track of visited positions. +The function starts by enqueuing the starting position (1, 0) into the queue and marking it as visited. +While the queue is not empty, it dequeues a position and checks if it is the destination square. If it is, the number of moves is returned. +Otherwise, the function generates the next possible destinations based on the roll of a 6-sided die and checks if they are valid and not visited. +If a destination has a snake or ladder, its destination is enqueued From 3f3450bdc6320a7c6aa499ae74ea9f7e2a260eda Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 16 Jun 2023 23:08:53 +0530 Subject: [PATCH 1388/1894] move to appropriate folder --- .../search in 2d sorted array.java | 0 .../recursive and iterative in singly linkedlist.py | 0 queue using stack.java => Stacks/queue using stack.java | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename search in 2d sorted array.java => 2D Arrays (Matrix)/search in 2d sorted array.java (100%) rename recursive and iterative in singly linkedlist.py => Linked List/recursive and iterative in singly linkedlist.py (100%) rename queue using stack.java => Stacks/queue using stack.java (100%) diff --git a/search in 2d sorted array.java b/2D Arrays (Matrix)/search in 2d sorted array.java similarity index 100% rename from search in 2d sorted array.java rename to 2D Arrays (Matrix)/search in 2d sorted array.java diff --git a/recursive and iterative in singly linkedlist.py b/Linked List/recursive and iterative in singly linkedlist.py similarity index 100% rename from recursive and iterative in singly linkedlist.py rename to Linked List/recursive and iterative in singly linkedlist.py diff --git a/queue using stack.java b/Stacks/queue using stack.java similarity index 100% rename from queue using stack.java rename to Stacks/queue using stack.java From 8269319f21983848214ce1617944341ff3a05760 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 16 Jun 2023 23:10:39 +0530 Subject: [PATCH 1389/1894] remove duplicate --- distance_of_nearest_0.py | 79 ---------------------------------------- 1 file changed, 79 deletions(-) delete mode 100644 distance_of_nearest_0.py diff --git a/distance_of_nearest_0.py b/distance_of_nearest_0.py deleted file mode 100644 index edc5ac00..00000000 --- a/distance_of_nearest_0.py +++ /dev/null @@ -1,79 +0,0 @@ -'''Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. - -The distance between two adjacent cells is 1. - - - -Example 1: - - -Input: mat = [[0,0,0],[0,1,0],[0,0,0]] -Output: [[0,0,0],[0,1,0],[0,0,0]] -Example 2: - - -Input: mat = [[0,0,0],[0,1,0],[1,1,1]] -Output: [[0,0,0],[0,1,0],[1,2,1]] - - -Constraints: - -m == mat.length -n == mat[i].length -1 <= m, n <= 104 -1 <= m * n <= 104 -mat[i][j] is either 0 or 1. -There is at least one 0 in mat. - -Explanation: - -In this Python implementation, we define a TreeNode class to represent each node in the binary tree. The constructBST function takes the pre-order traversal array as input and returns the root node of the constructed BST. - -We create the root node using the first element of the pre-order array and also initialize a stack with the root node. Then, for each element in the pre-order array (starting from the second element), we create a new node. We compare the value of the new node with the top of the stack to determine its position in the BST. - -If the value is less than the top of the stack, we add it as the left child of the top node. Otherwise, we pop nodes from the stack until we find a node with a value greater than the new node. The last popped node becomes the parent of the new node and we add the new node as its right child. - -Finally, we return the root node of the constructed BST. The inorderTraversal function is used to verify the correctness of the construction by performing an in-order traversal of the BST and printing the values. - -When executed, this code will output the in-order traversal of the constructed BST, which should match the expected output you provided. - -''' - -class TreeNode: - def __init__(self, val): - self.val = val - self.left = None - self.right = None - -def constructBST(preorder): - if not preorder: - return None - - root = TreeNode(preorder[0]) - stack = [root] - - for val in preorder[1:]: - node = TreeNode(val) - - if val < stack[-1].val: - stack[-1].left = node - else: - while stack and val > stack[-1].val: - last = stack.pop() - last.right = node - - stack.append(node) - - return root - -def inorderTraversal(root): - if root: - inorderTraversal(root.left) - print(root.val, end=' ') - inorderTraversal(root.right) - -preorder = [10, 4, 2, 1, 5, 17, 19, 18] -root = constructBST(preorder) - -# Verify the constructed BST by performing an in-order traversal -inorderTraversal(root) \ No newline at end of file From 97509d62fa55461ebbec4467c6c6b2c68acaf8f3 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sat, 17 Jun 2023 00:01:16 +0530 Subject: [PATCH 1390/1894] Update Snakes_and_Ladders.java Comments added --- Graphs/Snakes_and_Ladders.java | 183 +++++++++++++++++++-------------- 1 file changed, 103 insertions(+), 80 deletions(-) diff --git a/Graphs/Snakes_and_Ladders.java b/Graphs/Snakes_and_Ladders.java index 6d7521c6..e31d48d4 100644 --- a/Graphs/Snakes_and_Ladders.java +++ b/Graphs/Snakes_and_Ladders.java @@ -1,92 +1,115 @@ -Here's the Java implementation of the solution along with an explanation: +Explanation: + +We start by importing the necessary classes and defining the class SnakesAndLadders. + +We declare the constant BOARD_SIZE to represent the number of cells on the board. + +We declare two maps: snakes to store the snake positions, and ladders to store the ladder positions. + +The SnakesAndLadders class has a constructor that initializes the snakes and ladders maps. + +The addSnake method is used to add a snake to the game by providing the start and end positions. + +The addLadder method is used to add a ladder to the game by providing the start and end positions. + +The playGame method simulates the game. It starts with the player's position at 0 and the number of dice rolls at 0. + +Inside the while loop, a dice is rolled using the rollDice method, and the player's position is updated. -import java.util.ArrayDeque; -import java.util.HashSet; -import java.util.Queue; -import java.util.Set; +After each move, we check if the player has landed on a ladder or a snake. If so, we update the player's position accordingly. + +The rollDice method generates a random number between 1 and 6, simulating a dice roll. + +In the main method, we create an instance of SnakesAndLadders and add snakes and ladders to the game. + +Finally, we call the playGame method to start the game and print the number of dice rolls required to reach or exceed the BOARD_SIZE. + +Below is an implementation of the Snakes and Ladders game in Java, along with comments: + +import java.util.HashMap; +import java.util.Map; public class SnakesAndLadders { - - private static class Position { - int square; - int moves; - - public Position(int square, int moves) { - this.square = square; - this.moves = moves; - } + private static final int BOARD_SIZE = 100; // Number of cells in the board + private Map snakes; // Map to store snake positions + private Map ladders; // Map to store ladder positions + + public SnakesAndLadders() { + // Initialize the snake and ladder positions + snakes = new HashMap<>(); + ladders = new HashMap<>(); } - - private static int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - - private static int[][] getBoardPosition(int square, int n) { - int row = n - 1 - (square - 1) / n; - int col = (row % 2 == n % 2) ? (square - 1) % n : n - 1 - (square - 1) % n; - return new int[]{row, col}; + + public void addSnake(int start, int end) { + snakes.put(start, end); } - - public static int snakesAndLadders(int[][] board) { - int n = board.length; - int destination = n * n; - - Queue queue = new ArrayDeque<>(); - Set visited = new HashSet<>(); - - queue.add(new Position(1, 0)); // Start position - visited.add(1); // Mark the start position as visited - - while (!queue.isEmpty()) { - Position position = queue.poll(); - int square = position.square; - int moves = position.moves; - - if (square == destination) { - return moves; + + public void addLadder(int start, int end) { + ladders.put(start, end); + } + + public int playGame() { + int currentPlayerPosition = 0; // Player's current position + int diceRolls = 0; // Number of dice rolls + + while (currentPlayerPosition < BOARD_SIZE) { + // Roll a dice + int dice = rollDice(); + + // Move the player + currentPlayerPosition += dice; + + // Check if the player has landed on a ladder + if (ladders.containsKey(currentPlayerPosition)) { + // Climb the ladder + currentPlayerPosition = ladders.get(currentPlayerPosition); } - - for (int roll = 1; roll <= 6; roll++) { - int nextSquare = square + roll; - - if (nextSquare > destination) { - break; - } - - int[] pos = getBoardPosition(nextSquare, n); - int row = pos[0]; - int col = pos[1]; - - if (!visited.contains(nextSquare)) { - visited.add(nextSquare); - - if (board[row][col] != -1) { - queue.add(new Position(board[row][col], moves + 1)); - } else { - queue.add(new Position(nextSquare, moves + 1)); - } - } + + // Check if the player has landed on a snake + if (snakes.containsKey(currentPlayerPosition)) { + // Go down the snake + currentPlayerPosition = snakes.get(currentPlayerPosition); } + + diceRolls++; // Increment the number of dice rolls } - - return -1; + + return diceRolls; } - - public static void main(String[] args) { - int[][] board = { - {-1, 4}, - {-1, 3} - }; - - System.out.println(snakesAndLadders(board)); // Output: 1 + + private int rollDice() { + // Generates a random number between 1 and 6 (inclusive) + return (int) (Math.random() * 6) + 1; } -} -Explanation: + public static void main(String[] args) { + SnakesAndLadders game = new SnakesAndLadders(); -The Position class is used to store the square number and the number of moves taken to reach that square. -The getBoardPosition function is used to convert a square number to its corresponding (row, column) position on the board. -The snakesAndLadders function implements the breadth-first search (BFS) algorithm to find the shortest path from square 1 to square n^2. -The function uses a queue (ArrayDeque) to store the positions to be explored during BFS and a set (HashSet) to keep track of visited positions. -The function starts by enqueuing the starting position (1, 0) into the queue and marking it as visited. -While the queue is not empty, it dequeues a position and checks if it is the destination square. If it is, the number of moves is returned. -Otherwise, the function generates the next possible destinations based on the roll of a 6-sided die and checks if they are valid and not visited. -If a destination has a snake or ladder, its destination is enqueued + // Add snakes to the game + game.addSnake(16, 6); + game.addSnake(47, 26); + game.addSnake(49, 11); + game.addSnake(56, 53); + game.addSnake(62, 19); + game.addSnake(64, 60); + game.addSnake(87, 24); + game.addSnake(93, 73); + game.addSnake(95, 75); + game.addSnake(98, 78); + + // Add ladders to the game + game.addLadder(1, 38); + game.addLadder(4, 14); + game.addLadder(9, 31); + game.addLadder(21, 42); + game.addLadder(28, 84); + game.addLadder(36, 44); + game.addLadder(51, 67); + game.addLadder(71, 91); + game.addLadder(80, 100); + + // Play the game + int diceRolls = game.playGame(); + System.out.println("Number of dice rolls: " + diceRolls); + } +} From 033cb2022b16af281f07cd12fa54795354cd99ea Mon Sep 17 00:00:00 2001 From: gargvarunjec Date: Sat, 17 Jun 2023 15:30:04 +0530 Subject: [PATCH 1391/1894] added explanation --- Hash Table/find_optimal_partion_of_string.cpp | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Hash Table/find_optimal_partion_of_string.cpp b/Hash Table/find_optimal_partion_of_string.cpp index 76857fef..d59ef89d 100644 --- a/Hash Table/find_optimal_partion_of_string.cpp +++ b/Hash Table/find_optimal_partion_of_string.cpp @@ -2,6 +2,17 @@ /* PROGRAM AUTHOR : VARUN GARG */ /* + + Our task is to partition the string into one or more substrings such that the characters in each substring are unique. + + Approach: + Intuitively, we can consider adding characters to a substring as long as we don't see a character + that has already been added to the current substring. When we see a character that is already + present in the substring, we start a new substring and repeat this process until we iterate over the entire string s. + we are declaring a set in which if the character is not present in the set then the character will be inserted in it + else it will break from the loop then the count of the strings will be increased . + + sample input : abacaba sample output : a b a c @@ -9,19 +20,23 @@ a The minimum number of substrings required for partition 4 + + Time Complexity: O(n) + Space Complexity: O(n) */ #include using namespace std; int main(){ string s; - cin>>s; + cin>>s; // taking input of the string int cnt=0; int n=s.size(); for(int i=0;i sub; - // taking the unique substrings in a set + // taking the unique substrings in a set by checking the character is present in the set or not while(i Date: Sat, 17 Jun 2023 17:21:50 +0530 Subject: [PATCH 1392/1894] Update longest palindromic substring.java >>added line comments --- longest palindromic substring.java | 32 +++++++++++++----------------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/longest palindromic substring.java b/longest palindromic substring.java index 72ed0e5c..82e0a1bc 100644 --- a/longest palindromic substring.java +++ b/longest palindromic substring.java @@ -32,35 +32,32 @@ as there is two recursion calls which are applied as two pointers so here Comple >>Finally, the function returns the substring of the original string from the starting position lo to lo + maxLen, which represents the longest palindrome found. */ +class Solution { + int maxLen = 0; // Length of the longest palindrome + int lo = 0; // Starting position of the longest palindrome -class Solution -{ - int maxLen = 0; - int lo = 0; + public String longestPalindrome(String s) { + char[] input = s.toCharArray(); // Convert the input word to individual characters - public String longestPalindrome(String s) - { - char[] input = s.toCharArray(); if (s.length() < 2) { - return s; + return s; // If word has less than 2 letters, it is already a palindrome } - for (int i = 0; i < input.length; i++) - { - expandPalindrome(input, i, i); - expandPalindrome(input, i, i + 1); + for (int i = 0; i < input.length; i++) { + expandPalindrome(input, i, i); // Check odd-length palindromes with current letter as center + expandPalindrome(input, i, i + 1); // Check even-length palindromes with current and next letters as center } - return s.substring(lo, lo + maxLen); + return s.substring(lo, lo + maxLen); // Return the longest palindrome found } public void expandPalindrome(char[] s, int j, int k) { while (j >= 0 && k < s.length && s[j] == s[k]) { - j--; - k++; + j--; // Move left to expand potential palindrome + k++; // Move right to expand potential palindrome } if (maxLen < k - j - 1) { - maxLen = k - j - 1; - lo = j + 1; + maxLen = k - j - 1; // Update length of longest palindrome if longer one is found + lo = j + 1; // Update starting position of longest palindrome } } @@ -74,4 +71,3 @@ public static void main(String[] args) { - From 51d301967e68f6ea874b4a7824561ea10c0b0790 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:00:50 +0530 Subject: [PATCH 1393/1894] add union find in go --- Graphs/union_find.go | 45 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Graphs/union_find.go diff --git a/Graphs/union_find.go b/Graphs/union_find.go new file mode 100644 index 00000000..7123b93c --- /dev/null +++ b/Graphs/union_find.go @@ -0,0 +1,45 @@ +package main + +type UnionFind struct { + parents map[int]int +} + +func NewUnionFind() *UnionFind { + return &UnionFind{ + parents: map[int]int{}, + } +} + +func (union *UnionFind) CreateSet(value int) { + union.parents[value] = value +} + +func (union *UnionFind) Find(value int) *int { + // Check if the value exists in the parents map + if _, found := union.parents[value]; !found { + return nil // Value not found, return nil + } + + currentParent := value + // Find the representative (parent) by following the parent links + for currentParent != union.parents[currentParent] { + currentParent = union.parents[currentParent] + } + + return ¤tParent +} + +func (union *UnionFind) Union(valueOne, valueTwo int) { + // Check if both values exist in the parents map + _, parentContainsOne := union.parents[valueOne] + _, parentContainsTwo := union.parents[valueTwo] + if !parentContainsOne || !parentContainsTwo { + return // One or both values are missing, return without union + } + + valueOneRoot := *union.Find(valueOne) + valueTwoRoot := *union.Find(valueTwo) + // Perform union by updating the parent of valueTwoRoot to valueOneRoot + union.parents[valueTwoRoot] = valueOneRoot +} + From 926fcb2dd4fe30fee3489e8046831be2bcaf7f0c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:01:05 +0530 Subject: [PATCH 1394/1894] add main func --- Graphs/union_find.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index 7123b93c..0f8244f8 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -1,5 +1,7 @@ package main +import "fmt" + type UnionFind struct { parents map[int]int } @@ -43,3 +45,26 @@ func (union *UnionFind) Union(valueOne, valueTwo int) { union.parents[valueTwoRoot] = valueOneRoot } +func main() { + // Create a new instance of UnionFind + union := NewUnionFind() + + // Create individual sets + union.CreateSet(1) + union.CreateSet(2) + union.CreateSet(3) + + // Perform union operations + union.Union(1, 2) + union.Union(2, 3) + + // Find representatives of values + representative := union.Find(3) + + // Check if the representative is found + if representative != nil { + fmt.Println("The representative of 3 is:", *representative) + } else { + fmt.Println("Value 3 is not found.") + } +} \ No newline at end of file From 45401526eaf0c3bb85866d110b02995e3e58aa7c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:02:44 +0530 Subject: [PATCH 1395/1894] add explanation --- Graphs/union_find.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index 0f8244f8..1853371c 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -1,3 +1,34 @@ +/* + Explanation: + The code snippet you provided implements the Union-Find data structure, which is used for efficient operations on disjoint + sets. Here's a detailed explanation of each part: + + + - The `UnionFind` struct represents the Union-Find data structure. It contains a map called `parents` that will store the + parent element for each set element. + + + - `NewUnionFind()` is a constructor function that creates a new instance of the Union-Find data structure and initializes + an empty `parents` map. + + + - `CreateSet(value int)` is a method of the `UnionFind` struct. It creates a new set with the given `value` as the + representative (parent) of the set. It adds an entry to the `parents` map, where the `value` maps to itself. + + + - `Find(value int)` is a method that finds and returns the representative (parent) of the set that contains the given + `value`. It starts from the given `value` and iteratively follows the parent links until it reaches the representative. + The method returns a pointer to the representative value. If the `value` is not present in the `parents` map, it returns `nil`. + + + - `Union(valueOne, valueTwo int)` is a method that performs the union of two sets that contain `valueOne` and `valueTwo`. + It first checks if both `valueOne` and `valueTwo` exist in the `parents` map. If either of them is missing, it returns + without performing the union operation. It then finds the representatives of both sets using the `Find()` method. + It updates the parent of `valueTwoRoot` to be `valueOneRoot`, effectively merging the two sets into one. + + Overall, this code provides a basic implementation of the Union-Find data structure, allowing the creation of sets, + finding the representative of a set, and performing unions between sets. +*/ package main import "fmt" From b750dbb279ae2e91485aec5c0cabbf74ee62badd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:08:39 +0530 Subject: [PATCH 1396/1894] add time and space complexity --- Graphs/union_find.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index 1853371c..ed271cff 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -28,6 +28,20 @@ Overall, this code provides a basic implementation of the Union-Find data structure, allowing the creation of sets, finding the representative of a set, and performing unions between sets. + + The time and space complexity of the operations in the `UnionFind` data structure are as follows: + + - `NewUnionFind`: This operation has a time complexity of O(1) as it simply initializes a new `UnionFind` instance. + The space complexity is also O(1) as it only requires memory to store the instance itself. + + - `CreateSet`: This operation has a time complexity of O(1) as it performs a constant number of operations to add + a value to the `parents` map. The space complexity is also O(1) as it only requires memory to store the mapping between values and their parents. + + - `Find`: has a time complexity of O(n) in the worst case, where n is the number of elements in the disjoint sets + + - `Union`: Union operation in the given implementation has a time complexity of O(n), where n is the number of elements in the data structure. + The space complexity is O(1) as it does not use any additional memory. + */ package main From 6e29a397c37e89fc5ab99ea7d19c031a46501bd1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:11:38 +0530 Subject: [PATCH 1397/1894] add question --- Graphs/union_find.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index ed271cff..e6329cdc 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -1,4 +1,21 @@ /* + Write a UnionFind class that implements the union-find (also called a disjoint set) data structure. + This class should support three methods: + + + The union-find data structure is similar to a traditional set data structure in that it contains a collection + of unique values. However, these values are spread out amongst a variety of distinct disjoint sets, meaning that no set + can have duplicate values, and no two sets can contain the same value. + + createSet(value) : : Adds a given value in a new set containing only that value. + + union(valueOne, valueTwo) : : Takes in two values and determines which sets they are in. If they are in different sets, the sets are combined + into a single set. If either value is not in a set or they are in the same set, the function should have no effect. + + find(value): : Returns the "representative" value of the set for which a value belongs to. This can be any value in the set, but it should + always be the same value, regardless of which value in the set find is passed. If the value is not in a set, the function + should return null / none + Explanation: The code snippet you provided implements the Union-Find data structure, which is used for efficient operations on disjoint sets. Here's a detailed explanation of each part: From 759f19d92e1994de9e23bbcdee2f4c3ba0bcacc5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:22:09 +0530 Subject: [PATCH 1398/1894] optimize solution --- Graphs/union_find.go | 103 +++++++++++++++++++++++-------------------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index e6329cdc..2ba4972d 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -17,96 +17,103 @@ should return null / none Explanation: - The code snippet you provided implements the Union-Find data structure, which is used for efficient operations on disjoint - sets. Here's a detailed explanation of each part: + The provided code snippet is an optimized version of the Union-Find data structure. Here's a detailed explanation: + - `UnionFind` struct: It contains two fields, `parents` and `ranks`. The `parents` map stores the parent of + each element, and the `ranks` map stores the rank of each element. The rank is used to optimize the Union operation. - - The `UnionFind` struct represents the Union-Find data structure. It contains a map called `parents` that will store the - parent element for each set element. + - `NewUnionFind` function: It initializes a new instance of the UnionFind struct by creating empty maps for + `parents` and `ranks`. + - `CreateSet` method: It creates a new set with the given value. It sets the parent of the value to itself and + initializes its rank to 0. - - `NewUnionFind()` is a constructor function that creates a new instance of the Union-Find data structure and initializes - an empty `parents` map. + - `Find` method: It finds the root/representative of the set to which the given value belongs. It starts from the + given value and traverses the parent pointers until it reaches the root. It uses path compression optimization to + update the parent pointers along the path to the root. Finally, it returns a pointer to the root. + `Union` method: It performs the union of two sets represented by the given values. It first checks if both values exist + in the data structure. If either value is missing, it returns without performing any union operation. Otherwise, it finds + the roots of the two sets using the `Find` method. It compares the ranks of the two roots and performs the union accordingly: - - `CreateSet(value int)` is a method of the `UnionFind` struct. It creates a new set with the given `value` as the - representative (parent) of the set. It adds an entry to the `parents` map, where the `value` maps to itself. + If the rank of the root of `valueOne` is less than the rank of the root of `valueTwo`, it sets the parent of `valueOne`'s + root to `valueTwo`'s root. + If the rank of the root of `valueOne` is greater than the rank of the root of `valueTwo`, it sets the parent of `valueTwo`'s + root to `valueOne`'s root. - - `Find(value int)` is a method that finds and returns the representative (parent) of the set that contains the given - `value`. It starts from the given `value` and iteratively follows the parent links until it reaches the representative. - The method returns a pointer to the representative value. If the `value` is not present in the `parents` map, it returns `nil`. + If the ranks are equal, it chooses one root as the parent and increments its rank by 1. - - - `Union(valueOne, valueTwo int)` is a method that performs the union of two sets that contain `valueOne` and `valueTwo`. - It first checks if both `valueOne` and `valueTwo` exist in the `parents` map. If either of them is missing, it returns - without performing the union operation. It then finds the representatives of both sets using the `Find()` method. - It updates the parent of `valueTwoRoot` to be `valueOneRoot`, effectively merging the two sets into one. - - Overall, this code provides a basic implementation of the Union-Find data structure, allowing the creation of sets, - finding the representative of a set, and performing unions between sets. + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. The time and space complexity of the operations in the `UnionFind` data structure are as follows: - - `NewUnionFind`: This operation has a time complexity of O(1) as it simply initializes a new `UnionFind` instance. - The space complexity is also O(1) as it only requires memory to store the instance itself. - - - `CreateSet`: This operation has a time complexity of O(1) as it performs a constant number of operations to add - a value to the `parents` map. The space complexity is also O(1) as it only requires memory to store the mapping between values and their parents. - - - `Find`: has a time complexity of O(n) in the worst case, where n is the number of elements in the disjoint sets - - - `Union`: Union operation in the given implementation has a time complexity of O(n), where n is the number of elements in the data structure. - The space complexity is O(1) as it does not use any additional memory. */ package main -import "fmt" - type UnionFind struct { - parents map[int]int + parents map[int]int // Map to store the parent of each element + ranks map[int]int // Map to store the rank of each element } +// NewUnionFind creates a new instance of the UnionFind struct. func NewUnionFind() *UnionFind { return &UnionFind{ parents: map[int]int{}, + ranks: map[int]int{}, } } +// CreateSet creates a new set with the given value. func (union *UnionFind) CreateSet(value int) { - union.parents[value] = value + union.parents[value] = value // Set the parent of the value to itself + union.ranks[value] = 0 // Initialize the rank of the value to 0 } +// Find finds the root/representative of the set to which the given value belongs. func (union *UnionFind) Find(value int) *int { - // Check if the value exists in the parents map if _, found := union.parents[value]; !found { - return nil // Value not found, return nil + return nil // Return nil if the value is not found (not part of any set) } - currentParent := value - // Find the representative (parent) by following the parent links for currentParent != union.parents[currentParent] { - currentParent = union.parents[currentParent] + currentParent = union.parents[currentParent] // Traverse the parent pointers until reaching the root } - return ¤tParent + // Perform path compression by updating parent pointers along the path to the root + // This optimization flattens the tree structure, reducing future lookup time + for value != currentParent { + nextParent := union.parents[value] + union.parents[value] = currentParent + value = nextParent + } + + return ¤tParent // Return a pointer to the root/representative } +// Union performs the union of two sets represented by the given values. func (union *UnionFind) Union(valueOne, valueTwo int) { - // Check if both values exist in the parents map - _, parentContainsOne := union.parents[valueOne] - _, parentContainsTwo := union.parents[valueTwo] - if !parentContainsOne || !parentContainsTwo { - return // One or both values are missing, return without union + _, parentFoundOne := union.parents[valueOne] + _, parentFoundTwo := union.parents[valueTwo] + if !parentFoundOne || !parentFoundTwo { + return // Return if either value is not found (not part of any set) } - valueOneRoot := *union.Find(valueOne) - valueTwoRoot := *union.Find(valueTwo) - // Perform union by updating the parent of valueTwoRoot to valueOneRoot - union.parents[valueTwoRoot] = valueOneRoot + valueOneRoot := *union.Find(valueOne) // Find the root of the set containing valueOne + valueTwoRoot := *union.Find(valueTwo) // Find the root of the set containing valueTwo + + if union.ranks[valueOneRoot] < union.ranks[valueTwoRoot] { + union.parents[valueOneRoot] = valueTwoRoot // Set the parent of valueOne's root to valueTwo's root + } else if union.ranks[valueOneRoot] > union.ranks[valueTwoRoot] { + union.parents[valueTwoRoot] = valueOneRoot // Set the parent of valueTwo's root to valueOne's root + } else { + union.parents[valueOneRoot] = valueTwoRoot // Set the parent of valueOne's root to valueTwo's root + union.ranks[valueTwoRoot] += 1 // Increment the rank of valueTwo's root + } } + func main() { // Create a new instance of UnionFind union := NewUnionFind() From fb424c3fdac488c901c8c8dc580ae6687130e3a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 17 Jun 2023 19:23:34 +0530 Subject: [PATCH 1399/1894] update time and space complexity --- Graphs/union_find.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Graphs/union_find.go b/Graphs/union_find.go index 2ba4972d..6b93374d 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -44,14 +44,21 @@ If the ranks are equal, it chooses one root as the parent and increments its rank by 1. - By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. The time and space complexity of the operations in the `UnionFind` data structure are as follows: + CreateSet : O(n) time O(1) space + Find : O(log(n)) time O(1) space where n is total number of values + Union : O(log(n)) time O(1) space where n is total number of values + + */ package main +import "fmt" + type UnionFind struct { parents map[int]int // Map to store the parent of each element ranks map[int]int // Map to store the rank of each element From dbfe626293ecf60ef93af941e07a8b70a00706cd Mon Sep 17 00:00:00 2001 From: Shruti Swarupa Dhar <125943681+Shr-reny@users.noreply.github.com> Date: Sat, 17 Jun 2023 21:02:51 +0530 Subject: [PATCH 1400/1894] Create Ford_Fulkerson.cpp --- Graphs/Ford_Fulkerson.cpp | 140 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 Graphs/Ford_Fulkerson.cpp diff --git a/Graphs/Ford_Fulkerson.cpp b/Graphs/Ford_Fulkerson.cpp new file mode 100644 index 00000000..ca19799a --- /dev/null +++ b/Graphs/Ford_Fulkerson.cpp @@ -0,0 +1,140 @@ +/*Name : Shruti Swarupa Dhar +Github username : Shr-reny +Repository name : data-structures-and-algorithms +Problem : Implement Ford Fulkerson algorithm in C++ +Issue Number : #1386 +Problem statement : + +Given a graph which represents a flow network where every edge has a capacity. Also, given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with the following constraints: +Flow on an edge doesn’t exceed the given capacity of the edge. +Incoming flow is equal to outgoing flow for every vertex except s and t. + +Explanation of the below C++ code : + +The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. +The algorithm works by iteratively finding an augmenting path, which is a path from the source to the sink in the residual graph, i.e., the graph obtained by subtracting the current flow from the capacity of each edge. The algorithm then increases the flow along this path by the maximum possible amount, which is the minimum capacity of the edges along the path. + +*/ + +-------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ + + +// C++ program for implementation of Ford Fulkerson +// algorithm +#include +#include +#include +#include +using namespace std; + +// Number of vertices in given graph +#define V 6 + +/* Returns true if there is a path from source 's' to sink +'t' in residual graph. Also fills parent[] to store the +path */ +bool bfs(int rGraph[V][V], int s, int t, int parent[]) +{ + // Create a visited array and mark all vertices as not + // visited + bool visited[V]; + memset(visited, 0, sizeof(visited)); + + // Create a queue, enqueue source vertex and mark source + // vertex as visited + queue q; + q.push(s); + visited[s] = true; + parent[s] = -1; + + // Standard BFS Loop + while (!q.empty()) { + int u = q.front(); + q.pop(); + + for (int v = 0; v < V; v++) { + if (visited[v] == false && rGraph[u][v] > 0) { + // If we find a connection to the sink node, + // then there is no point in BFS anymore We + // just have to set its parent and can return + // true + if (v == t) { + parent[v] = u; + return true; + } + q.push(v); + parent[v] = u; + visited[v] = true; + } + } + } + + // We didn't reach sink in BFS starting from source, so + // return false + return false; +} + +// Returns the maximum flow from s to t in the given graph +int fordFulkerson(int graph[V][V], int s, int t) +{ + int u, v; + + // Create a residual graph and fill the residual graph + // with given capacities in the original graph as + // residual capacities in residual graph + int rGraph[V] + [V]; // Residual graph where rGraph[i][j] + // indicates residual capacity of edge + // from i to j (if there is an edge. If + // rGraph[i][j] is 0, then there is not) + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; + + int parent[V]; // This array is filled by BFS and to + // store path + + int max_flow = 0; // There is no flow initially + + // Augment the flow while there is path from source to + // sink + while (bfs(rGraph, s, t, parent)) { + // Find minimum residual capacity of the edges along + // the path filled by BFS. Or we can say find the + // maximum flow through the path found. + int path_flow = INT_MAX; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + path_flow = min(path_flow, rGraph[u][v]); + } + + // update residual capacities of the edges and + // reverse edges along the path + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= path_flow; + rGraph[v][u] += path_flow; + } + + // Add path flow to overall flow + max_flow += path_flow; + } + + // Return the overall flow + return max_flow; +} + +// Driver program to test above functions +int main() +{ + // Let us create a graph shown in the above example + int graph[V][V] + = { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, + { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, + { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; + + cout << "The maximum possible flow is " + << fordFulkerson(graph, 0, 5); + + return 0; +} From 6df1ae5d1abc4042fbdabc42d498ac22d0324c9d Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 18 Jun 2023 11:12:01 +0530 Subject: [PATCH 1401/1894] Create Graphs_Ford_Fulkerson.cpp --- Graphs/Graphs_Ford_Fulkerson.cpp | 123 +++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Graphs/Graphs_Ford_Fulkerson.cpp diff --git a/Graphs/Graphs_Ford_Fulkerson.cpp b/Graphs/Graphs_Ford_Fulkerson.cpp new file mode 100644 index 00000000..ec8a9dc0 --- /dev/null +++ b/Graphs/Graphs_Ford_Fulkerson.cpp @@ -0,0 +1,123 @@ +The Ford-Fulkerson algorithm is a graph algorithm used to find the maximum flow in a flow network. +Here is a high-level overview of the algorithm and some resources for further documentation: + +Ford-Fulkerson Algorithm Overview: + +Start with an initial flow of zero. +While there exists an augmenting path from the source to the sink: +Find the residual capacity of the augmenting path (minimum capacity edge along the path). +Update the flow by increasing the flow along the augmenting path. +Update the residual capacities of the edges. +The maximum flow is the sum of the flows along the augmenting paths. + +Here's an example of the Ford-Fulkerson algorithm implemented in C++: + +#include +#include +#include +#include +using namespace std; + +// Number of vertices in the graph +#define V 6 + +// A BFS based function to check whether there is an augmenting path +// from source to sink. Returns true if there is an augmenting path, +// else returns false +bool bfs(int rGraph[V][V], int s, int t, int parent[]) +{ + // Create a visited array and mark all vertices as not visited + bool visited[V]; + memset(visited, 0, sizeof(visited)); + + // Create a queue, enqueue source vertex and mark source vertex + // as visited + queue q; + q.push(s); + visited[s] = true; + parent[s] = -1; + + // Standard BFS Loop + while (!q.empty()) { + int u = q.front(); + q.pop(); + + for (int v = 0; v < V; v++) { + if (visited[v] == false && rGraph[u][v] > 0) { + q.push(v); + parent[v] = u; + visited[v] = true; + } + } + } + + // If we reached the sink in BFS starting from source, then return + // true, else false + return (visited[t] == true); +} + +// A function to implement the Ford-Fulkerson algorithm +// This will find the maximum possible flow from the source to the sink +int fordFulkerson(int graph[V][V], int s, int t) +{ + int u, v; + + // Create a residual graph and fill the residual graph with + // given capacities in the original graph as residual capacities + // in residual graph + int rGraph[V][V]; // Residual graph where rGraph[i][j] indicates + // residual capacity of edge from i to j (if there + // is an edge. If rGraph[i][j] is 0, then there is not) + for (u = 0; u < V; u++) + for (v = 0; v < V; v++) + rGraph[u][v] = graph[u][v]; + + int parent[V]; // This array is filled by BFS and to store path + + int maxFlow = 0; // There is no flow initially + + // Augument the flow while there is path from source to sink + while (bfs(rGraph, s, t, parent)) { + // Find minimum residual capacity of the edges along the + // path filled by BFS. Or we can say find the maximum flow + // through the path found. + int pathFlow = INT_MAX; + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + pathFlow = min(pathFlow, rGraph[u][v]); + } + + // Update residual capacities of the edges and reverse edges + // along the path + for (v = t; v != s; v = parent[v]) { + u = parent[v]; + rGraph[u][v] -= pathFlow; + rGraph[v][u] += pathFlow; + } + + // Add path flow to overall flow + maxFlow += pathFlow; + } + + // Return the overall flow as the maximum flow + return maxFlow; +} + +// Driver program to test above functions +int main() +{ + // Let us create a graph shown in the above example + int graph[V][V] = { { 0, 16, 13, 0, 0, 0 }, + { 0, 0, 10, 12, 0, 0 }, + { 0, 4, 0, 0, 14, 0 }, + { 0, 0, 9, 0, 0, 20 }, + { 0, 0, 0, 7, 0, 4 }, + { 0, 0, 0, 0, 0, 0 } }; + + int source = 0; + int sink = 5; + + cout << "The maximum possible flow is: " << fordFulkerson(graph, source, sink) << endl; + + return 0; +} From ba827e053c350143797abef10d50398980e4dd93 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 18 Jun 2023 11:16:00 +0530 Subject: [PATCH 1402/1894] Update Graphs_Ford_Fulkerson.cpp --- Graphs/Graphs_Ford_Fulkerson.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/Graphs/Graphs_Ford_Fulkerson.cpp b/Graphs/Graphs_Ford_Fulkerson.cpp index ec8a9dc0..809f4cb2 100644 --- a/Graphs/Graphs_Ford_Fulkerson.cpp +++ b/Graphs/Graphs_Ford_Fulkerson.cpp @@ -102,7 +102,6 @@ int fordFulkerson(int graph[V][V], int s, int t) // Return the overall flow as the maximum flow return maxFlow; } - // Driver program to test above functions int main() { From 245dbcbf8f69e0f0b024388fb256279e9483c028 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Sun, 18 Jun 2023 11:28:57 +0530 Subject: [PATCH 1403/1894] Update Snakes_and_Ladders.java Code commented and Time and Space complexity added --- Graphs/Snakes_and_Ladders.java | 43 ++++++++++++++-------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/Graphs/Snakes_and_Ladders.java b/Graphs/Snakes_and_Ladders.java index e31d48d4..fa84ce40 100644 --- a/Graphs/Snakes_and_Ladders.java +++ b/Graphs/Snakes_and_Ladders.java @@ -1,30 +1,18 @@ Explanation: -We start by importing the necessary classes and defining the class SnakesAndLadders. - -We declare the constant BOARD_SIZE to represent the number of cells on the board. - -We declare two maps: snakes to store the snake positions, and ladders to store the ladder positions. - -The SnakesAndLadders class has a constructor that initializes the snakes and ladders maps. - -The addSnake method is used to add a snake to the game by providing the start and end positions. - -The addLadder method is used to add a ladder to the game by providing the start and end positions. - -The playGame method simulates the game. It starts with the player's position at 0 and the number of dice rolls at 0. - -Inside the while loop, a dice is rolled using the rollDice method, and the player's position is updated. - -After each move, we check if the player has landed on a ladder or a snake. If so, we update the player's position accordingly. - -The rollDice method generates a random number between 1 and 6, simulating a dice roll. - -In the main method, we create an instance of SnakesAndLadders and add snakes and ladders to the game. - -Finally, we call the playGame method to start the game and print the number of dice rolls required to reach or exceed the BOARD_SIZE. - -Below is an implementation of the Snakes and Ladders game in Java, along with comments: +// We start by importing the necessary classes and defining the class SnakesAndLadders. +// We declare the constant BOARD_SIZE to represent the number of cells on the board. +// We declare two maps: snakes to store the snake positions, and ladders to store the ladder positions. +// The SnakesAndLadders class has a constructor that initializes the snakes and ladders maps. +// The addSnake method is used to add a snake to the game by providing the start and end positions. +// The addLadder method is used to add a ladder to the game by providing the start and end positions. +// The playGame method simulates the game. It starts with the player's position at 0 and the number of dice rolls at 0. +// Inside the while loop, a dice is rolled using the rollDice method, and the player's position is updated. +// After each move, we check if the player has landed on a ladder or a snake. If so, we update the player's position accordingly. +// The rollDice method generates a random number between 1 and 6, simulating a dice roll. +// In the main method, we create an instance of SnakesAndLadders and add snakes and ladders to the game. +// Finally, we call the playGame method to start the game and print the number of dice rolls required to reach or exceed the BOARD_SIZE. +// Below is an implementation of the Snakes and Ladders game in Java, along with comments: import java.util.HashMap; import java.util.Map; @@ -113,3 +101,8 @@ public static void main(String[] args) { System.out.println("Number of dice rolls: " + diceRolls); } } + +Time Complexity: the average generalized time complexity of the code can be expressed as O(N), where N represents the average number of dice rolls required to + complete the game over a large number of instances. +Space Complexity: The average generalized space complexity of the code can be expressed as O(M), where M represents the average number of snakes and ladders add- + -ed to the game. From 11f0f3a2c491234ac33361cbd6cef21710b5b1f1 Mon Sep 17 00:00:00 2001 From: Shruti Swarupa Dhar <125943681+Shr-reny@users.noreply.github.com> Date: Sun, 18 Jun 2023 21:05:00 +0530 Subject: [PATCH 1404/1894] Update and rename Ford_Fulkerson.cpp to fordFulkerson.cpp --- Graphs/{Ford_Fulkerson.cpp => fordFulkerson.cpp} | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) rename Graphs/{Ford_Fulkerson.cpp => fordFulkerson.cpp} (95%) diff --git a/Graphs/Ford_Fulkerson.cpp b/Graphs/fordFulkerson.cpp similarity index 95% rename from Graphs/Ford_Fulkerson.cpp rename to Graphs/fordFulkerson.cpp index ca19799a..f785e710 100644 --- a/Graphs/Ford_Fulkerson.cpp +++ b/Graphs/fordFulkerson.cpp @@ -14,8 +14,9 @@ Explanation of the below C++ code : The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. The algorithm works by iteratively finding an augmenting path, which is a path from the source to the sink in the residual graph, i.e., the graph obtained by subtracting the current flow from the capacity of each edge. The algorithm then increases the flow along this path by the maximum possible amount, which is the minimum capacity of the edges along the path. -*/ +Time Complexity : O(|V| * E^2) ,where E is the number of edges and V is the number of vertices. +Space Complexity :O(V) , as we created queue.*/ -------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ @@ -138,3 +139,6 @@ int main() return 0; } + +/*Sample Output: +The maximum possible flow is 23. */ From 1c62facf08497fe5b3200c24c5ce2ff176bc6ec5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:37:59 +0530 Subject: [PATCH 1405/1894] add single cycle check --- Graphs/single_cycle_check,go | 29 +++++++++++++++++++++++++++++ Graphs/union_find.go | 2 -- 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 Graphs/single_cycle_check,go diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check,go new file mode 100644 index 00000000..eb5b63b7 --- /dev/null +++ b/Graphs/single_cycle_check,go @@ -0,0 +1,29 @@ +package main + +func HasSingleCycle(array []int) bool { + nextElementVisited := 0 + currIdx := 0 + + for nextElementVisited < len(array) { + // Check if more than one element has been visited and current index is back to the starting index (0) + if nextElementVisited > 0 && currIdx == 0 { + return false // Multiple cycles detected, return false + } + + nextElementVisited += 1 // Increment the count of visited elements + currIdx = getNextIdx(array, currIdx) // Get the index of the next element + } + + return currIdx == 0 // Return true if all elements have been visited in a single cycle +} + +func getNextIdx(array []int, currIdx int) int { + jump := array[currIdx] // Get the jump value from the current index + nextIdx := (currIdx + jump) % len(array) // Calculate the index of the next element + + if nextIdx >= 0 { + return nextIdx // Return the next index if it is non-negative + } + + return nextIdx + len(array) // Adjust the next index if it is negative (wrapped around to the beginning) +} diff --git a/Graphs/union_find.go b/Graphs/union_find.go index 6b93374d..e948818e 100644 --- a/Graphs/union_find.go +++ b/Graphs/union_find.go @@ -52,8 +52,6 @@ Find : O(log(n)) time O(1) space where n is total number of values Union : O(log(n)) time O(1) space where n is total number of values - - */ package main From 2349b27238cf0ba448110ea01cd0270d79345a76 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:38:54 +0530 Subject: [PATCH 1406/1894] add explanation --- Graphs/single_cycle_check,go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check,go index eb5b63b7..767e83b2 100644 --- a/Graphs/single_cycle_check,go +++ b/Graphs/single_cycle_check,go @@ -1,3 +1,37 @@ +/* + Explanation: + + The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array + has a single cycle. It initializes two variables: nextElementVisited to keep track of the number of elements visited, and + currIdx to track the current index in the array. + + The function enters a loop that continues until all elements in the array are visited. It checks if nextElementVisited is + greater than 0 (indicating that at least one element has been visited) and currIdx is 0. If this condition is true, it means + the loop has returned to the starting index prematurely, indicating multiple cycles. In such a case, the function returns + false. + + Inside the loop, nextElementVisited is incremented by 1, and the currIdx is updated using the getNextIdx function, which we + will examine next. + + The getNextIdx function takes an integer array and the current index as input and returns the index of the next element in + the cycle. + + It first retrieves the jump value from the current index in the array. The jump value represents the number of steps to take + from the current element. + + The nextIdx is calculated by adding the jump value to the current index and taking the modulo % operator with the length of + the array. This ensures that the index stays within the valid range of the array. + + Finally, there is a check to ensure that nextIdx is non-negative. If it is negative, it means the index has wrapped around to + the beginning of the array. In such a case, the function adds the length of the array to nextIdx to correctly calculate the next index. + + Once the loop in the HasSingleCycle function completes, the final check is made to ensure that the currIdx is back at the + starting index (0). If it is, it means all elements have been visited in a single cycle, and the function returns true. + Otherwise, it returns false. + + Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices + and jumps between elements. +*/ package main func HasSingleCycle(array []int) bool { From c5cffe9f80b529e8ed4eba2a28656223ba19d23d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:40:49 +0530 Subject: [PATCH 1407/1894] add question --- Graphs/single_cycle_check,go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check,go index 767e83b2..69f61b65 100644 --- a/Graphs/single_cycle_check,go +++ b/Graphs/single_cycle_check,go @@ -1,4 +1,14 @@ /* + + You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer + 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. + If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the + last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0 + + Write a function that returns a boolean representing whether the jumps in the array form a single + cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every + element in the array is visited exactly once before landing back on the starting index. + Explanation: The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array From 4961a40352604aecc16225c230506a07a77d2110 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:41:30 +0530 Subject: [PATCH 1408/1894] add sample io --- Graphs/single_cycle_check,go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check,go index 69f61b65..6641dcef 100644 --- a/Graphs/single_cycle_check,go +++ b/Graphs/single_cycle_check,go @@ -9,6 +9,9 @@ cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every element in the array is visited exactly once before landing back on the starting index. + Sample Input: [2, 3, 1, -4, -4, 2] + Output: True + Explanation: The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array From d4f00b6771e81d77fe23a9fcf632841ad5240dac Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:42:25 +0530 Subject: [PATCH 1409/1894] add time and space --- Graphs/single_cycle_check,go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check,go index 6641dcef..dc9dc584 100644 --- a/Graphs/single_cycle_check,go +++ b/Graphs/single_cycle_check,go @@ -44,6 +44,9 @@ Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices and jumps between elements. + + Time Complexity : O(n) where n is the length of the input array + Space Complexity : O(1) */ package main From 8eef3f551357e41142770ab8917648df86d628b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 18 Jun 2023 23:45:09 +0530 Subject: [PATCH 1410/1894] add main func and correct file extension --- ...single_cycle_check,go => single_cycle_check.go} | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) rename Graphs/{single_cycle_check,go => single_cycle_check.go} (93%) diff --git a/Graphs/single_cycle_check,go b/Graphs/single_cycle_check.go similarity index 93% rename from Graphs/single_cycle_check,go rename to Graphs/single_cycle_check.go index dc9dc584..e38cb304 100644 --- a/Graphs/single_cycle_check,go +++ b/Graphs/single_cycle_check.go @@ -1,5 +1,4 @@ /* - You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the @@ -50,6 +49,9 @@ */ package main +import "fmt" + + func HasSingleCycle(array []int) bool { nextElementVisited := 0 currIdx := 0 @@ -77,3 +79,13 @@ func getNextIdx(array []int, currIdx int) int { return nextIdx + len(array) // Adjust the next index if it is negative (wrapped around to the beginning) } + + +func main() { + // Test cases + array1 := []int{2, 3, 1, -4, -4, 2} // has a single cycle + fmt.Println("Array 1:", HasSingleCycle(array1)) // Output: true + + array2 := []int{2, 2, -1} // does have a single cycle + fmt.Println("Array 2:", HasSingleCycle(array2)) // Output: true +} \ No newline at end of file From 2fbab2884f2765c44eb42247e178c6eae4c77c48 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:33:13 +0530 Subject: [PATCH 1411/1894] add single cycle check in c++ --- Graphs/single_cycle_check.cpp | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Graphs/single_cycle_check.cpp diff --git a/Graphs/single_cycle_check.cpp b/Graphs/single_cycle_check.cpp new file mode 100644 index 00000000..7ca857d8 --- /dev/null +++ b/Graphs/single_cycle_check.cpp @@ -0,0 +1,45 @@ +#include +#include + +using namespace std; + +// Function to check if the given array has a single cycle +bool hasSingleCycle(vector& array) { + int nextElementVisited = 0; + int currIdx = 0; + + while (nextElementVisited < array.size()) { + // Check if more than one element has been visited and current index is back to the starting index (0) + if (nextElementVisited > 0 && currIdx == 0) { + return false; // Multiple cycles detected, return false + } + + nextElementVisited++; // Increment the count of visited elements + currIdx = getNextIdx(array, currIdx); // Get the index of the next element + } + + return currIdx == 0; // Return true if all elements have been visited in a single cycle +} + +// Function to get the index of the next element in the cycle +int getNextIdx(vector& array, int currIdx) { + int jump = array[currIdx]; // Get the jump value from the current index + int nextIdx = (currIdx + jump) % array.size(); // Calculate the index of the next element + + if (nextIdx >= 0) { + return nextIdx; // Return the next index if it is non-negative + } + + return nextIdx + array.size(); // Adjust the next index if it is negative (wrapped around to the beginning) +} + +int main() { + // Test cases + vector array1 = {2, 3, 1, -4, -4, 2}; + cout << "Array 1: " << (hasSingleCycle(array1) ? "true" : "false") << endl; + + vector array2 = {2, 2, -1}; + cout << "Array 2: " << (hasSingleCycle(array2) ? "true" : "false") << endl; + + return 0; +} From be37da2c43c4cf888c6d3c6d74ea0afb97a88624 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:33:28 +0530 Subject: [PATCH 1412/1894] add explanation --- Graphs/single_cycle_check.cpp | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Graphs/single_cycle_check.cpp b/Graphs/single_cycle_check.cpp index 7ca857d8..72e0e002 100644 --- a/Graphs/single_cycle_check.cpp +++ b/Graphs/single_cycle_check.cpp @@ -1,3 +1,52 @@ +/* + You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer + 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. + If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the + last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0 + + Write a function that returns a boolean representing whether the jumps in the array form a single + cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every + element in the array is visited exactly once before landing back on the starting index. + + Sample Input: [2, 3, 1, -4, -4, 2] + Output: True + + Explanation: + + The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array + has a single cycle. It initializes two variables: nextElementVisited to keep track of the number of elements visited, and + currIdx to track the current index in the array. + + The function enters a loop that continues until all elements in the array are visited. It checks if nextElementVisited is + greater than 0 (indicating that at least one element has been visited) and currIdx is 0. If this condition is true, it means + the loop has returned to the starting index prematurely, indicating multiple cycles. In such a case, the function returns + false. + + Inside the loop, nextElementVisited is incremented by 1, and the currIdx is updated using the getNextIdx function, which we + will examine next. + + The getNextIdx function takes an integer array and the current index as input and returns the index of the next element in + the cycle. + + It first retrieves the jump value from the current index in the array. The jump value represents the number of steps to take + from the current element. + + The nextIdx is calculated by adding the jump value to the current index and taking the modulo % operator with the length of + the array. This ensures that the index stays within the valid range of the array. + + Finally, there is a check to ensure that nextIdx is non-negative. If it is negative, it means the index has wrapped around to + the beginning of the array. In such a case, the function adds the length of the array to nextIdx to correctly calculate the next index. + + Once the loop in the HasSingleCycle function completes, the final check is made to ensure that the currIdx is back at the + starting index (0). If it is, it means all elements have been visited in a single cycle, and the function returns true. + Otherwise, it returns false. + + Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices + and jumps between elements. + + Time Complexity : O(n) where n is the length of the input array + Space Complexity : O(1) +*/ #include #include From 4e27884557347f6349ea43e0165a29b34e30afb5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:36:10 +0530 Subject: [PATCH 1413/1894] add single cycle check in java --- Graphs/single_cycle_check.java | 91 ++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Graphs/single_cycle_check.java diff --git a/Graphs/single_cycle_check.java b/Graphs/single_cycle_check.java new file mode 100644 index 00000000..a53e0771 --- /dev/null +++ b/Graphs/single_cycle_check.java @@ -0,0 +1,91 @@ +/* + You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer + 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. + If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the + last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0 + + Write a function that returns a boolean representing whether the jumps in the array form a single + cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every + element in the array is visited exactly once before landing back on the starting index. + + Sample Input: [2, 3, 1, -4, -4, 2] + Output: True + + Explanation: + + The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array + has a single cycle. It initializes two variables: nextElementVisited to keep track of the number of elements visited, and + currIdx to track the current index in the array. + + The function enters a loop that continues until all elements in the array are visited. It checks if nextElementVisited is + greater than 0 (indicating that at least one element has been visited) and currIdx is 0. If this condition is true, it means + the loop has returned to the starting index prematurely, indicating multiple cycles. In such a case, the function returns + false. + + Inside the loop, nextElementVisited is incremented by 1, and the currIdx is updated using the getNextIdx function, which we + will examine next. + + The getNextIdx function takes an integer array and the current index as input and returns the index of the next element in + the cycle. + + It first retrieves the jump value from the current index in the array. The jump value represents the number of steps to take + from the current element. + + The nextIdx is calculated by adding the jump value to the current index and taking the modulo % operator with the length of + the array. This ensures that the index stays within the valid range of the array. + + Finally, there is a check to ensure that nextIdx is non-negative. If it is negative, it means the index has wrapped around to + the beginning of the array. In such a case, the function adds the length of the array to nextIdx to correctly calculate the next index. + + Once the loop in the HasSingleCycle function completes, the final check is made to ensure that the currIdx is back at the + starting index (0). If it is, it means all elements have been visited in a single cycle, and the function returns true. + Otherwise, it returns false. + + Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices + and jumps between elements. + + Time Complexity : O(n) where n is the length of the input array + Space Complexity : O(1) +*/ +import java.util.*; + +public class Main { + // Function to check if the given array has a single cycle + public static boolean hasSingleCycle(int[] array) { + int nextElementVisited = 0; + int currIdx = 0; + + while (nextElementVisited < array.length) { + // Check if more than one element has been visited and current index is back to the starting index (0) + if (nextElementVisited > 0 && currIdx == 0) { + return false; // Multiple cycles detected, return false + } + + nextElementVisited++; // Increment the count of visited elements + currIdx = getNextIdx(array, currIdx); // Get the index of the next element + } + + return currIdx == 0; // Return true if all elements have been visited in a single cycle + } + + // Function to get the index of the next element in the cycle + public static int getNextIdx(int[] array, int currIdx) { + int jump = array[currIdx]; // Get the jump value from the current index + int nextIdx = (currIdx + jump) % array.length; // Calculate the index of the next element + + if (nextIdx >= 0) { + return nextIdx; // Return the next index if it is non-negative + } + + return nextIdx + array.length; // Adjust the next index if it is negative (wrapped around to the beginning) + } + + public static void main(String[] args) { + // Test cases + int[] array1 = {2, 3, 1, -4, -4, 2}; + System.out.println("Array 1: " + (hasSingleCycle(array1) ? "true" : "false")); + + int[] array2 = {2, 2, -1}; + System.out.println("Array 2: " + (hasSingleCycle(array2) ? "true" : "false")); + } +} From 560e6310724eb16805927c00e0b8375352ecd7c0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:37:42 +0530 Subject: [PATCH 1414/1894] add single cycle check in python --- Graphs/single_cycle_check.py | 81 ++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Graphs/single_cycle_check.py diff --git a/Graphs/single_cycle_check.py b/Graphs/single_cycle_check.py new file mode 100644 index 00000000..444f7fff --- /dev/null +++ b/Graphs/single_cycle_check.py @@ -0,0 +1,81 @@ +''' + You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer + 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. + If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the + last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0 + + Write a function that returns a boolean representing whether the jumps in the array form a single + cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every + element in the array is visited exactly once before landing back on the starting index. + + Sample Input: [2, 3, 1, -4, -4, 2] + Output: True + + Explanation: + + The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array + has a single cycle. It initializes two variables: nextElementVisited to keep track of the number of elements visited, and + currIdx to track the current index in the array. + + The function enters a loop that continues until all elements in the array are visited. It checks if nextElementVisited is + greater than 0 (indicating that at least one element has been visited) and currIdx is 0. If this condition is true, it means + the loop has returned to the starting index prematurely, indicating multiple cycles. In such a case, the function returns + false. + + Inside the loop, nextElementVisited is incremented by 1, and the currIdx is updated using the getNextIdx function, which we + will examine next. + + The getNextIdx function takes an integer array and the current index as input and returns the index of the next element in + the cycle. + + It first retrieves the jump value from the current index in the array. The jump value represents the number of steps to take + from the current element. + + The nextIdx is calculated by adding the jump value to the current index and taking the modulo % operator with the length of + the array. This ensures that the index stays within the valid range of the array. + + Finally, there is a check to ensure that nextIdx is non-negative. If it is negative, it means the index has wrapped around to + the beginning of the array. In such a case, the function adds the length of the array to nextIdx to correctly calculate the next index. + + Once the loop in the HasSingleCycle function completes, the final check is made to ensure that the currIdx is back at the + starting index (0). If it is, it means all elements have been visited in a single cycle, and the function returns true. + Otherwise, it returns false. + + Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices + and jumps between elements. + + Time Complexity : O(n) where n is the length of the input array + Space Complexity : O(1) +''' + +def has_single_cycle(array): + next_element_visited = 0 + curr_idx = 0 + + while next_element_visited < len(array): + # Check if more than one element has been visited and current index is back to the starting index (0) + if next_element_visited > 0 and curr_idx == 0: + return False # Multiple cycles detected, return False + + next_element_visited += 1 # Increment the count of visited elements + curr_idx = get_next_idx(array, curr_idx) # Get the index of the next element + + return curr_idx == 0 # Return True if all elements have been visited in a single cycle + + +def get_next_idx(array, curr_idx): + jump = array[curr_idx] # Get the jump value from the current index + next_idx = (curr_idx + jump) % len(array) # Calculate the index of the next element + + if next_idx >= 0: + return next_idx # Return the next index if it is non-negative + + return next_idx + len(array) # Adjust the next index if it is negative (wrapped around to the beginning) + + +# Test cases +array1 = [2, 3, 1, -4, -4, 2] +print("Array 1:", has_single_cycle(array1)) + +array2 = [2, 2, -1] +print("Array 2:", has_single_cycle(array2)) From 0693e3846135ec80fc215209eccc77b86fd4a817 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:39:37 +0530 Subject: [PATCH 1415/1894] add single cycle check in javascript --- Graphs/single_cycle_check.js | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Graphs/single_cycle_check.js diff --git a/Graphs/single_cycle_check.js b/Graphs/single_cycle_check.js new file mode 100644 index 00000000..670de1d3 --- /dev/null +++ b/Graphs/single_cycle_check.js @@ -0,0 +1,83 @@ +/* + You're given an array of integers where each integer represents a jump of its value in the array. For instance, the integer + 2 represents a jump of two indices forward in the array; the integer -3 represents a jump of three indices backward in the array. + If a jump spills past the array's bounds, it wraps over to the other side. For instance, a jump of -1 at index 0 brings us to the + last index in the array. Similarly, a jump of 1 at the last index in the array brings us to index 0 + + Write a function that returns a boolean representing whether the jumps in the array form a single + cycle. A single cycle occurs if, starting at any index in the array and following the jumps, every + element in the array is visited exactly once before landing back on the starting index. + + Sample Input: [2, 3, 1, -4, -4, 2] + Output: True + + Explanation: + + The HasSingleCycle function takes an integer array as input and returns a boolean value indicating whether the array + has a single cycle. It initializes two variables: nextElementVisited to keep track of the number of elements visited, and + currIdx to track the current index in the array. + + The function enters a loop that continues until all elements in the array are visited. It checks if nextElementVisited is + greater than 0 (indicating that at least one element has been visited) and currIdx is 0. If this condition is true, it means + the loop has returned to the starting index prematurely, indicating multiple cycles. In such a case, the function returns + false. + + Inside the loop, nextElementVisited is incremented by 1, and the currIdx is updated using the getNextIdx function, which we + will examine next. + + The getNextIdx function takes an integer array and the current index as input and returns the index of the next element in + the cycle. + + It first retrieves the jump value from the current index in the array. The jump value represents the number of steps to take + from the current element. + + The nextIdx is calculated by adding the jump value to the current index and taking the modulo % operator with the length of + the array. This ensures that the index stays within the valid range of the array. + + Finally, there is a check to ensure that nextIdx is non-negative. If it is negative, it means the index has wrapped around to + the beginning of the array. In such a case, the function adds the length of the array to nextIdx to correctly calculate the next index. + + Once the loop in the HasSingleCycle function completes, the final check is made to ensure that the currIdx is back at the + starting index (0). If it is, it means all elements have been visited in a single cycle, and the function returns true. + Otherwise, it returns false. + + Overall, this code snippet implements the logic to determine whether an array has a single cycle by tracking the indices + and jumps between elements. + + Time Complexity : O(n) where n is the length of the input array + Space Complexity : O(1) +*/ +function hasSingleCycle(array) { + let nextElementVisited = 0; + let currIdx = 0; + + while (nextElementVisited < array.length) { + // Check if more than one element has been visited and current index is back to the starting index (0) + if (nextElementVisited > 0 && currIdx === 0) { + return false; // Multiple cycles detected, return false + } + + nextElementVisited += 1; // Increment the count of visited elements + currIdx = getNextIdx(array, currIdx); // Get the index of the next element + } + + return currIdx === 0; // Return true if all elements have been visited in a single cycle +} + +function getNextIdx(array, currIdx) { + const jump = array[currIdx]; // Get the jump value from the current index + const nextIdx = (currIdx + jump) % array.length; // Calculate the index of the next element + + if (nextIdx >= 0) { + return nextIdx; // Return the next index if it is non-negative + } + + return nextIdx + array.length; // Adjust the next index if it is negative (wrapped around to the beginning) +} + +// Test cases +const array1 = [2, 3, 1, -4, -4, 2]; +console.log("Array 1:", hasSingleCycle(array1)); + +const array2 = [2, 2, -1]; +console.log("Array 2:", hasSingleCycle(array2)); From 07559f6fc12b16c5a23492b8afa14a660afafc9f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:42:18 +0530 Subject: [PATCH 1416/1894] add river sizes in go --- Graphs/river_sizes.go | 104 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Graphs/river_sizes.go diff --git a/Graphs/river_sizes.go b/Graphs/river_sizes.go new file mode 100644 index 00000000..5df5ade1 --- /dev/null +++ b/Graphs/river_sizes.go @@ -0,0 +1,104 @@ +package main + +func RiverSizes(matrix [][]int) []int { + // Slice to store the sizes of rivers + sizes := []int{} + + // Create a visited matrix to keep track of visited nodes + visited := make([][]bool, len(matrix)) + for i := range visited { + visited[i] = make([]bool, len(matrix[i])) + } + + // Iterate over each cell in the matrix + for i := range matrix { + for j := range matrix[i] { + // If the cell has already been visited, continue to the next iteration + if visited[i][j] { + continue + } + + // Explore the river connected to the current cell and update sizes + sizes = traverseNode(i, j, matrix, visited, sizes) + } + } + + return sizes +} + +func traverseNode(i, j int, matrix [][]int, visited [][]bool, sizes []int) []int { + // Variable to track the size of the current river + currentRiverSize := 0 + + // Queue to store nodes that need to be visited + nodesToExplore := [][]int{{i, j}} + + // Loop until there are no more nodes to explore + for len(nodesToExplore) > 0 { + // Dequeue the first node from the queue and update the current position (i, j) + currentNode := nodesToExplore[0] + nodesToExplore = nodesToExplore[1:] + i, j := currentNode[0], currentNode[1] + + // If the current node has already been visited, continue to the next iteration + if visited[i][j] { + continue + } + + // Mark the current node as visited + visited[i][j] = true + + // If the current node is land (0), continue to the next iteration + if matrix[i][j] == 0 { + continue + } + + // Increment the size of the current river + currentRiverSize++ + + // Get the unvisited neighboring nodes of the current node + unvisitedNeighbors := getUnvisitedNeighbors(i, j, matrix, visited) + + // Add the unvisited neighbors to the nodesToExplore queue + for _, neighbor := range unvisitedNeighbors { + nodesToExplore = append(nodesToExplore, neighbor) + } + } + + // If the current river size is greater than 0, append it to the sizes slice + if currentRiverSize > 0 { + sizes = append(sizes, currentRiverSize) + } + + return sizes +} + +func getUnvisitedNeighbors(i, j int, matrix [][]int, visited [][]bool) [][]int { + // Slice to store unvisited neighboring nodes + unvisitedNeighbors := [][]int{} + + // Check the four neighboring cells (up, down, left, right) of the current cell + // and add unvisited neighbors to the unvisitedNeighbors slice + + // Up neighbor + if i > 0 && !visited[i-1][j] { + unvisitedNeighbors = append(unvisitedNeighbors, []int{i - 1, j}) + } + + // Down neighbor + if i < len(matrix)-1 && !visited[i+1][j] { + unvisitedNeighbors = append(unvisitedNeighbors, []int{i + 1, j}) + } + + // Left neighbor + if j > 0 && !visited[i][j-1] { + unvisitedNeighbors = append(unvisitedNeighbors, []int{i, j - 1}) + } + + // Right neighbor + if j < len(matrix[0])-1 && !visited[i][j+1] { + unvisitedNeighbors = append(unvisitedNeighbors, []int{i, j + 1}) + } + + return unvisitedNeighbors +} From b33db213bf75a29b94dcc39ee9facc3c0e16294f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 21 Jun 2023 22:42:51 +0530 Subject: [PATCH 1417/1894] add explanation --- Graphs/river_sizes.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Graphs/river_sizes.go b/Graphs/river_sizes.go index 5df5ade1..53b7dbe4 100644 --- a/Graphs/river_sizes.go +++ b/Graphs/river_sizes.go @@ -1,3 +1,45 @@ +/* + + Explanation: + + 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. + + 2. The function then iterates over each cell in the matrix using nested loops. + + 3. If a cell has already been visited (marked as `true` in the `visited` matrix), the code continues to the next iteration to avoid processing it again. + + 4. If a cell has not been visited, the code calls the `traverseNode` function to explore the river connected to that cell and updates the `sizes` slice with the size of the river. + + 5. The `traverseNode` function takes the starting position (i, j) of a river, the matrix, the `visited` matrix, and the `sizes` slice as input. + + 6. It initializes a variable `currentRiverSize` to 0 to keep track of the size of the river being explored. + + 7. It maintains a queue (`nodesToExplore`) to store the nodes that need to be visited. It starts with the initial node (i, j). + + 8. The function enters a loop that continues until there are no more nodes to explore in the queue. + + 9. In each iteration, it dequeues the first node from the `nodesToExplore` queue and updates the current position (i, j) accordingly. + + 10. If the current node has already been visited, the code continues to the next iteration. + + 11. If the current node contains a value of 0 (indicating land), the code continues to the next iteration, as it's not part of the river. + + 12. If the current node contains a value of 1 (indicating a river), it increments the `currentRiverSize` by 1. + + 13. It then retrieves the unvisited neighboring nodes of the current node using the `getUnvisitedNeighbors` function and adds them to the `nodesToExplore` queue. + + 14. Once the loop finishes, if the `currentRiverSize` is greater than 0, it appends it to the `sizes` slice. + + 15. Finally, the `sizes` slice containing the sizes of all rivers is returned. + + 16. The `getUnvisitedNeighbors` function takes the current position (i, j), the matrix, and the `visited` matrix as input. + + 17. It checks the four neighboring cells (up, down, left, right) of the current cell and adds the unvisited neighbors to the `unvisitedNeighbors` slice. + + 18. The function returns the `unvisitedNeighbors` slice. + + The code essentially performs a depth-first search (DFS) traversal on the matrix to find connected regions of 1s (rivers) and keeps track of their sizes. The `visited` matrix helps avoid revisiting nodes that have already been processed, ensuring each river is counted only once. +*/ package main func RiverSizes(matrix [][]int) []int { From 2bc4081792b577ac2fa89018127d7111d111cc94 Mon Sep 17 00:00:00 2001 From: harshitcompcode <84669711+harshitcompcode@users.noreply.github.com> Date: Thu, 22 Jun 2023 22:22:59 +0530 Subject: [PATCH 1418/1894] Update Snakes_and_Ladders.java I applied the recommended changes --- Graphs/Snakes_and_Ladders.java | 41 +++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/Graphs/Snakes_and_Ladders.java b/Graphs/Snakes_and_Ladders.java index fa84ce40..f8608137 100644 --- a/Graphs/Snakes_and_Ladders.java +++ b/Graphs/Snakes_and_Ladders.java @@ -1,18 +1,33 @@ +/*You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. + +You start on square 1 of the board. In each move, starting from square curr, do the following: + +Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. +This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. +If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. +The game ends when you reach the square n2. +A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder. + +Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. + +For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. +Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1. + Explanation: -// We start by importing the necessary classes and defining the class SnakesAndLadders. -// We declare the constant BOARD_SIZE to represent the number of cells on the board. -// We declare two maps: snakes to store the snake positions, and ladders to store the ladder positions. -// The SnakesAndLadders class has a constructor that initializes the snakes and ladders maps. -// The addSnake method is used to add a snake to the game by providing the start and end positions. -// The addLadder method is used to add a ladder to the game by providing the start and end positions. -// The playGame method simulates the game. It starts with the player's position at 0 and the number of dice rolls at 0. -// Inside the while loop, a dice is rolled using the rollDice method, and the player's position is updated. -// After each move, we check if the player has landed on a ladder or a snake. If so, we update the player's position accordingly. -// The rollDice method generates a random number between 1 and 6, simulating a dice roll. -// In the main method, we create an instance of SnakesAndLadders and add snakes and ladders to the game. -// Finally, we call the playGame method to start the game and print the number of dice rolls required to reach or exceed the BOARD_SIZE. -// Below is an implementation of the Snakes and Ladders game in Java, along with comments: +We start by importing the necessary classes and defining the class SnakesAndLadders. +We declare the constant BOARD_SIZE to represent the number of cells on the board. +We declare two maps: snakes to store the snake positions, and ladders to store the ladder positions. +The SnakesAndLadders class has a constructor that initializes the snakes and ladders maps. +The addSnake method is used to add a snake to the game by providing the start and end positions. +The addLadder method is used to add a ladder to the game by providing the start and end positions. +The playGame method simulates the game. It starts with the player's position at 0 and the number of dice rolls at 0. +Inside the while loop, a dice is rolled using the rollDice method, and the player's position is updated. +After each move, we check if the player has landed on a ladder or a snake. If so, we update the player's position accordingly. +The rollDice method generates a random number between 1 and 6, simulating a dice roll. +In the main method, we create an instance of SnakesAndLadders and add snakes and ladders to the game. +Finally, we call the playGame method to start the game and print the number of dice rolls required to reach or exceed the BOARD_SIZE. +Below is an implementation of the Snakes and Ladders game in Java, along with comments:*/ import java.util.HashMap; import java.util.Map; From b1f8abeeb7bcf636918225c05d93eb0db31edf0e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:40:05 +0530 Subject: [PATCH 1419/1894] add question --- Graphs/river_sizes.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Graphs/river_sizes.go b/Graphs/river_sizes.go index 53b7dbe4..97509ca1 100644 --- a/Graphs/river_sizes.go +++ b/Graphs/river_sizes.go @@ -1,5 +1,17 @@ /* + You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only + 0's and 1's. Each 0 represent land and each 1 represent part of river. A river consists of any number of 1's + that are either horizontally or vertically adjacent (but not diagonally adjacent). + The number of adjacent 1's forming a river determine its size. + + Note that a river can twist. In other words, it doesn't have to be a straight vertical line or a straight + horizontal line; it can be L-shaped, for example. + + Write a function that returns an array of the sizes of all rivers represented in the input matrix. + The sizes don't need to be in any particular order. + + Explanation: 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. From a6b56c1c93f4585c9dd2c1f4ed44325811f2fdcf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:41:05 +0530 Subject: [PATCH 1420/1894] add sample io --- Graphs/river_sizes.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Graphs/river_sizes.go b/Graphs/river_sizes.go index 97509ca1..b21baa34 100644 --- a/Graphs/river_sizes.go +++ b/Graphs/river_sizes.go @@ -11,6 +11,14 @@ Write a function that returns an array of the sizes of all rivers represented in the input matrix. The sizes don't need to be in any particular order. + Sample Input:[ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], + ] + Output: [1, 2, 2, 2, 5] Explanation: From a88c63e6d4e09c477a66289e5a5e0de769fa4b74 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:45:31 +0530 Subject: [PATCH 1421/1894] add river sizes in python --- Graphs/river_sizes.py | 84 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Graphs/river_sizes.py diff --git a/Graphs/river_sizes.py b/Graphs/river_sizes.py new file mode 100644 index 00000000..4ecd99ba --- /dev/null +++ b/Graphs/river_sizes.py @@ -0,0 +1,84 @@ +def riverSizes(matrix): + # List to store the sizes of rivers + sizes = [] + + # Create a visited matrix to keep track of visited nodes + visited = [[False for _ in range(len(matrix[0]))] for _ in range(len(matrix))] + + # Iterate over each cell in the matrix + for i in range(len(matrix)): + for j in range(len(matrix[i])): + # If the cell has already been visited, continue to the next iteration + if visited[i][j]: + continue + + # Explore the river connected to the current cell and update sizes + sizes = traverseNode(i, j, matrix, visited, sizes) + + return sizes + + +def traverseNode(i, j, matrix, visited, sizes): + # Variable to track the size of the current river + currentRiverSize = 0 + + # Queue to store nodes that need to be visited + nodesToExplore = [[i, j]] + + # Loop until there are no more nodes to explore + while nodesToExplore: + # Dequeue the first node from the queue and update the current position (i, j) + currentNode = nodesToExplore.pop(0) + i, j = currentNode[0], currentNode[1] + + # If the current node has already been visited, continue to the next iteration + if visited[i][j]: + continue + + # Mark the current node as visited + visited[i][j] = True + + # If the current node is land (0), continue to the next iteration + if matrix[i][j] == 0: + continue + + # Increment the size of the current river + currentRiverSize += 1 + + # Get the unvisited neighboring nodes of the current node + unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited) + + # Add the unvisited neighbors to the nodesToExplore queue + nodesToExplore.extend(unvisitedNeighbors) + + # If the current river size is greater than 0, append it to the sizes list + if currentRiverSize > 0: + sizes.append(currentRiverSize) + + return sizes + + +def getUnvisitedNeighbors(i, j, matrix, visited): + # List to store unvisited neighboring nodes + unvisitedNeighbors = [] + + # Check the four neighboring cells (up, down, left, right) of the current cell + # and add unvisited neighbors to the unvisitedNeighbors list + + # Up neighbor + if i > 0 and not visited[i - 1][j]: + unvisitedNeighbors.append([i - 1, j]) + + # Down neighbor + if i < len(matrix) - 1 and not visited[i + 1][j]: + unvisitedNeighbors.append([i + 1, j]) + + # Left neighbor + if j > 0 and not visited[i][j - 1]: + unvisitedNeighbors.append([i, j - 1]) + + # Right neighbor + if j < len(matrix[0]) - 1 and not visited[i][j + 1]: + unvisitedNeighbors.append([i, j + 1]) + + return unvisitedNeighbors From 3b8ef9020c8fe2ce26e93aa85905a67db7bd9f65 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:45:41 +0530 Subject: [PATCH 1422/1894] add explanation --- Graphs/river_sizes.py | 63 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/Graphs/river_sizes.py b/Graphs/river_sizes.py index 4ecd99ba..247c9bfc 100644 --- a/Graphs/river_sizes.py +++ b/Graphs/river_sizes.py @@ -1,3 +1,66 @@ +''' + + You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only + 0's and 1's. Each 0 represent land and each 1 represent part of river. A river consists of any number of 1's + that are either horizontally or vertically adjacent (but not diagonally adjacent). + The number of adjacent 1's forming a river determine its size. + + Note that a river can twist. In other words, it doesn't have to be a straight vertical line or a straight + horizontal line; it can be L-shaped, for example. + + Write a function that returns an array of the sizes of all rivers represented in the input matrix. + The sizes don't need to be in any particular order. + + Sample Input:[ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], + ] + Output: [1, 2, 2, 2, 5] + + Explanation: + + 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. + + 2. The function then iterates over each cell in the matrix using nested loops. + + 3. If a cell has already been visited (marked as `true` in the `visited` matrix), the code continues to the next iteration to avoid processing it again. + + 4. If a cell has not been visited, the code calls the `traverseNode` function to explore the river connected to that cell and updates the `sizes` slice with the size of the river. + + 5. The `traverseNode` function takes the starting position (i, j) of a river, the matrix, the `visited` matrix, and the `sizes` slice as input. + + 6. It initializes a variable `currentRiverSize` to 0 to keep track of the size of the river being explored. + + 7. It maintains a queue (`nodesToExplore`) to store the nodes that need to be visited. It starts with the initial node (i, j). + + 8. The function enters a loop that continues until there are no more nodes to explore in the queue. + + 9. In each iteration, it dequeues the first node from the `nodesToExplore` queue and updates the current position (i, j) accordingly. + + 10. If the current node has already been visited, the code continues to the next iteration. + + 11. If the current node contains a value of 0 (indicating land), the code continues to the next iteration, as it's not part of the river. + + 12. If the current node contains a value of 1 (indicating a river), it increments the `currentRiverSize` by 1. + + 13. It then retrieves the unvisited neighboring nodes of the current node using the `getUnvisitedNeighbors` function and adds them to the `nodesToExplore` queue. + + 14. Once the loop finishes, if the `currentRiverSize` is greater than 0, it appends it to the `sizes` slice. + + 15. Finally, the `sizes` slice containing the sizes of all rivers is returned. + + 16. The `getUnvisitedNeighbors` function takes the current position (i, j), the matrix, and the `visited` matrix as input. + + 17. It checks the four neighboring cells (up, down, left, right) of the current cell and adds the unvisited neighbors to the `unvisitedNeighbors` slice. + + 18. The function returns the `unvisitedNeighbors` slice. + + The code essentially performs a depth-first search (DFS) traversal on the matrix to find connected regions of 1s (rivers) and keeps track of their sizes. The `visited` matrix helps avoid revisiting nodes that have already been processed, ensuring each river is counted only once. + +''' def riverSizes(matrix): # List to store the sizes of rivers sizes = [] From a1d4b0d66d4a56a89cda88da80f426d88ec707a3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:52:04 +0530 Subject: [PATCH 1423/1894] add river sizes in c++ --- Graphs/river_sizes.cpp | 186 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 Graphs/river_sizes.cpp diff --git a/Graphs/river_sizes.cpp b/Graphs/river_sizes.cpp new file mode 100644 index 00000000..4171d438 --- /dev/null +++ b/Graphs/river_sizes.cpp @@ -0,0 +1,186 @@ +/* + You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only + 0's and 1's. Each 0 represent land and each 1 represent part of river. A river consists of any number of 1's + that are either horizontally or vertically adjacent (but not diagonally adjacent). + The number of adjacent 1's forming a river determine its size. + + Note that a river can twist. In other words, it doesn't have to be a straight vertical line or a straight + horizontal line; it can be L-shaped, for example. + + Write a function that returns an array of the sizes of all rivers represented in the input matrix. + The sizes don't need to be in any particular order. + + Sample Input:[ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], + ] + Output: [1, 2, 2, 2, 5] + + Explanation: + + 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. + + 2. The function then iterates over each cell in the matrix using nested loops. + + 3. If a cell has already been visited (marked as `true` in the `visited` matrix), the code continues to the next iteration to avoid processing it again. + + 4. If a cell has not been visited, the code calls the `traverseNode` function to explore the river connected to that cell and updates the `sizes` slice with the size of the river. + + 5. The `traverseNode` function takes the starting position (i, j) of a river, the matrix, the `visited` matrix, and the `sizes` slice as input. + + 6. It initializes a variable `currentRiverSize` to 0 to keep track of the size of the river being explored. + + 7. It maintains a queue (`nodesToExplore`) to store the nodes that need to be visited. It starts with the initial node (i, j). + + 8. The function enters a loop that continues until there are no more nodes to explore in the queue. + + 9. In each iteration, it dequeues the first node from the `nodesToExplore` queue and updates the current position (i, j) accordingly. + + 10. If the current node has already been visited, the code continues to the next iteration. + + 11. If the current node contains a value of 0 (indicating land), the code continues to the next iteration, as it's not part of the river. + + 12. If the current node contains a value of 1 (indicating a river), it increments the `currentRiverSize` by 1. + + 13. It then retrieves the unvisited neighboring nodes of the current node using the `getUnvisitedNeighbors` function and adds them to the `nodesToExplore` queue. + + 14. Once the loop finishes, if the `currentRiverSize` is greater than 0, it appends it to the `sizes` slice. + + 15. Finally, the `sizes` slice containing the sizes of all rivers is returned. + + 16. The `getUnvisitedNeighbors` function takes the current position (i, j), the matrix, and the `visited` matrix as input. + + 17. It checks the four neighboring cells (up, down, left, right) of the current cell and adds the unvisited neighbors to the `unvisitedNeighbors` slice. + + 18. The function returns the `unvisitedNeighbors` slice. + + The code essentially performs a depth-first search (DFS) traversal on the matrix to find connected regions of 1s (rivers) and keeps track of their sizes. The `visited` matrix helps avoid revisiting nodes that have already been processed, ensuring each river is counted only once. +*/ +#include +#include + +using namespace std; + +vector riverSizes(vector>& matrix) { + // Vector to store the sizes of rivers + vector sizes; + + // Create a visited matrix to keep track of visited nodes + vector> visited(matrix.size(), vector(matrix[0].size(), false)); + + // Iterate over each cell in the matrix + for (int i = 0; i < matrix.size(); i++) { + for (int j = 0; j < matrix[i].size(); j++) { + // If the cell has already been visited, continue to the next iteration + if (visited[i][j]) { + continue; + } + + // Explore the river connected to the current cell and update sizes + sizes = traverseNode(i, j, matrix, visited, sizes); + } + } + + return sizes; +} + +vector traverseNode(int i, int j, vector>& matrix, vector>& visited, vector& sizes) { + // Variable to track the size of the current river + int currentRiverSize = 0; + + // Queue to store nodes that need to be visited + vector> nodesToExplore{{i, j}}; + + // Loop until there are no more nodes to explore + while (!nodesToExplore.empty()) { + // Dequeue the first node from the queue and update the current position (i, j) + vector currentNode = nodesToExplore[0]; + nodesToExplore.erase(nodesToExplore.begin()); + i = currentNode[0]; + j = currentNode[1]; + + // If the current node has already been visited, continue to the next iteration + if (visited[i][j]) { + continue; + } + + // Mark the current node as visited + visited[i][j] = true; + + // If the current node is land (0), continue to the next iteration + if (matrix[i][j] == 0) { + continue; + } + + // Increment the size of the current river + currentRiverSize++; + + // Get the unvisited neighboring nodes of the current node + vector> unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited); + + // Add the unvisited neighbors to the nodesToExplore queue + for (const auto& neighbor : unvisitedNeighbors) { + nodesToExplore.push_back(neighbor); + } + } + + // If the current river size is greater than 0, append it to the sizes vector + if (currentRiverSize > 0) { + sizes.push_back(currentRiverSize); + } + + return sizes; +} + +vector> getUnvisitedNeighbors(int i, int j, vector>& matrix, vector>& visited) { + // Vector to store unvisited neighboring nodes + vector> unvisitedNeighbors; + + // Check the four neighboring cells (up, down, left, right) of the current cell + // and add unvisited neighbors to the unvisitedNeighbors vector + + // Up neighbor + if (i > 0 && !visited[i - 1][j]) { + unvisitedNeighbors.push_back({i - 1, j}); + } + + // Down neighbor + if (i < matrix.size() - 1 && !visited[i + 1][j]) { + unvisitedNeighbors.push_back({i + 1, j}); + } + + // Left neighbor + if (j > 0 && !visited[i][j - 1]) { + unvisitedNeighbors.push_back({i, j - 1}); + } + + // Right neighbor + if (j < matrix[0].size() - 1 && !visited[i][j + 1]) { + unvisitedNeighbors.push_back({i, j + 1}); + } + + return unvisitedNeighbors; +} + +int main() { + // Test the riverSizes function + vector> matrix = { + {1, 0, 0, 1, 0}, + {1, 0, 1, 0, 0}, + {0, 0, 1, 0, 1}, + {1, 0, 1, 0, 1}, + {1, 0, 1, 1, 0} + }; + + vector sizes = riverSizes(matrix); + + // Print the sizes of the rivers + for (const auto& size : sizes) { + cout << size << " "; + } + + return 0; +} From 8866c4987b14312b3c6b68d3d50390c899636a8c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:56:14 +0530 Subject: [PATCH 1424/1894] add river sizes in js --- Graphs/river_sizes.js | 172 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 Graphs/river_sizes.js diff --git a/Graphs/river_sizes.js b/Graphs/river_sizes.js new file mode 100644 index 00000000..18ea1f1d --- /dev/null +++ b/Graphs/river_sizes.js @@ -0,0 +1,172 @@ +/* + You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only + 0's and 1's. Each 0 represent land and each 1 represent part of river. A river consists of any number of 1's + that are either horizontally or vertically adjacent (but not diagonally adjacent). + The number of adjacent 1's forming a river determine its size. + + Note that a river can twist. In other words, it doesn't have to be a straight vertical line or a straight + horizontal line; it can be L-shaped, for example. + + Write a function that returns an array of the sizes of all rivers represented in the input matrix. + The sizes don't need to be in any particular order. + + Sample Input:[ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], + ] + Output: [1, 2, 2, 2, 5] + + Explanation: + + 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. + + 2. The function then iterates over each cell in the matrix using nested loops. + + 3. If a cell has already been visited (marked as `true` in the `visited` matrix), the code continues to the next iteration to avoid processing it again. + + 4. If a cell has not been visited, the code calls the `traverseNode` function to explore the river connected to that cell and updates the `sizes` slice with the size of the river. + + 5. The `traverseNode` function takes the starting position (i, j) of a river, the matrix, the `visited` matrix, and the `sizes` slice as input. + + 6. It initializes a variable `currentRiverSize` to 0 to keep track of the size of the river being explored. + + 7. It maintains a queue (`nodesToExplore`) to store the nodes that need to be visited. It starts with the initial node (i, j). + + 8. The function enters a loop that continues until there are no more nodes to explore in the queue. + + 9. In each iteration, it dequeues the first node from the `nodesToExplore` queue and updates the current position (i, j) accordingly. + + 10. If the current node has already been visited, the code continues to the next iteration. + + 11. If the current node contains a value of 0 (indicating land), the code continues to the next iteration, as it's not part of the river. + + 12. If the current node contains a value of 1 (indicating a river), it increments the `currentRiverSize` by 1. + + 13. It then retrieves the unvisited neighboring nodes of the current node using the `getUnvisitedNeighbors` function and adds them to the `nodesToExplore` queue. + + 14. Once the loop finishes, if the `currentRiverSize` is greater than 0, it appends it to the `sizes` slice. + + 15. Finally, the `sizes` slice containing the sizes of all rivers is returned. + + 16. The `getUnvisitedNeighbors` function takes the current position (i, j), the matrix, and the `visited` matrix as input. + + 17. It checks the four neighboring cells (up, down, left, right) of the current cell and adds the unvisited neighbors to the `unvisitedNeighbors` slice. + + 18. The function returns the `unvisitedNeighbors` slice. + + The code essentially performs a depth-first search (DFS) traversal on the matrix to find connected regions of 1s (rivers) and keeps track of their sizes. The `visited` matrix helps avoid revisiting nodes that have already been processed, ensuring each river is counted only once. +*/ +function riverSizes(matrix) { + // Array to store the sizes of rivers + const sizes = []; + + // Create a visited matrix to keep track of visited nodes + const visited = Array.from({ length: matrix.length }, () => + new Array(matrix[0].length).fill(false) + ); + + // Iterate over each cell in the matrix + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[i].length; j++) { + // If the cell has already been visited, continue to the next iteration + if (visited[i][j]) { + continue; + } + + // Explore the river connected to the current cell and update sizes + sizes.push(traverseNode(i, j, matrix, visited)); + } + } + + return sizes; +} + +function traverseNode(i, j, matrix, visited) { + // Variable to track the size of the current river + let currentRiverSize = 0; + + // Queue to store nodes that need to be visited + const nodesToExplore = [[i, j]]; + + // Loop until there are no more nodes to explore + while (nodesToExplore.length) { + // Dequeue the first node from the queue and update the current position (i, j) + const [currentI, currentJ] = nodesToExplore.shift(); + + // If the current node has already been visited, continue to the next iteration + if (visited[currentI][currentJ]) { + continue; + } + + // Mark the current node as visited + visited[currentI][currentJ] = true; + + // If the current node is land (0), continue to the next iteration + if (matrix[currentI][currentJ] === 0) { + continue; + } + + // Increment the size of the current river + currentRiverSize++; + + // Get the unvisited neighboring nodes of the current node + const unvisitedNeighbors = getUnvisitedNeighbors( + currentI, + currentJ, + matrix, + visited + ); + + // Add the unvisited neighbors to the nodesToExplore queue + nodesToExplore.push(...unvisitedNeighbors); + } + + return currentRiverSize; +} + +function getUnvisitedNeighbors(i, j, matrix, visited) { + // Array to store unvisited neighboring nodes + const unvisitedNeighbors = []; + + // Check the four neighboring cells (up, down, left, right) of the current cell + // and add unvisited neighbors to the unvisitedNeighbors array + + // Up neighbor + if (i > 0 && !visited[i - 1][j]) { + unvisitedNeighbors.push([i - 1, j]); + } + + // Down neighbor + if (i < matrix.length - 1 && !visited[i + 1][j]) { + unvisitedNeighbors.push([i + 1, j]); + } + + // Left neighbor + if (j > 0 && !visited[i][j - 1]) { + unvisitedNeighbors.push([i, j - 1]); + } + + // Right neighbor + if (j < matrix[0].length - 1 && !visited[i][j + 1]) { + unvisitedNeighbors.push([i, j + 1]); + } + + return unvisitedNeighbors; +} + +// Test the riverSizes function +const matrix = [ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], +]; + +const sizes = riverSizes(matrix); + +// Print the sizes of the rivers +console.log(sizes); From c5adf4e8fae8cdd256be36b53b60e1059c335a51 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 22 Jun 2023 22:56:49 +0530 Subject: [PATCH 1425/1894] move to famous algorithms --- Graphs/knuth_morris_pratt.java => Famous Algorithms/kmp.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/knuth_morris_pratt.java => Famous Algorithms/kmp.java (100%) diff --git a/Graphs/knuth_morris_pratt.java b/Famous Algorithms/kmp.java similarity index 100% rename from Graphs/knuth_morris_pratt.java rename to Famous Algorithms/kmp.java From e9b4d52ce0e8d89c6cd78a1ae203f2c6fdfadbba Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 23 Jun 2023 22:29:26 +0530 Subject: [PATCH 1426/1894] Create longest_string.cpp --- Strings/longest_string.cpp | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Strings/longest_string.cpp diff --git a/Strings/longest_string.cpp b/Strings/longest_string.cpp new file mode 100644 index 00000000..31f94717 --- /dev/null +++ b/Strings/longest_string.cpp @@ -0,0 +1,46 @@ +#include + +class Solution { +public: + string longestPalindrome(string s) { + int n = s.length(); + if (n < 2) { + return s; + } + + int start = 0; // start index of the longest palindrome + int maxLen = 1; // length of the longest palindrome + + // Initialize a table to store the results of subproblems + vector> dp(n, vector(n, false)); + + // All substrings of length 1 are palindromes + for (int i = 0; i < n; i++) { + dp[i][i] = true; + } + + // Check for substrings of length 2 + for (int i = 0; i < n - 1; i++) { + if (s[i] == s[i + 1]) { + dp[i][i + 1] = true; + start = i; + maxLen = 2; + } + } + + // Check for substrings of length greater than 2 + for (int len = 3; len <= n; len++) { + for (int i = 0; i < n - len + 1; i++) { + int j = i + len - 1; + if (s[i] == s[j] && dp[i + 1][j - 1]) { + dp[i][j] = true; + start = i; + maxLen = len; + } + } + } + + // Return the longest palindrome substring + return s.substr(start, maxLen); + } +}; From 40f4790b338cb480bbad76ceb6467bad0b527728 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:05:50 +0530 Subject: [PATCH 1427/1894] move into strings --- .../longest palindromic substring.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename longest palindromic substring.java => Strings/longest palindromic substring.java (100%) diff --git a/longest palindromic substring.java b/Strings/longest palindromic substring.java similarity index 100% rename from longest palindromic substring.java rename to Strings/longest palindromic substring.java From f489d695200154c4abc1cb36acc7b705089660aa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:07:14 +0530 Subject: [PATCH 1428/1894] rename file --- ...ing_in_2DSorted_Array.cpp => searching_in_2d_sorted_array.cpp} | 0 ... in 2d sorted array.java => searching_in_2d_sorted_array.java} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{searching_in_2DSorted_Array.cpp => searching_in_2d_sorted_array.cpp} (100%) rename 2D Arrays (Matrix)/{search in 2d sorted array.java => searching_in_2d_sorted_array.java} (100%) diff --git a/2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp b/2D Arrays (Matrix)/searching_in_2d_sorted_array.cpp similarity index 100% rename from 2D Arrays (Matrix)/searching_in_2DSorted_Array.cpp rename to 2D Arrays (Matrix)/searching_in_2d_sorted_array.cpp diff --git a/2D Arrays (Matrix)/search in 2d sorted array.java b/2D Arrays (Matrix)/searching_in_2d_sorted_array.java similarity index 100% rename from 2D Arrays (Matrix)/search in 2d sorted array.java rename to 2D Arrays (Matrix)/searching_in_2d_sorted_array.java From d08d27e16e55b403169b341f6544386bfb6ca9aa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:07:26 +0530 Subject: [PATCH 1429/1894] remove duplicate --- .../matrix_search_in_sorted_mat.cpp | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp diff --git a/2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp b/2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp deleted file mode 100644 index a28ef305..00000000 --- a/2D Arrays (Matrix)/matrix_search_in_sorted_mat.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// Search in a rowwise/colwise sorted matrix O(n + m) -#include -using namespace std; -bool search_in_sorted_mat(int Mat[][10], int R, int C, int key){ - int i = 0, flag = 0, j = C-1; - while(j >= 0 && i < R){ - if(Mat[i][j] == key){ - cout << "Found at position " << i << " " << j << endl; - flag = 1; - break; - } - else if(Mat[i][j] < key) - i++; - else if(Mat[i][j] > key){ - j--; - } - } - return flag == 1 ? true : false; -} -int main(){ - int Mat[10][10], R, C; - cin >> R >> C; - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cin >> Mat[i][j]; - } - } - for(int i = 0; i < R; i++){ - for(int j = 0; j < C; j++){ - cout << Mat[i][j] << " "; - } - cout << endl; - } - int key; - cin >> key; - cout << search_in_sorted_mat(Mat, R, C, key); -} \ No newline at end of file From a68a04cdaf4d9e99984ce848a60d8c5c8f8cf41b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:07:48 +0530 Subject: [PATCH 1430/1894] rename file --- .../{Sorted_array_2D.js => searching_in_2d_sorted_array.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{Sorted_array_2D.js => searching_in_2d_sorted_array.js} (100%) diff --git a/2D Arrays (Matrix)/Sorted_array_2D.js b/2D Arrays (Matrix)/searching_in_2d_sorted_array.js similarity index 100% rename from 2D Arrays (Matrix)/Sorted_array_2D.js rename to 2D Arrays (Matrix)/searching_in_2d_sorted_array.js From 98d8f0304950b825afa766f04b4d3c2757d9df23 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:08:09 +0530 Subject: [PATCH 1431/1894] rename file --- 2D Arrays (Matrix)/{2d_binary_search.cpp => binary_search.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{2d_binary_search.cpp => binary_search.cpp} (100%) diff --git a/2D Arrays (Matrix)/2d_binary_search.cpp b/2D Arrays (Matrix)/binary_search.cpp similarity index 100% rename from 2D Arrays (Matrix)/2d_binary_search.cpp rename to 2D Arrays (Matrix)/binary_search.cpp From 3abb5933d8a3a6f9fbc37afc580478a9a3a6b520 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:08:35 +0530 Subject: [PATCH 1432/1894] rename file --- ...ching_in_2d_sorted_array.cpp => searching_in_sorted_array.cpp} | 0 ...ing_in_2d_sorted_array.java => searching_in_sorted_array.java} | 0 ...arching_in_2d_sorted_array.js => searching_in_sorted_array.js} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/{searching_in_2d_sorted_array.cpp => searching_in_sorted_array.cpp} (100%) rename 2D Arrays (Matrix)/{searching_in_2d_sorted_array.java => searching_in_sorted_array.java} (100%) rename 2D Arrays (Matrix)/{searching_in_2d_sorted_array.js => searching_in_sorted_array.js} (100%) diff --git a/2D Arrays (Matrix)/searching_in_2d_sorted_array.cpp b/2D Arrays (Matrix)/searching_in_sorted_array.cpp similarity index 100% rename from 2D Arrays (Matrix)/searching_in_2d_sorted_array.cpp rename to 2D Arrays (Matrix)/searching_in_sorted_array.cpp diff --git a/2D Arrays (Matrix)/searching_in_2d_sorted_array.java b/2D Arrays (Matrix)/searching_in_sorted_array.java similarity index 100% rename from 2D Arrays (Matrix)/searching_in_2d_sorted_array.java rename to 2D Arrays (Matrix)/searching_in_sorted_array.java diff --git a/2D Arrays (Matrix)/searching_in_2d_sorted_array.js b/2D Arrays (Matrix)/searching_in_sorted_array.js similarity index 100% rename from 2D Arrays (Matrix)/searching_in_2d_sorted_array.js rename to 2D Arrays (Matrix)/searching_in_sorted_array.js From abb0a7ee1f1e50aa6d99ad8339bc58d28eda3add Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:11:49 +0530 Subject: [PATCH 1433/1894] add num ways to traverse a graph in go --- .../num_ways_to_traverse_graph.go | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_traverse_graph.go diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go new file mode 100644 index 00000000..410e70a8 --- /dev/null +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -0,0 +1,31 @@ +package main + +func NumberOfWaysToTraverseGraph(width int, height int) int { + // Initialize the numberOfWays matrix with dimensions (height+1) x (width+1) + // The extra "+1" is to account for the boundary cases when traversing the graph + numberOfWays := make([][]int, height+1) + for i := range numberOfWays { + numberOfWays[i] = make([]int, width+1) + } + + // Iterate over the graph cells + for widthIdx := 1; widthIdx < width+1; widthIdx++ { + for heightIdx := 1; heightIdx < height+1; heightIdx++ { + // Check if the current cell is on the top row or the leftmost column + if widthIdx == 1 || heightIdx == 1 { + // If so, there is only one way to reach this cell (moving right or moving down) + numberOfWays[heightIdx][widthIdx] = 1 + } else { + // If the cell is not on the top row or the leftmost column, + // calculate the number of ways to reach this cell based on the + // number of ways to reach the cell above (up) and the cell to the left (left) + waysLeft := numberOfWays[heightIdx][widthIdx-1] + waysUp := numberOfWays[heightIdx-1][widthIdx] + numberOfWays[heightIdx][widthIdx] = waysLeft + waysUp + } + } + } + + // Return the number of ways to reach the bottom-right corner of the graph + return numberOfWays[height][width] +} From f1f383426f1e68f0b0c645ae413026746b4ad9cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:14:43 +0530 Subject: [PATCH 1434/1894] add question --- .../num_ways_to_traverse_graph.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index 410e70a8..147fd87d 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -1,3 +1,24 @@ +/* + + You're given two positive integers representing the width and height of a grid-shaped, rectangular graph. + Write a function that returns the number of ways to reach the bottom right corner of the graph when starting + at the top left corner. Each move you take must either go down or right. In other words, you can never move up + or left in the graph. + + For example, given the graph illustrated below, with width = 2 and height = 3 , there are three ways to + reach the bottom right corner when starting at the top left corner: + _ _ + |_|_| + |_|_| + |_|_| + Down Down Right + Right Down Down + Down Right Down + + Sample Input: Width : 4 height: 3 + Output: 10 + +*/ package main func NumberOfWaysToTraverseGraph(width int, height int) int { From 2ba512edabd804dc670ecd49b0e46d7326996317 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:16:00 +0530 Subject: [PATCH 1435/1894] add explanation --- .../num_ways_to_traverse_graph.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index 147fd87d..aac8a524 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -18,6 +18,39 @@ Sample Input: Width : 4 height: 3 Output: 10 + Explanation: + The code snippet implements the `NumberOfWaysToTraverseGraph` function, which calculates the number of ways to + traverse a 2D graph from the top-left corner to the bottom-right corner. The graph has a given width and height. + + Here's a breakdown of the code: + + 1. The function takes two parameters: `width` and `height`, representing the dimensions of the graph. + + 2. It initializes a 2D slice called `numberOfWays` with dimensions `(height+1) x (width+1)`. The additional "+1" is to + account for the boundary cases when traversing the graph. + + 3. It enters a nested loop to iterate over the graph cells. The outer loop iterates over the width indices (`widthIdx`), + and the inner loop iterates over the height indices (`heightIdx`). + + 4. For each cell, it checks if it is on the top row (`heightIdx == 1`) or the leftmost column (`widthIdx == 1`). If so, it + means that there is only one way to reach that cell, either by moving right or moving down. Therefore, it sets `numberOfWays[heightIdx][widthIdx]` to 1. + + 5. If the cell is not on the top row or the leftmost column, it means that it can be reached by either moving from the + cell above (up) or the cell to the left (left). The number of ways to reach the current cell is the sum of the number of + ways to reach the cell above and the number of ways to reach the cell to the left. This value is stored in + `numberOfWays[heightIdx][widthIdx]`. + + 6. After iterating over all cells, the function returns the value stored in the bottom-right corner of `numberOfWays`, + which represents the total number of ways to traverse the graph. + + The algorithm uses dynamic programming to build the `numberOfWays` matrix iteratively, starting from the top-left corner + and moving towards the bottom-right corner. By calculating the number of ways to reach each cell based on the number of ways to reach its neighboring cells, it avoids redundant calculations and computes the result efficiently. + + The time complexity of the algorithm is O(width * height) since it iterates over all cells of the graph. + + The space complexity is also O(width * height) since it uses the `numberOfWays` matrix to store intermediate results. + + */ package main From a8de3531ca86143459b888571560e3d60f3aecd1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:16:49 +0530 Subject: [PATCH 1436/1894] add combinatorics solution --- .../num_ways_to_traverse_graph.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index aac8a524..5c721b84 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -83,3 +83,30 @@ func NumberOfWaysToTraverseGraph(width int, height int) int { // Return the number of ways to reach the bottom-right corner of the graph return numberOfWays[height][width] } + + +// Combinatorics Solution + +func NumberOfWaysToTraverseGraphCombinatorics(width int, height int) int { + // Calculate the distance to the bottom-right corner of the graph + xDistanceToCorner := width - 1 + yDistanceToCorner := height - 1 + + // Calculate the number of ways to traverse the graph using combinatorics + // by calculating the binomial coefficient of (xDistanceToCorner + yDistanceToCorner) choose xDistanceToCorner + // where (n choose k) = n! / (k! * (n-k)!) + numerator := factorial(xDistanceToCorner + yDistanceToCorner) + denominator := factorial(xDistanceToCorner) * factorial(yDistanceToCorner) + + // Return the result by dividing the numerator by the denominator + return numerator / denominator +} + +func factorial(num int) int { + // Calculate the factorial of a number using an iterative approach + result := 1 + for n := 2; n <= num; n++ { + result *= n + } + return result +} From 02bf658e09f0bc30bdcb63b16adb01bd5b5fbc18 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:17:19 +0530 Subject: [PATCH 1437/1894] add recursive solution --- Dynamic Programming/num_ways_to_traverse_graph.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index 5c721b84..21492580 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -110,3 +110,12 @@ func factorial(num int) int { } return result } + +// Recursive solution + +func NumberOfWaysToTraverseGraphRecursive(width int, height int) int { + if width == 1 || height == 1 { + return 1 + } + return NumberOfWaysToTraverseGraph(width - 1, height) + NumberOfWaysToTraverseGraph(width, height - 1) +} From 124debb737df3ff4b56036b49147a5c3346940ba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:18:33 +0530 Subject: [PATCH 1438/1894] add explanation --- .../num_ways_to_traverse_graph.go | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index 21492580..a5c331f0 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -111,8 +111,47 @@ func factorial(num int) int { return result } -// Recursive solution +/* + Recursive solution + The given solution aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. It uses a recursive approach to break down the problem into smaller subproblems. + + Here's how the solution works: + + 1. The function `NumberOfWaysToTraverseGraph` takes the width and height of the graph as input and returns the number of ways to traverse it. + + 2. The base case of the recursion is when either the width or height is equal to 1. In this case, there is only one way to traverse the graph: either by moving only horizontally or vertically. Therefore, the function returns 1. + + 3. For other cases where the width and height are both greater than 1, the function recursively calls itself with two smaller subproblems: + - One subproblem is created by reducing the width by 1 and keeping the same height. + - The other subproblem is created by keeping the same width and reducing the height by 1. + + 4. The number of ways to traverse the current graph is calculated by summing up the number of ways from the two subproblems. + + 5. The recursion continues until it reaches the base case, where the width or height becomes 1, and eventually returns the total number of ways to traverse the graph. + + While this recursive approach is conceptually simple, it suffers from efficiency issues due to exponential time complexity and redundant + calculations. As the graph size increases, the number of recursive calls grows exponentially, leading to a significant increase in computation time. Additionally, without memoization, the function recalculates the same subproblems multiple times, further reducing efficiency. + + To address these drawbacks, alternative approaches like dynamic programming or memoization can be employed to store and + reuse the results of previously solved subproblems, avoiding redundant calculations and improving efficiency. + + The given solution uses a recursive approach to calculate the number of ways to traverse a graph from the top-left corner + to the bottom-right corner. However, this solution has some drawbacks that make it inefficient for larger inputs: + + 1. Exponential Time Complexity: The recursive function makes multiple recursive calls, each with a smaller width or height. + As a result, the number of function calls grows exponentially with the size of the input. This leads to a high time complexity, making the solution inefficient for larger graphs. The time complexity is O(2^(width+height)), which can quickly become unmanageable. + + 2. Overlapping Subproblems: The recursive function suffers from redundant calculations of the same subproblems. For example, + when calculating the number of ways for a specific width and height, the function may recursively calculate the number of ways for smaller widths and heights multiple times. This leads to redundant work and decreases efficiency. + + 3. Lack of Memoization: The solution does not utilize memoization to store the results of previously solved subproblems. + Without memoization, the recursive function ends up recalculating the same subproblems multiple times, further reducing efficiency. + + Due to these reasons, the given recursive solution is considered inefficient and impractical for larger graph sizes. + It is prone to exponential time complexity and redundant calculations, making it unsuitable for real-world scenarios where efficiency is crucial. Alternative approaches, such as the dynamic programming solution mentioned earlier, can provide better performance by avoiding redundant calculations and improving time complexity. +*/ func NumberOfWaysToTraverseGraphRecursive(width int, height int) int { if width == 1 || height == 1 { return 1 From 07f38ae834a8be5e400b7e694fb3fcac9ab268cd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 23 Jun 2023 23:19:49 +0530 Subject: [PATCH 1439/1894] add combinatorics explanation --- .../num_ways_to_traverse_graph.go | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.go b/Dynamic Programming/num_ways_to_traverse_graph.go index a5c331f0..cefac13d 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.go +++ b/Dynamic Programming/num_ways_to_traverse_graph.go @@ -85,8 +85,37 @@ func NumberOfWaysToTraverseGraph(width int, height int) int { } -// Combinatorics Solution +/* + Combinatorics Solution + + The given code snippet aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. Let's break down the solution and provide a detailed explanation: + + 1. The `NumberOfWaysToTraverseGraph` function takes two parameters: `width` and `height`, representing the dimensions of + the graph. + + 2. The variables `xDistanceToCorner` and `yDistanceToCorner` are calculated by subtracting 1 from the `width` and `height` + respectively. These variables represent the distances from the top-left corner to the bottom-right corner along the x-axis and y-axis. + + 3. The `factorial` function is defined separately to calculate the factorial of a number. It takes a number `num` as input + and uses an iterative approach to calculate the factorial. + 4. In the `NumberOfWaysToTraverseGraph` function, the numerator is calculated as the factorial of the sum of + `xDistanceToCorner` and `yDistanceToCorner`. This represents the total number of possible paths from the top-left + corner to the bottom-right corner. + + 5. The denominator is calculated as the product of the factorials of `xDistanceToCorner` and `yDistanceToCorner`. + This represents the number of ways to arrange the steps along the x-axis and y-axis. + + 6. Finally, the function returns the result by dividing the numerator by the denominator, giving the total number of + ways to traverse the graph. + + The solution relies on the concept of combinatorics, specifically the binomial coefficient, to calculate the number of + ways to traverse the graph. By using factorials, it accounts for all possible paths and eliminates duplicate paths. + This approach provides an efficient solution to the problem. + + O(n + m) time | O(1) space - where n is the width of the graph and m is the height +*/ func NumberOfWaysToTraverseGraphCombinatorics(width int, height int) int { // Calculate the distance to the bottom-right corner of the graph xDistanceToCorner := width - 1 From ee5d27a194e401a0f64460e74f0c71ceb8373f86 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sat, 24 Jun 2023 09:56:11 +0530 Subject: [PATCH 1440/1894] Create Ladder_Pattern.java --- Famous Algorithms/Ladder_Pattern.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Famous Algorithms/Ladder_Pattern.java diff --git a/Famous Algorithms/Ladder_Pattern.java b/Famous Algorithms/Ladder_Pattern.java new file mode 100644 index 00000000..59d71f43 --- /dev/null +++ b/Famous Algorithms/Ladder_Pattern.java @@ -0,0 +1,26 @@ +import java.util.Scanner; +public class Ladder_Pattern +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + System.out.print("Enter the number of steps: " ); + //reads an integer form the user + //n is the number of steps in ladder + int n=sc.nextInt(); + for(int i=1;i<=n*3+2;i++) + { + for(int j=1;j<=5;j++) + { + if(i%3==0) + System.out.print("*"); + else if(j==1||j==5) + System.out.print("*"); + else + System.out.print(" "); + } + //throws cursor to the new line + System.out.println(); + } + } +} From 4c66e7a8ef36508cdc77afaa9feb3f0b1ee5db3b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:37:56 +0530 Subject: [PATCH 1441/1894] add num ways to traverse in a graph --- .../num_ways_to_traverse_graph.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_traverse_graph.py diff --git a/Dynamic Programming/num_ways_to_traverse_graph.py b/Dynamic Programming/num_ways_to_traverse_graph.py new file mode 100644 index 00000000..6a93cc0c --- /dev/null +++ b/Dynamic Programming/num_ways_to_traverse_graph.py @@ -0,0 +1,75 @@ +''' + You're given two positive integers representing the width and height of a grid-shaped, rectangular graph. + Write a function that returns the number of ways to reach the bottom right corner of the graph when starting + at the top left corner. Each move you take must either go down or right. In other words, you can never move up + or left in the graph. + + For example, given the graph illustrated below, with width = 2 and height = 3 , there are three ways to + reach the bottom right corner when starting at the top left corner: + _ _ + |_|_| + |_|_| + |_|_| + Down Down Right + Right Down Down + Down Right Down + + Sample Input: Width : 4 height: 3 + Output: 10 + + Explanation: + The code snippet implements the `NumberOfWaysToTraverseGraph` function, which calculates the number of ways to + traverse a 2D graph from the top-left corner to the bottom-right corner. The graph has a given width and height. + + Here's a breakdown of the code: + + 1. The function takes two parameters: `width` and `height`, representing the dimensions of the graph. + + 2. It initializes a 2D slice called `numberOfWays` with dimensions `(height+1) x (width+1)`. The additional "+1" is to + account for the boundary cases when traversing the graph. + + 3. It enters a nested loop to iterate over the graph cells. The outer loop iterates over the width indices (`widthIdx`), + and the inner loop iterates over the height indices (`heightIdx`). + + 4. For each cell, it checks if it is on the top row (`heightIdx == 1`) or the leftmost column (`widthIdx == 1`). If so, it + means that there is only one way to reach that cell, either by moving right or moving down. Therefore, it sets `numberOfWays[heightIdx][widthIdx]` to 1. + + 5. If the cell is not on the top row or the leftmost column, it means that it can be reached by either moving from the + cell above (up) or the cell to the left (left). The number of ways to reach the current cell is the sum of the number of + ways to reach the cell above and the number of ways to reach the cell to the left. This value is stored in + `numberOfWays[heightIdx][widthIdx]`. + + 6. After iterating over all cells, the function returns the value stored in the bottom-right corner of `numberOfWays`, + which represents the total number of ways to traverse the graph. + + The algorithm uses dynamic programming to build the `numberOfWays` matrix iteratively, starting from the top-left corner + and moving towards the bottom-right corner. By calculating the number of ways to reach each cell based on the number of ways to reach its neighboring cells, it avoids redundant calculations and computes the result efficiently. + + The time complexity of the algorithm is O(width * height) since it iterates over all cells of the graph. + + The space complexity is also O(width * height) since it uses the `numberOfWays` matrix to store intermediate results. + +''' + +def number_of_ways_to_traverse_graph(width, height): + # Initialize the numberOfWays matrix with dimensions (height+1) x (width+1) + # The extra "+1" is to account for the boundary cases when traversing the graph + numberOfWays = [[0] * (width + 1) for _ in range(height + 1)] + + # Iterate over the graph cells + for widthIdx in range(1, width + 1): + for heightIdx in range(1, height + 1): + # Check if the current cell is on the top row or the leftmost column + if widthIdx == 1 or heightIdx == 1: + # If so, there is only one way to reach this cell (moving right or moving down) + numberOfWays[heightIdx][widthIdx] = 1 + else: + # If the cell is not on the top row or the leftmost column, + # calculate the number of ways to reach this cell based on the + # number of ways to reach the cell above (up) and the cell to the left (left) + waysLeft = numberOfWays[heightIdx][widthIdx - 1] + waysUp = numberOfWays[heightIdx - 1][widthIdx] + numberOfWays[heightIdx][widthIdx] = waysLeft + waysUp + + # Return the number of ways to reach the bottom-right corner of the graph + return numberOfWays[height][width] From 66d37141732d30dfc6a793403721139253d6c247 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:39:24 +0530 Subject: [PATCH 1442/1894] add combinatorics version --- .../num_ways_to_traverse_graph.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.py b/Dynamic Programming/num_ways_to_traverse_graph.py index 6a93cc0c..68749ac6 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.py +++ b/Dynamic Programming/num_ways_to_traverse_graph.py @@ -73,3 +73,51 @@ def number_of_ways_to_traverse_graph(width, height): # Return the number of ways to reach the bottom-right corner of the graph return numberOfWays[height][width] + +''' + Combinatorics Solution + + The given code snippet aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. Let's break down the solution and provide a detailed explanation: + + 1. The `NumberOfWaysToTraverseGraph` function takes two parameters: `width` and `height`, representing the dimensions of + the graph. + + 2. The variables `xDistanceToCorner` and `yDistanceToCorner` are calculated by subtracting 1 from the `width` and `height` + respectively. These variables represent the distances from the top-left corner to the bottom-right corner along the x-axis and y-axis. + + 3. The `factorial` function is defined separately to calculate the factorial of a number. It takes a number `num` as input + and uses an iterative approach to calculate the factorial. + + 4. In the `NumberOfWaysToTraverseGraph` function, the numerator is calculated as the factorial of the sum of + `xDistanceToCorner` and `yDistanceToCorner`. This represents the total number of possible paths from the top-left + corner to the bottom-right corner. + + 5. The denominator is calculated as the product of the factorials of `xDistanceToCorner` and `yDistanceToCorner`. + This represents the number of ways to arrange the steps along the x-axis and y-axis. + + 6. Finally, the function returns the result by dividing the numerator by the denominator, giving the total number of + ways to traverse the graph. + + The solution relies on the concept of combinatorics, specifically the binomial coefficient, to calculate the number of + ways to traverse the graph. By using factorials, it accounts for all possible paths and eliminates duplicate paths. + This approach provides an efficient solution to the problem. + + O(n + m) time | O(1) space - where n is the width of the graph and m is the height +''' + +import math + +def number_of_ways_to_traverse_graph_combinatorics(width, height): + # Calculate the distance to the bottom-right corner of the graph + x_distance_to_corner = width - 1 + y_distance_to_corner = height - 1 + + # Calculate the number of ways to traverse the graph using combinatorics + # by calculating the binomial coefficient of (x_distance_to_corner + y_distance_to_corner) choose x_distance_to_corner + # where (n choose k) = n! / (k! * (n-k)!) + numerator = math.factorial(x_distance_to_corner + y_distance_to_corner) + denominator = math.factorial(x_distance_to_corner) * math.factorial(y_distance_to_corner) + + # Return the result by dividing the numerator by the denominator + return numerator // denominator From 01f3b3e505264fe98b4550835ab6490eab553a63 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:40:15 +0530 Subject: [PATCH 1443/1894] add recursive version --- .../num_ways_to_traverse_graph.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.py b/Dynamic Programming/num_ways_to_traverse_graph.py index 68749ac6..f7933554 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.py +++ b/Dynamic Programming/num_ways_to_traverse_graph.py @@ -121,3 +121,48 @@ def number_of_ways_to_traverse_graph_combinatorics(width, height): # Return the result by dividing the numerator by the denominator return numerator // denominator + +''' + Recursive solution + The given solution aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. It uses a recursive approach to break down the problem into smaller subproblems. + + Here's how the solution works: + + 1. The function `NumberOfWaysToTraverseGraph` takes the width and height of the graph as input and returns the number of ways to traverse it. + + 2. The base case of the recursion is when either the width or height is equal to 1. In this case, there is only one way to traverse the graph: either by moving only horizontally or vertically. Therefore, the function returns 1. + + 3. For other cases where the width and height are both greater than 1, the function recursively calls itself with two smaller subproblems: + - One subproblem is created by reducing the width by 1 and keeping the same height. + - The other subproblem is created by keeping the same width and reducing the height by 1. + + 4. The number of ways to traverse the current graph is calculated by summing up the number of ways from the two subproblems. + + 5. The recursion continues until it reaches the base case, where the width or height becomes 1, and eventually returns the total number of ways to traverse the graph. + + While this recursive approach is conceptually simple, it suffers from efficiency issues due to exponential time complexity and redundant + calculations. As the graph size increases, the number of recursive calls grows exponentially, leading to a significant increase in computation time. Additionally, without memoization, the function recalculates the same subproblems multiple times, further reducing efficiency. + + To address these drawbacks, alternative approaches like dynamic programming or memoization can be employed to store and + reuse the results of previously solved subproblems, avoiding redundant calculations and improving efficiency. + + The given solution uses a recursive approach to calculate the number of ways to traverse a graph from the top-left corner + to the bottom-right corner. However, this solution has some drawbacks that make it inefficient for larger inputs: + + 1. Exponential Time Complexity: The recursive function makes multiple recursive calls, each with a smaller width or height. + As a result, the number of function calls grows exponentially with the size of the input. This leads to a high time complexity, making the solution inefficient for larger graphs. The time complexity is O(2^(width+height)), which can quickly become unmanageable. + + 2. Overlapping Subproblems: The recursive function suffers from redundant calculations of the same subproblems. For example, + when calculating the number of ways for a specific width and height, the function may recursively calculate the number of ways for smaller widths and heights multiple times. This leads to redundant work and decreases efficiency. + + 3. Lack of Memoization: The solution does not utilize memoization to store the results of previously solved subproblems. + Without memoization, the recursive function ends up recalculating the same subproblems multiple times, further reducing efficiency. + + Due to these reasons, the given recursive solution is considered inefficient and impractical for larger graph sizes. + It is prone to exponential time complexity and redundant calculations, making it unsuitable for real-world scenarios where efficiency is crucial. Alternative approaches, such as the dynamic programming solution mentioned earlier, can provide better performance by avoiding redundant calculations and improving time complexity. +''' +def number_of_ways_to_traverse_graph_recursive(width, height): + if width == 1 or height == 1: + return 1 + return number_of_ways_to_traverse_graph_recursive(width - 1, height) + number_of_ways_to_traverse_graph_recursive(width, height - 1) From 78cd8b069f843e56bf383f90af130f38f77bc0f4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:44:51 +0530 Subject: [PATCH 1444/1894] add num ways to traverse a graph in javascript --- .../num_ways_to_traverse_graph.js | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_traverse_graph.js diff --git a/Dynamic Programming/num_ways_to_traverse_graph.js b/Dynamic Programming/num_ways_to_traverse_graph.js new file mode 100644 index 00000000..f7f3f060 --- /dev/null +++ b/Dynamic Programming/num_ways_to_traverse_graph.js @@ -0,0 +1,72 @@ +/* + + You're given two positive integers representing the width and height of a grid-shaped, rectangular graph. + Write a function that returns the number of ways to reach the bottom right corner of the graph when starting + at the top left corner. Each move you take must either go down or right. In other words, you can never move up + or left in the graph. + + For example, given the graph illustrated below, with width = 2 and height = 3 , there are three ways to + reach the bottom right corner when starting at the top left corner: + _ _ + |_|_| + |_|_| + |_|_| + Down Down Right + Right Down Down + Down Right Down + + Sample Input: Width : 4 height: 3 + Output: 10 + + Explanation: + The code snippet implements the `NumberOfWaysToTraverseGraph` function, which calculates the number of ways to + traverse a 2D graph from the top-left corner to the bottom-right corner. The graph has a given width and height. + + Here's a breakdown of the code: + + 1. The function takes two parameters: `width` and `height`, representing the dimensions of the graph. + + 2. It initializes a 2D slice called `numberOfWays` with dimensions `(height+1) x (width+1)`. The additional "+1" is to + account for the boundary cases when traversing the graph. + + 3. It enters a nested loop to iterate over the graph cells. The outer loop iterates over the width indices (`widthIdx`), + and the inner loop iterates over the height indices (`heightIdx`). + + 4. For each cell, it checks if it is on the top row (`heightIdx == 1`) or the leftmost column (`widthIdx == 1`). If so, it + means that there is only one way to reach that cell, either by moving right or moving down. Therefore, it sets `numberOfWays[heightIdx][widthIdx]` to 1. + + 5. If the cell is not on the top row or the leftmost column, it means that it can be reached by either moving from the + cell above (up) or the cell to the left (left). The number of ways to reach the current cell is the sum of the number of + ways to reach the cell above and the number of ways to reach the cell to the left. This value is stored in + `numberOfWays[heightIdx][widthIdx]`. + + 6. After iterating over all cells, the function returns the value stored in the bottom-right corner of `numberOfWays`, + which represents the total number of ways to traverse the graph. + + The algorithm uses dynamic programming to build the `numberOfWays` matrix iteratively, starting from the top-left corner + and moving towards the bottom-right corner. By calculating the number of ways to reach each cell based on the number of ways to reach its neighboring cells, it avoids redundant calculations and computes the result efficiently. + + The time complexity of the algorithm is O(width * height) since it iterates over all cells of the graph. + + The space complexity is also O(width * height) since it uses the `numberOfWays` matrix to store intermediate results. + + +*/ +function numberOfWaysToTraverseGraph(width, height) { + // Create a 2D array to store the number of ways to reach each cell + const numberOfWays = new Array(height) + .fill(1) + .map(() => new Array(width).fill(1)); + + // Iterate through the cells from top to bottom and left to right + for (let i = 1; i < height; i++) { + for (let j = 1; j < width; j++) { + // Calculate the number of ways to reach the current cell + // by summing the number of ways from the cell above and the cell to the left + numberOfWays[i][j] = numberOfWays[i - 1][j] + numberOfWays[i][j - 1]; + } + } + + // Return the number of ways to reach the bottom-right corner of the graph + return numberOfWays[height - 1][width - 1]; +} From 4f6b106ae79de8a508908784ed5a694f693d1272 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:45:40 +0530 Subject: [PATCH 1445/1894] add combinatorics solution --- .../num_ways_to_traverse_graph.js | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.js b/Dynamic Programming/num_ways_to_traverse_graph.js index f7f3f060..6fa9604d 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.js +++ b/Dynamic Programming/num_ways_to_traverse_graph.js @@ -70,3 +70,59 @@ function numberOfWaysToTraverseGraph(width, height) { // Return the number of ways to reach the bottom-right corner of the graph return numberOfWays[height - 1][width - 1]; } + +/* + Combinatorics Solution + + The given code snippet aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. Let's break down the solution and provide a detailed explanation: + + 1. The `NumberOfWaysToTraverseGraph` function takes two parameters: `width` and `height`, representing the dimensions of + the graph. + + 2. The variables `xDistanceToCorner` and `yDistanceToCorner` are calculated by subtracting 1 from the `width` and `height` + respectively. These variables represent the distances from the top-left corner to the bottom-right corner along the x-axis and y-axis. + + 3. The `factorial` function is defined separately to calculate the factorial of a number. It takes a number `num` as input + and uses an iterative approach to calculate the factorial. + + 4. In the `NumberOfWaysToTraverseGraph` function, the numerator is calculated as the factorial of the sum of + `xDistanceToCorner` and `yDistanceToCorner`. This represents the total number of possible paths from the top-left + corner to the bottom-right corner. + + 5. The denominator is calculated as the product of the factorials of `xDistanceToCorner` and `yDistanceToCorner`. + This represents the number of ways to arrange the steps along the x-axis and y-axis. + + 6. Finally, the function returns the result by dividing the numerator by the denominator, giving the total number of + ways to traverse the graph. + + The solution relies on the concept of combinatorics, specifically the binomial coefficient, to calculate the number of + ways to traverse the graph. By using factorials, it accounts for all possible paths and eliminates duplicate paths. + This approach provides an efficient solution to the problem. + + O(n + m) time | O(1) space - where n is the width of the graph and m is the height +*/ + +function numberOfWaysToTraverseGraphCombinatorics(width, height) { + // Calculate the distances to the bottom-right corner of the graph + const xDistanceToCorner = width - 1; + const yDistanceToCorner = height - 1; + + // Calculate the numerator and denominator for the binomial coefficient + const numerator = factorial(xDistanceToCorner + yDistanceToCorner); + const denominator = + factorial(xDistanceToCorner) * factorial(yDistanceToCorner); + + // Return the result by dividing the numerator by the denominator + return numerator / denominator; +} + +function factorial(n) { + // Base case: factorial of 0 or 1 is 1 + if (n <= 1) { + return 1; + } + + // Recursive case: compute factorial by multiplying n with factorial(n-1) + return n * factorial(n - 1); +} From e25c8884d26e348e6c3d6aba733fd68f2058e621 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:45:58 +0530 Subject: [PATCH 1446/1894] add recursive solution --- .../num_ways_to_traverse_graph.js | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.js b/Dynamic Programming/num_ways_to_traverse_graph.js index 6fa9604d..38316f93 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.js +++ b/Dynamic Programming/num_ways_to_traverse_graph.js @@ -126,3 +126,57 @@ function factorial(n) { // Recursive case: compute factorial by multiplying n with factorial(n-1) return n * factorial(n - 1); } + +/* + Recursive solution + The given solution aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. It uses a recursive approach to break down the problem into smaller subproblems. + + Here's how the solution works: + + 1. The function `NumberOfWaysToTraverseGraph` takes the width and height of the graph as input and returns the number of ways to traverse it. + + 2. The base case of the recursion is when either the width or height is equal to 1. In this case, there is only one way to traverse the graph: either by moving only horizontally or vertically. Therefore, the function returns 1. + + 3. For other cases where the width and height are both greater than 1, the function recursively calls itself with two smaller subproblems: + - One subproblem is created by reducing the width by 1 and keeping the same height. + - The other subproblem is created by keeping the same width and reducing the height by 1. + + 4. The number of ways to traverse the current graph is calculated by summing up the number of ways from the two subproblems. + + 5. The recursion continues until it reaches the base case, where the width or height becomes 1, and eventually returns the total number of ways to traverse the graph. + + While this recursive approach is conceptually simple, it suffers from efficiency issues due to exponential time complexity and redundant + calculations. As the graph size increases, the number of recursive calls grows exponentially, leading to a significant increase in computation time. Additionally, without memoization, the function recalculates the same subproblems multiple times, further reducing efficiency. + + To address these drawbacks, alternative approaches like dynamic programming or memoization can be employed to store and + reuse the results of previously solved subproblems, avoiding redundant calculations and improving efficiency. + + The given solution uses a recursive approach to calculate the number of ways to traverse a graph from the top-left corner + to the bottom-right corner. However, this solution has some drawbacks that make it inefficient for larger inputs: + + 1. Exponential Time Complexity: The recursive function makes multiple recursive calls, each with a smaller width or height. + As a result, the number of function calls grows exponentially with the size of the input. This leads to a high time complexity, making the solution inefficient for larger graphs. The time complexity is O(2^(width+height)), which can quickly become unmanageable. + + 2. Overlapping Subproblems: The recursive function suffers from redundant calculations of the same subproblems. For example, + when calculating the number of ways for a specific width and height, the function may recursively calculate the number of ways for smaller widths and heights multiple times. This leads to redundant work and decreases efficiency. + + 3. Lack of Memoization: The solution does not utilize memoization to store the results of previously solved subproblems. + Without memoization, the recursive function ends up recalculating the same subproblems multiple times, further reducing efficiency. + + Due to these reasons, the given recursive solution is considered inefficient and impractical for larger graph sizes. + It is prone to exponential time complexity and redundant calculations, making it unsuitable for real-world scenarios where efficiency is crucial. Alternative approaches, such as the dynamic programming solution mentioned earlier, can provide better performance by avoiding redundant calculations and improving time complexity. +*/ + +function numberOfWaysToTraverseGraphRecursive(width, height) { + // Base case: when the width or height is 1, there is only one way to reach the destination + if (width === 1 || height === 1) { + return 1; + } + + // Recursive case: sum the number of ways from the cell above and the cell to the left + return ( + numberOfWaysToTraverseGraphRecursive(width - 1, height) + + numberOfWaysToTraverseGraphRecursive(width, height - 1) + ); +} From ceb3c7ec46994105b962060f0121aeecd3ce5b6f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:50:01 +0530 Subject: [PATCH 1447/1894] add num ways to traverse a graph in c++ --- .../num_ways_to_traverse_graph.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Dynamic Programming/num_ways_to_traverse_graph.cpp diff --git a/Dynamic Programming/num_ways_to_traverse_graph.cpp b/Dynamic Programming/num_ways_to_traverse_graph.cpp new file mode 100644 index 00000000..5650f417 --- /dev/null +++ b/Dynamic Programming/num_ways_to_traverse_graph.cpp @@ -0,0 +1,73 @@ +/* + + You're given two positive integers representing the width and height of a grid-shaped, rectangular graph. + Write a function that returns the number of ways to reach the bottom right corner of the graph when starting + at the top left corner. Each move you take must either go down or right. In other words, you can never move up + or left in the graph. + + For example, given the graph illustrated below, with width = 2 and height = 3 , there are three ways to + reach the bottom right corner when starting at the top left corner: + _ _ + |_|_| + |_|_| + |_|_| + Down Down Right + Right Down Down + Down Right Down + + Sample Input: Width : 4 height: 3 + Output: 10 + + Explanation: + The code snippet implements the `NumberOfWaysToTraverseGraph` function, which calculates the number of ways to + traverse a 2D graph from the top-left corner to the bottom-right corner. The graph has a given width and height. + + Here's a breakdown of the code: + + 1. The function takes two parameters: `width` and `height`, representing the dimensions of the graph. + + 2. It initializes a 2D slice called `numberOfWays` with dimensions `(height+1) x (width+1)`. The additional "+1" is to + account for the boundary cases when traversing the graph. + + 3. It enters a nested loop to iterate over the graph cells. The outer loop iterates over the width indices (`widthIdx`), + and the inner loop iterates over the height indices (`heightIdx`). + + 4. For each cell, it checks if it is on the top row (`heightIdx == 1`) or the leftmost column (`widthIdx == 1`). If so, it + means that there is only one way to reach that cell, either by moving right or moving down. Therefore, it sets `numberOfWays[heightIdx][widthIdx]` to 1. + + 5. If the cell is not on the top row or the leftmost column, it means that it can be reached by either moving from the + cell above (up) or the cell to the left (left). The number of ways to reach the current cell is the sum of the number of + ways to reach the cell above and the number of ways to reach the cell to the left. This value is stored in + `numberOfWays[heightIdx][widthIdx]`. + + 6. After iterating over all cells, the function returns the value stored in the bottom-right corner of `numberOfWays`, + which represents the total number of ways to traverse the graph. + + The algorithm uses dynamic programming to build the `numberOfWays` matrix iteratively, starting from the top-left corner + and moving towards the bottom-right corner. By calculating the number of ways to reach each cell based on the number of ways to reach its neighboring cells, it avoids redundant calculations and computes the result efficiently. + + The time complexity of the algorithm is O(width * height) since it iterates over all cells of the graph. + + The space complexity is also O(width * height) since it uses the `numberOfWays` matrix to store intermediate results. + + +*/ + +int numberOfWaysToTraverseGraph(int width, int height) { + // Create a 2D vector to store the number of ways to reach each cell + vector> numberOfWays(height, vector(width, 1)); + + // Iterate through the cells from top to bottom and left to right + for (int i = 1; i < height; i++) { + for (int j = 1; j < width; j++) { + // Calculate the number of ways to reach the current cell + // by summing the number of ways from the cell above and the cell to the left + numberOfWays[i][j] = numberOfWays[i - 1][j] + numberOfWays[i][j - 1]; + } + } + + // Return the number of ways to reach the bottom-right corner of the graph + return numberOfWays[height - 1][width - 1]; +} + + From c42e0ede5a104af28e731abed842365ba7ef8fa0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:50:19 +0530 Subject: [PATCH 1448/1894] add combinatorics version --- .../num_ways_to_traverse_graph.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.cpp b/Dynamic Programming/num_ways_to_traverse_graph.cpp index 5650f417..c7293aa5 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.cpp +++ b/Dynamic Programming/num_ways_to_traverse_graph.cpp @@ -71,3 +71,58 @@ int numberOfWaysToTraverseGraph(int width, int height) { } +/* + Combinatorics Solution + + The given code snippet aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. Let's break down the solution and provide a detailed explanation: + + 1. The `NumberOfWaysToTraverseGraph` function takes two parameters: `width` and `height`, representing the dimensions of + the graph. + + 2. The variables `xDistanceToCorner` and `yDistanceToCorner` are calculated by subtracting 1 from the `width` and `height` + respectively. These variables represent the distances from the top-left corner to the bottom-right corner along the x-axis and y-axis. + + 3. The `factorial` function is defined separately to calculate the factorial of a number. It takes a number `num` as input + and uses an iterative approach to calculate the factorial. + + 4. In the `NumberOfWaysToTraverseGraph` function, the numerator is calculated as the factorial of the sum of + `xDistanceToCorner` and `yDistanceToCorner`. This represents the total number of possible paths from the top-left + corner to the bottom-right corner. + + 5. The denominator is calculated as the product of the factorials of `xDistanceToCorner` and `yDistanceToCorner`. + This represents the number of ways to arrange the steps along the x-axis and y-axis. + + 6. Finally, the function returns the result by dividing the numerator by the denominator, giving the total number of + ways to traverse the graph. + + The solution relies on the concept of combinatorics, specifically the binomial coefficient, to calculate the number of + ways to traverse the graph. By using factorials, it accounts for all possible paths and eliminates duplicate paths. + This approach provides an efficient solution to the problem. + + O(n + m) time | O(1) space - where n is the width of the graph and m is the height +*/ + +int numberOfWaysToTraverseGraphCombinatorics(int width, int height) { + // Calculate the distances to the bottom-right corner of the graph + int xDistanceToCorner = width - 1; + int yDistanceToCorner = height - 1; + + // Calculate the numerator and denominator for the binomial coefficient + int numerator = factorial(xDistanceToCorner + yDistanceToCorner); + int denominator = factorial(xDistanceToCorner) * factorial(yDistanceToCorner); + + // Return the result by dividing the numerator by the denominator + return numerator / denominator; +} + +int factorial(int n) { + // Base case: factorial of 0 or 1 is 1 + if (n <= 1) { + return 1; + } + + // Recursive case: compute factorial by multiplying n with factorial(n-1) + return n * factorial(n - 1); +} + From 1989ee79461eacd885f8c6a1ad434e4e4966a653 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 24 Jun 2023 22:50:37 +0530 Subject: [PATCH 1449/1894] add recursive version --- .../num_ways_to_traverse_graph.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Dynamic Programming/num_ways_to_traverse_graph.cpp b/Dynamic Programming/num_ways_to_traverse_graph.cpp index c7293aa5..ed5ce093 100644 --- a/Dynamic Programming/num_ways_to_traverse_graph.cpp +++ b/Dynamic Programming/num_ways_to_traverse_graph.cpp @@ -126,3 +126,54 @@ int factorial(int n) { return n * factorial(n - 1); } + +/* + Recursive solution + The given solution aims to calculate the number of ways to traverse a graph from the top-left corner to the bottom-right + corner. It uses a recursive approach to break down the problem into smaller subproblems. + + Here's how the solution works: + + 1. The function `NumberOfWaysToTraverseGraph` takes the width and height of the graph as input and returns the number of ways to traverse it. + + 2. The base case of the recursion is when either the width or height is equal to 1. In this case, there is only one way to traverse the graph: either by moving only horizontally or vertically. Therefore, the function returns 1. + + 3. For other cases where the width and height are both greater than 1, the function recursively calls itself with two smaller subproblems: + - One subproblem is created by reducing the width by 1 and keeping the same height. + - The other subproblem is created by keeping the same width and reducing the height by 1. + + 4. The number of ways to traverse the current graph is calculated by summing up the number of ways from the two subproblems. + + 5. The recursion continues until it reaches the base case, where the width or height becomes 1, and eventually returns the total number of ways to traverse the graph. + + While this recursive approach is conceptually simple, it suffers from efficiency issues due to exponential time complexity and redundant + calculations. As the graph size increases, the number of recursive calls grows exponentially, leading to a significant increase in computation time. Additionally, without memoization, the function recalculates the same subproblems multiple times, further reducing efficiency. + + To address these drawbacks, alternative approaches like dynamic programming or memoization can be employed to store and + reuse the results of previously solved subproblems, avoiding redundant calculations and improving efficiency. + + The given solution uses a recursive approach to calculate the number of ways to traverse a graph from the top-left corner + to the bottom-right corner. However, this solution has some drawbacks that make it inefficient for larger inputs: + + 1. Exponential Time Complexity: The recursive function makes multiple recursive calls, each with a smaller width or height. + As a result, the number of function calls grows exponentially with the size of the input. This leads to a high time complexity, making the solution inefficient for larger graphs. The time complexity is O(2^(width+height)), which can quickly become unmanageable. + + 2. Overlapping Subproblems: The recursive function suffers from redundant calculations of the same subproblems. For example, + when calculating the number of ways for a specific width and height, the function may recursively calculate the number of ways for smaller widths and heights multiple times. This leads to redundant work and decreases efficiency. + + 3. Lack of Memoization: The solution does not utilize memoization to store the results of previously solved subproblems. + Without memoization, the recursive function ends up recalculating the same subproblems multiple times, further reducing efficiency. + + Due to these reasons, the given recursive solution is considered inefficient and impractical for larger graph sizes. + It is prone to exponential time complexity and redundant calculations, making it unsuitable for real-world scenarios where efficiency is crucial. Alternative approaches, such as the dynamic programming solution mentioned earlier, can provide better performance by avoiding redundant calculations and improving time complexity. +*/ + +int numberOfWaysToTraverseGraphRecursive(int width, int height) { + // Base case: when the width or height is 1, there is only one way to reach the destination + if (width == 1 || height == 1) { + return 1; + } + + // Recursive case: sum the number of ways from the cell above and the cell to the left + return numberOfWaysToTraverseGraphRecursive(width - 1, height) + numberOfWaysToTraverseGraphRecursive(width, height - 1); +} From 7b6495d547a7a6c0996288fab9e75462f2a33682 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 24 Jun 2023 22:52:35 +0530 Subject: [PATCH 1450/1894] Update longest_string.cpp --- Strings/longest_string.cpp | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/Strings/longest_string.cpp b/Strings/longest_string.cpp index 31f94717..74710716 100644 --- a/Strings/longest_string.cpp +++ b/Strings/longest_string.cpp @@ -1,24 +1,39 @@ +/*The code implements the dynamic programming approach to find the longest palindrome substring in a given string. It uses a two-dimensional table dp to store the results of subproblems, where dp[i][j] represents whether the substring from index i to index j is a palindrome. + +The algorithm first checks for all substrings of length 1 and marks them as palindromes. Then it checks for substrings of length 2 and updates the start and maxLen variables if a palindrome of length 2 is found. + +After that, it checks for substrings of length greater than 2 by iterating over all possible lengths and positions. If a palindrome is found at a particular position, it updates the start and maxLen variables accordingly. + +*/ + #include +#include class Solution { public: - string longestPalindrome(string s) { + /** + * Finds the longest palindrome substring within a given string. + * + * @param s The input string. + * @return The longest palindrome substring. + */ + std::string longestPalindrome(std::string s) { int n = s.length(); if (n < 2) { return s; } - + int start = 0; // start index of the longest palindrome int maxLen = 1; // length of the longest palindrome - + // Initialize a table to store the results of subproblems - vector> dp(n, vector(n, false)); - + std::vector> dp(n, std::vector(n, false)); + // All substrings of length 1 are palindromes for (int i = 0; i < n; i++) { dp[i][i] = true; } - + // Check for substrings of length 2 for (int i = 0; i < n - 1; i++) { if (s[i] == s[i + 1]) { @@ -27,7 +42,7 @@ class Solution { maxLen = 2; } } - + // Check for substrings of length greater than 2 for (int len = 3; len <= n; len++) { for (int i = 0; i < n - len + 1; i++) { @@ -39,8 +54,9 @@ class Solution { } } } - + // Return the longest palindrome substring return s.substr(start, maxLen); } }; + From 9e8b38de81e5878f783b35229bbb041e7d071528 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 24 Jun 2023 22:59:48 +0530 Subject: [PATCH 1451/1894] Create 2D_sorted_array closes issue number #271 --- 2D Arrays (Matrix)/2D_sorted_array | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 2D Arrays (Matrix)/2D_sorted_array diff --git a/2D Arrays (Matrix)/2D_sorted_array b/2D Arrays (Matrix)/2D_sorted_array new file mode 100644 index 00000000..297b6a09 --- /dev/null +++ b/2D Arrays (Matrix)/2D_sorted_array @@ -0,0 +1,29 @@ +#include + +class Solution { +public: + bool searchMatrix(std::vector>& matrix, int target) { + int m = matrix.size(); + int n = matrix[0].size(); + + int left = 0; + int right = m * n - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + int row = mid / n; + int col = mid % n; + int num = matrix[row][col]; + + if (num == target) { + return true; + } else if (num < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return false; + } +}; From 1bba4014d802a31a55f4131bd211267e3985092d Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 24 Jun 2023 23:01:39 +0530 Subject: [PATCH 1452/1894] Update and rename 2D_sorted_array to 2D_sorted_array.java --- 2D Arrays (Matrix)/2D_sorted_array | 29 -------------- 2D Arrays (Matrix)/2D_sorted_array.java | 53 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 29 deletions(-) delete mode 100644 2D Arrays (Matrix)/2D_sorted_array create mode 100644 2D Arrays (Matrix)/2D_sorted_array.java diff --git a/2D Arrays (Matrix)/2D_sorted_array b/2D Arrays (Matrix)/2D_sorted_array deleted file mode 100644 index 297b6a09..00000000 --- a/2D Arrays (Matrix)/2D_sorted_array +++ /dev/null @@ -1,29 +0,0 @@ -#include - -class Solution { -public: - bool searchMatrix(std::vector>& matrix, int target) { - int m = matrix.size(); - int n = matrix[0].size(); - - int left = 0; - int right = m * n - 1; - - while (left <= right) { - int mid = left + (right - left) / 2; - int row = mid / n; - int col = mid % n; - int num = matrix[row][col]; - - if (num == target) { - return true; - } else if (num < target) { - left = mid + 1; - } else { - right = mid - 1; - } - } - - return false; - } -}; diff --git a/2D Arrays (Matrix)/2D_sorted_array.java b/2D Arrays (Matrix)/2D_sorted_array.java new file mode 100644 index 00000000..bffdfeac --- /dev/null +++ b/2D Arrays (Matrix)/2D_sorted_array.java @@ -0,0 +1,53 @@ +/* + +The algorithm starts by initializing two pointers, left and right, which represent the start and end indices of the search range. The range spans from the first element (matrix[0][0]) to the last element (matrix[m - 1][n - 1]) in the matrix, where m is the number of rows and n is the number of columns. + +The function then enters a while loop that continues as long as left is less than or equal to right. In each iteration, it calculates the middle index mid using the formula mid = left + (right - left) / 2. This ensures that mid is always rounded down to the lower integer if the range is odd. + +The middle index mid is then mapped to its corresponding row and column indices in the matrix using the formulas row = mid / n and col = mid % n. + +The number num at the middle position (matrix[row][col]) is retrieved and compared with the target. If num is equal to the target, the function returns true as the target is found in the matrix. If num is less than the target, the left pointer is updated to mid + 1 to search in the upper half of the range. If num is greater than the target, the right pointer is updated to mid - 1 to search in the lower half of the range. + +If the while loop terminates without finding the target, the function returns false. + +The algorithm achieves a time complexity of O(log(m * n)), where m is the number of rows and n is the number of columns in the matrix, as it uses binary search to efficiently search within the given range. + +*/ + + + +#include +class Solution { +public: + /** + * Searches for a target integer in a matrix with specific properties. + * + * @param matrix The input matrix. + * @param target The target integer to search for. + * @return True if the target is found in the matrix, false otherwise. + */ + bool searchMatrix(std::vector>& matrix, int target) { + int m = matrix.size(); + int n = matrix[0].size(); + + int left = 0; // Start index of the search range + int right = m * n - 1; // End index of the search range + + while (left <= right) { + int mid = left + (right - left) / 2; // Calculate middle index + int row = mid / n; // Calculate row index + int col = mid % n; // Calculate column index + int num = matrix[row][col]; // Get the number at the middle position + + if (num == target) { + return true; // Target found in the matrix + } else if (num < target) { + left = mid + 1; // Search in the upper half of the range + } else { + right = mid - 1; // Search in the lower half of the range + } + } + + return false; // Target not found in the matrix + } +}; From cd883d03fb596fcd3333a6ee42410cada862ad3b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:42:50 +0530 Subject: [PATCH 1453/1894] remove duplicate --- Dynamic Programming/unique_paths.cpp | 38 ---------------------------- 1 file changed, 38 deletions(-) delete mode 100644 Dynamic Programming/unique_paths.cpp diff --git a/Dynamic Programming/unique_paths.cpp b/Dynamic Programming/unique_paths.cpp deleted file mode 100644 index b5c63319..00000000 --- a/Dynamic Programming/unique_paths.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. - - Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. - - The test cases are generated so that the answer will be less than or equal to 2 * 109. - - Example 1: - Input: m = 3, n = 7 - Output: 28 - - Example 2: - Input: m = 3, n = 2 - Output: 3 - Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: - 1. Right -> Down -> Down - 2. Down -> Down -> Right - 3. Down -> Right -> Down -*/ - -class Solution { -public: - int uniquePaths(int m, int n) { - int mat[m][n]; - for(int i = 0; i < m; i++){ - mat[i][0] = 1; - } - for(int i = 0; i < n; i++){ - mat[0][i] = 1; - } - for(int i = 1; i < m; i++){ - for(int j = 1; j < n; j++){ - mat[i][j] = mat[i - 1][j] + mat[i][j - 1]; - } - } - return mat[m-1][n-1]; - } -}; \ No newline at end of file From 4207cf67cac4c4271df725c9c8c9f7bc33abaa43 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:43:43 +0530 Subject: [PATCH 1454/1894] merge memoized and dp --- ... => min_steps_to_reduce_a_number_to_one.cpp} | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) rename Dynamic Programming/{min_steps_to_reduce_a_number_to_one_dp.cpp => min_steps_to_reduce_a_number_to_one.cpp} (69%) diff --git a/Dynamic Programming/min_steps_to_reduce_a_number_to_one_dp.cpp b/Dynamic Programming/min_steps_to_reduce_a_number_to_one.cpp similarity index 69% rename from Dynamic Programming/min_steps_to_reduce_a_number_to_one_dp.cpp rename to Dynamic Programming/min_steps_to_reduce_a_number_to_one.cpp index 653ccd63..bb2f2ca3 100644 --- a/Dynamic Programming/min_steps_to_reduce_a_number_to_one_dp.cpp +++ b/Dynamic Programming/min_steps_to_reduce_a_number_to_one.cpp @@ -33,6 +33,23 @@ int find_min_steps(int number){ return dp[number]; } + +int memoized[10004]; +int find_min_steps(int number){ + if(number == 1) + return 0; + int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; + if(memoized[number] != -1) return memoized[number]; + r1 = 1 + find_min_steps(number - 1); + if(number % 2 == 0) + r2 = 1 + find_min_steps(number / 2); + if(number % 3 == 0) + r3 = 1 + find_min_steps(number / 3); + memoized[number] = min(r1, min(r2, r3)); + return memoized[number]; +} + + int main(){ int number; cin >> number; From ac281fee258ddd1446c2adb551d0be71b7887e0c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:43:57 +0530 Subject: [PATCH 1455/1894] remove memoized file --- ...eps_to_reduce_a_number_to_one_memoized.cpp | 39 ------------------- 1 file changed, 39 deletions(-) delete mode 100644 Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp diff --git a/Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp b/Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp deleted file mode 100644 index cc80fe1b..00000000 --- a/Dynamic Programming/min_steps_to_reduce_a_number_to_one_memoized.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// Minimum steps to reduce a number to one conditions are as follows -// a) subtract 1 [one operation] -// b) divide by 2 [one operation] -// c) divide by 3 [one operation] -// Recursive + Memoized solution -// Program Author : Abhisek Kumar Gupta -/* - Input : 10 - Output : 3 - Explanation : 10 reduced to 9 reduced to 3 reduced to 1 [total 3 operations] - Input : 15 - Output : 4 -*/ -#include -using namespace std; -int memoized[10004]; -int find_min_steps(int number){ - if(number == 1) - return 0; - int r1 = INT_MAX, r2 = INT_MAX, r3 = INT_MAX; - if(memoized[number] != -1) return memoized[number]; - r1 = 1 + find_min_steps(number - 1); - if(number % 2 == 0) - r2 = 1 + find_min_steps(number / 2); - if(number % 3 == 0) - r3 = 1 + find_min_steps(number / 3); - memoized[number] = min(r1, min(r2, r3)); - return memoized[number]; -} - - -int main(){ - int number; - cin >> number; - memset(memoized, -1, sizeof(memoized)); - int result = find_min_steps(number); - cout << result; - return 0; -} From dde29063813efda3131af9375393a260ad4f0cc9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:44:19 +0530 Subject: [PATCH 1456/1894] rename file --- ...g_pallindrome.cpp => min_steps_to_make_string_pallindrome.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{minimum_insertion_steps_to_make_string_pallindrome.cpp => min_steps_to_make_string_pallindrome.cpp} (100%) diff --git a/Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp b/Dynamic Programming/min_steps_to_make_string_pallindrome.cpp similarity index 100% rename from Dynamic Programming/minimum_insertion_steps_to_make_string_pallindrome.cpp rename to Dynamic Programming/min_steps_to_make_string_pallindrome.cpp From 8b2427aa5fed77ac4843f20ce7e9f6202af44fe4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:45:29 +0530 Subject: [PATCH 1457/1894] rename file --- ...est_Rectangle_In_Binary_Matrix.java => largest_rectangle.java} | 0 ...Largest_Rectangle_In_Binary_Matrix.py => largest_rectangle.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{Largest_Rectangle_In_Binary_Matrix.java => largest_rectangle.java} (100%) rename Dynamic Programming/{Largest_Rectangle_In_Binary_Matrix.py => largest_rectangle.py} (100%) diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java b/Dynamic Programming/largest_rectangle.java similarity index 100% rename from Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.java rename to Dynamic Programming/largest_rectangle.java diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py b/Dynamic Programming/largest_rectangle.py similarity index 100% rename from Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.py rename to Dynamic Programming/largest_rectangle.py From fcc234198420323fe8338eea7ad4ee55f1e73cb7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:45:40 +0530 Subject: [PATCH 1458/1894] rename file --- ...Largest_Rectangle_In_Binary_Matrix.js => largest_rectangle.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{Largest_Rectangle_In_Binary_Matrix.js => largest_rectangle.js} (100%) diff --git a/Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js b/Dynamic Programming/largest_rectangle.js similarity index 100% rename from Dynamic Programming/Largest_Rectangle_In_Binary_Matrix.js rename to Dynamic Programming/largest_rectangle.js From 12c98a05e4d1a48c9aa02ea9496be27ee1276ace Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:47:03 +0530 Subject: [PATCH 1459/1894] rename file --- Graphs/{Dijkstra.cpp => dijkstras.cpp} | 0 .../{fordFulkerson.cpp => ford_fulkerson.cpp} | 31 ++++++++++--------- 2 files changed, 16 insertions(+), 15 deletions(-) rename Graphs/{Dijkstra.cpp => dijkstras.cpp} (100%) rename Graphs/{fordFulkerson.cpp => ford_fulkerson.cpp} (65%) diff --git a/Graphs/Dijkstra.cpp b/Graphs/dijkstras.cpp similarity index 100% rename from Graphs/Dijkstra.cpp rename to Graphs/dijkstras.cpp diff --git a/Graphs/fordFulkerson.cpp b/Graphs/ford_fulkerson.cpp similarity index 65% rename from Graphs/fordFulkerson.cpp rename to Graphs/ford_fulkerson.cpp index f785e710..828b243d 100644 --- a/Graphs/fordFulkerson.cpp +++ b/Graphs/ford_fulkerson.cpp @@ -1,23 +1,24 @@ -/*Name : Shruti Swarupa Dhar -Github username : Shr-reny -Repository name : data-structures-and-algorithms -Problem : Implement Ford Fulkerson algorithm in C++ -Issue Number : #1386 -Problem statement : +/* + Name : Shruti Swarupa Dhar + Github username : Shr-reny + Repository name : data-structures-and-algorithms + Problem : Implement Ford Fulkerson algorithm in C++ + Issue Number : #1386 + Problem statement : -Given a graph which represents a flow network where every edge has a capacity. Also, given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with the following constraints: -Flow on an edge doesn’t exceed the given capacity of the edge. -Incoming flow is equal to outgoing flow for every vertex except s and t. + Given a graph which represents a flow network where every edge has a capacity. Also, given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with the following constraints: + Flow on an edge doesn’t exceed the given capacity of the edge. + Incoming flow is equal to outgoing flow for every vertex except s and t. -Explanation of the below C++ code : + Explanation of the below C++ code : -The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. -The algorithm works by iteratively finding an augmenting path, which is a path from the source to the sink in the residual graph, i.e., the graph obtained by subtracting the current flow from the capacity of each edge. The algorithm then increases the flow along this path by the maximum possible amount, which is the minimum capacity of the edges along the path. + The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints on the edges. + The algorithm works by iteratively finding an augmenting path, which is a path from the source to the sink in the residual graph, i.e., the graph obtained by subtracting the current flow from the capacity of each edge. The algorithm then increases the flow along this path by the maximum possible amount, which is the minimum capacity of the edges along the path. -Time Complexity : O(|V| * E^2) ,where E is the number of edges and V is the number of vertices. + Time Complexity : O(|V| * E^2) ,where E is the number of edges and V is the number of vertices. -Space Complexity :O(V) , as we created queue.*/ --------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------------------ + Space Complexity :O(V) , as we created queue. +*/ // C++ program for implementation of Ford Fulkerson From 62bbf37c268c5f0713d9f136ce3eb0ebfe1caa34 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:47:31 +0530 Subject: [PATCH 1460/1894] rename file --- Graphs/{graphs_bfs_snackes_ladders.cpp => snack_ladders.cpp} | 0 Graphs/{graphs_bfs_snakes_ladder.js => snack_ladders.js} | 0 Graphs/{graphs_bfs_snakes_ladders.py => snack_ladders.py} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Graphs/{graphs_bfs_snackes_ladders.cpp => snack_ladders.cpp} (100%) rename Graphs/{graphs_bfs_snakes_ladder.js => snack_ladders.js} (100%) rename Graphs/{graphs_bfs_snakes_ladders.py => snack_ladders.py} (100%) diff --git a/Graphs/graphs_bfs_snackes_ladders.cpp b/Graphs/snack_ladders.cpp similarity index 100% rename from Graphs/graphs_bfs_snackes_ladders.cpp rename to Graphs/snack_ladders.cpp diff --git a/Graphs/graphs_bfs_snakes_ladder.js b/Graphs/snack_ladders.js similarity index 100% rename from Graphs/graphs_bfs_snakes_ladder.js rename to Graphs/snack_ladders.js diff --git a/Graphs/graphs_bfs_snakes_ladders.py b/Graphs/snack_ladders.py similarity index 100% rename from Graphs/graphs_bfs_snakes_ladders.py rename to Graphs/snack_ladders.py From 8dcca9c4a40974b788899949f1d65b8e01c88288 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:47:46 +0530 Subject: [PATCH 1461/1894] rename file --- Graphs/{topological_sort_dfs.py => topological_sort.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{topological_sort_dfs.py => topological_sort.py} (100%) diff --git a/Graphs/topological_sort_dfs.py b/Graphs/topological_sort.py similarity index 100% rename from Graphs/topological_sort_dfs.py rename to Graphs/topological_sort.py From 0b25d5b47288ded7f8cb30c647700abbe6b4e7c4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:48:11 +0530 Subject: [PATCH 1462/1894] rename file --- Graphs/{Kruskal's_Algorithm.java => kruskals_algorithm.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Kruskal's_Algorithm.java => kruskals_algorithm.java} (100%) diff --git a/Graphs/Kruskal's_Algorithm.java b/Graphs/kruskals_algorithm.java similarity index 100% rename from Graphs/Kruskal's_Algorithm.java rename to Graphs/kruskals_algorithm.java From 1e3ae35bc8dff39d87caad46a3b42b99711a0c2f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:48:35 +0530 Subject: [PATCH 1463/1894] rename file --- Graphs/{Kruskal_Algo.py => kruskals_algorithm.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Kruskal_Algo.py => kruskals_algorithm.py} (100%) diff --git a/Graphs/Kruskal_Algo.py b/Graphs/kruskals_algorithm.py similarity index 100% rename from Graphs/Kruskal_Algo.py rename to Graphs/kruskals_algorithm.py From 98a8af165af6df530da7852fb38a184df9d822d7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:49:13 +0530 Subject: [PATCH 1464/1894] fix typo --- ...partion_of_string.cpp => find_optimal_partition_of_string.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash Table/{find_optimal_partion_of_string.cpp => find_optimal_partition_of_string.cpp} (100%) diff --git a/Hash Table/find_optimal_partion_of_string.cpp b/Hash Table/find_optimal_partition_of_string.cpp similarity index 100% rename from Hash Table/find_optimal_partion_of_string.cpp rename to Hash Table/find_optimal_partition_of_string.cpp From 4d3c7cbd9b50cf84873de371b8da4cf0ff8f2e54 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:49:56 +0530 Subject: [PATCH 1465/1894] rename file --- Linked List/{addTwoNumbers.cpp => add_two_numbers.cpp} | 0 Linked List/{addTwoNumbers.js => add_two_numbers.js} | 0 ...ly_linked_list_implementation.java => doubly_linked_list.java} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Linked List/{addTwoNumbers.cpp => add_two_numbers.cpp} (100%) rename Linked List/{addTwoNumbers.js => add_two_numbers.js} (100%) rename Linked List/{Doubly_linked_list_implementation.java => doubly_linked_list.java} (100%) diff --git a/Linked List/addTwoNumbers.cpp b/Linked List/add_two_numbers.cpp similarity index 100% rename from Linked List/addTwoNumbers.cpp rename to Linked List/add_two_numbers.cpp diff --git a/Linked List/addTwoNumbers.js b/Linked List/add_two_numbers.js similarity index 100% rename from Linked List/addTwoNumbers.js rename to Linked List/add_two_numbers.js diff --git a/Linked List/Doubly_linked_list_implementation.java b/Linked List/doubly_linked_list.java similarity index 100% rename from Linked List/Doubly_linked_list_implementation.java rename to Linked List/doubly_linked_list.java From f3828ca3a4701bcd46952ff60af8cad65166ff2a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 25 Jun 2023 20:50:17 +0530 Subject: [PATCH 1466/1894] remove duplicate --- .../implementation_Doubly_Linked_List.cpp | 196 ------------------ 1 file changed, 196 deletions(-) delete mode 100644 Linked List/implementation_Doubly_Linked_List.cpp diff --git a/Linked List/implementation_Doubly_Linked_List.cpp b/Linked List/implementation_Doubly_Linked_List.cpp deleted file mode 100644 index 2990f96c..00000000 --- a/Linked List/implementation_Doubly_Linked_List.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* Implementation of Doubly Linked List with Basic Functions: - > Addition of Node At Head - > Addition of Node At Tail - > Addition of Node In Between Of Linked List - > Deletion of Node At Head - > Deletion of Node At Tail - > Deletion of Intermediary Node Linked List - > Forward Traversal of Linked List - > Backward Traversal of Linked List -*/ -#include -using namespace std; - -// Define a doubly linked list node - -struct Node { - int val; - struct Node* next; - struct Node* prev; -}; - -// Function to inserts node at the head of the list -void insertAtHead(Node** head, int data) -{ - Node* temp = new Node; - temp->val = data; - - temp->next = (*head); - temp->prev = NULL; - - if ((*head) != NULL) - (*head)->prev = temp; - - (*head) = temp; -} - -// Function to inserts node at the tail of the list -void insertAtTail(Node** head, int data) -{ - - Node* temp = new Node; - temp->val = data; - temp->next = NULL; - - if (*head == NULL) { - temp->prev = NULL; - *head = temp; - return; - } - - Node* tail = *head; - - while (tail->next != NULL) - { - tail = tail->next; - } - - tail->next = temp; - temp->prev = tail; -} - -// Function to inserts after intermediary node -void insertAfterNode(Node* myNode, int data) -{ - if (myNode == NULL) return; - - Node* temp = new Node; - temp->val = data; - - temp->next = myNode->next; - myNode->next = temp; - temp->prev = myNode; - - if (temp->next != NULL) - temp->next->prev = temp; -} - -// Function to inserts node at the head of the list -Node* deleteAtHead(Node* head) -{ - if(head==NULL) return NULL; - Node* temp = head; - head = temp->next; - - head->prev = NULL; - delete temp; - return head; - -} - -// Function to inserts node at the tail of the list -void deleteAtTail(Node* head) -{ - if(head==NULL) return; - Node* temp = head; - while (temp->next != NULL) - { - temp = temp->next; - } - Node* tail=temp->prev; - tail->next=NULL; - delete temp; -} - -// Function to delete an intermediary node -void deleteNode(Node* myNode) -{ - if (myNode == NULL) return; - - Node* nextNode = myNode->next; - Node* prevNode = myNode->prev; - - nextNode->prev=prevNode; - prevNode->next=nextNode; - - delete myNode; -} - -// Function for forward Traversal -void displayList_F(Node* head) { - if(head==NULL) return; - Node* temp=head; - - while (temp != NULL) { - cout<val<<" "; - temp = temp->next; - } -} - -// Function for backward Traversal -void displayList_B(Node* head) { - if(head==NULL) return; - displayList_B(head->next); - cout<val<<" "; -} - -//main program -int main() { - /* Start with the empty list */ - Node* head = NULL; - - // Insert 40 as last node - insertAtTail(&head, 40); - - // insert 20 at the head - insertAtHead(&head, 20); - - // Insert 10 at the beginning. - insertAtHead(&head, 10); - - // Insert 50 at the end. - insertAtTail(&head, 50); - - // Insert 30, after 20. - insertAfterNode(head->next, 30); - - //Forward Traversal - cout<<"\n Forward Traversal of Doubly linked list is \n "<next->next); - - //Forward Traversal - cout<<"\n Forward Traversal of Doubly linked list is \n "< Date: Sun, 25 Jun 2023 20:50:51 +0530 Subject: [PATCH 1467/1894] rename file --- Linked List/{Kth_nodedelete.js => delete_kth_node.js} | 5 ----- ...ntation_Singly_Linked_List.cpp => singly_linked_list.cpp} | 0 2 files changed, 5 deletions(-) rename Linked List/{Kth_nodedelete.js => delete_kth_node.js} (91%) rename Linked List/{implementation_Singly_Linked_List.cpp => singly_linked_list.cpp} (100%) diff --git a/Linked List/Kth_nodedelete.js b/Linked List/delete_kth_node.js similarity index 91% rename from Linked List/Kth_nodedelete.js rename to Linked List/delete_kth_node.js index 7b7448b4..1192e751 100644 --- a/Linked List/Kth_nodedelete.js +++ b/Linked List/delete_kth_node.js @@ -14,10 +14,6 @@ Now you can create a linked list and call the removeKthFromEnd function to remov */ --------------------------------------------------------------------------//Javascript code begins here------------------------------------------------------------------------ - - - class Node { constructor(value) { this.value = value; @@ -73,7 +69,6 @@ while (current !== null) { current = current.next; } - /* OUTPUT: 1 diff --git a/Linked List/implementation_Singly_Linked_List.cpp b/Linked List/singly_linked_list.cpp similarity index 100% rename from Linked List/implementation_Singly_Linked_List.cpp rename to Linked List/singly_linked_list.cpp From 2179fd2e6472997952f6627e586f8741d0bfdc1b Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 26 Jun 2023 20:34:53 +0530 Subject: [PATCH 1468/1894] Create stacks_with_queues.py --- Stacks/stacks_with_queues.py | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Stacks/stacks_with_queues.py diff --git a/Stacks/stacks_with_queues.py b/Stacks/stacks_with_queues.py new file mode 100644 index 00000000..d258c85c --- /dev/null +++ b/Stacks/stacks_with_queues.py @@ -0,0 +1,59 @@ +from queue import Queue + +class Stack: + """ + Stack implementation using queues. + """ + + def __init__(self): + """ + Initialize an empty stack. + """ + self.queue1 = Queue() + self.queue2 = Queue() + + def push(self, item): + """ + Add an item to the top of the stack. + """ + # Add the item to the empty queue + self.queue1.put(item) + + # Move all the elements from the other queue to the empty queue + while not self.queue2.empty(): + self.queue1.put(self.queue2.get()) + + # Swap the names of the two queues + self.queue1, self.queue2 = self.queue2, self.queue1 + + def pop(self): + """ + Remove and return the item at the top of the stack. + """ + if self.queue2.empty(): + raise IndexError("Stack is empty") + + # Remove and return the front element of the non-empty queue + return self.queue2.get() + + def top(self): + """ + Return the item at the top of the stack without removing it. + """ + if self.queue2.empty(): + raise IndexError("Stack is empty") + + # Get the front element of the non-empty queue + return self.queue2.queue[0] + + def is_empty(self): + """ + Check if the stack is empty. + """ + return self.queue2.empty() + + def size(self): + """ + Return the number of items in the stack. + """ + return self.queue2.qsize() From 57f0979beedc2b1c4b6ecf1e05e2c4424d79577e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 26 Jun 2023 22:38:13 +0530 Subject: [PATCH 1469/1894] add union find in python --- Graphs/union_find.py | 117 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Graphs/union_find.py diff --git a/Graphs/union_find.py b/Graphs/union_find.py new file mode 100644 index 00000000..83c185c4 --- /dev/null +++ b/Graphs/union_find.py @@ -0,0 +1,117 @@ +''' + Write a UnionFind class that implements the union-find (also called a disjoint set) data structure. + This class should support three methods: + + + The union-find data structure is similar to a traditional set data structure in that it contains a collection + of unique values. However, these values are spread out amongst a variety of distinct disjoint sets, meaning that no set + can have duplicate values, and no two sets can contain the same value. + + createSet(value) : : Adds a given value in a new set containing only that value. + + union(valueOne, valueTwo) : : Takes in two values and determines which sets they are in. If they are in different sets, the sets are combined + into a single set. If either value is not in a set or they are in the same set, the function should have no effect. + + find(value): : Returns the "representative" value of the set for which a value belongs to. This can be any value in the set, but it should + always be the same value, regardless of which value in the set find is passed. If the value is not in a set, the function + should return null / none + + Explanation: + The provided code snippet is an optimized version of the Union-Find data structure. Here's a detailed explanation: + + - `UnionFind` struct: It contains two fields, `parents` and `ranks`. The `parents` map stores the parent of + each element, and the `ranks` map stores the rank of each element. The rank is used to optimize the Union operation. + + - `NewUnionFind` function: It initializes a new instance of the UnionFind struct by creating empty maps for + `parents` and `ranks`. + + - `CreateSet` method: It creates a new set with the given value. It sets the parent of the value to itself and + initializes its rank to 0. + + - `Find` method: It finds the root/representative of the set to which the given value belongs. It starts from the + given value and traverses the parent pointers until it reaches the root. It uses path compression optimization to + update the parent pointers along the path to the root. Finally, it returns a pointer to the root. + + `Union` method: It performs the union of two sets represented by the given values. It first checks if both values exist + in the data structure. If either value is missing, it returns without performing any union operation. Otherwise, it finds + the roots of the two sets using the `Find` method. It compares the ranks of the two roots and performs the union accordingly: + + If the rank of the root of `valueOne` is less than the rank of the root of `valueTwo`, it sets the parent of `valueOne`'s + root to `valueTwo`'s root. + + If the rank of the root of `valueOne` is greater than the rank of the root of `valueTwo`, it sets the parent of `valueTwo`'s + root to `valueOne`'s root. + + If the ranks are equal, it chooses one root as the parent and increments its rank by 1. + + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. + + The time and space complexity of the operations in the `UnionFind` data structure are as follows: + + CreateSet : O(n) time O(1) space + Find : O(log(n)) time O(1) space where n is total number of values + Union : O(log(n)) time O(1) space where n is total number of values + +''' +class UnionFind: + def __init__(self): + self.parents = {} # Map to store the parent of each element + self.ranks = {} # Map to store the rank of each element + + def create_set(self, value): + self.parents[value] = value # Set the parent of the value to itself + self.ranks[value] = 0 # Initialize the rank of the value to 0 + + def find(self, value): + if value not in self.parents: + return None # Return None if the value is not found (not part of any set) + + current_parent = value + while current_parent != self.parents[current_parent]: + current_parent = self.parents[current_parent] # Traverse the parent pointers until reaching the root + + # Perform path compression by updating parent pointers along the path to the root + # This optimization flattens the tree structure, reducing future lookup time + while value != current_parent: + next_parent = self.parents[value] + self.parents[value] = current_parent + value = next_parent + + return current_parent # Return the root/representative + + def union(self, value_one, value_two): + if value_one not in self.parents or value_two not in self.parents: + return # Return if either value is not found (not part of any set) + + value_one_root = self.find(value_one) # Find the root of the set containing value_one + value_two_root = self.find(value_two) # Find the root of the set containing value_two + + if self.ranks[value_one_root] < self.ranks[value_two_root]: + self.parents[value_one_root] = value_two_root # Set the parent of value_one's root to value_two's root + elif self.ranks[value_one_root] > self.ranks[value_two_root]: + self.parents[value_two_root] = value_one_root # Set the parent of value_two's root to value_one's root + else: + self.parents[value_one_root] = value_two_root # Set the parent of value_one's root to value_two's root + self.ranks[value_two_root] += 1 # Increment the rank of value_two's root + + +# Create a new instance of UnionFind +union = UnionFind() + +# Create individual sets +union.create_set(1) +union.create_set(2) +union.create_set(3) + +# Perform union operations +union.union(1, 2) +union.union(2, 3) + +# Find representatives of values +representative = union.find(3) + +# Check if the representative is found +if representative is not None: + print("The representative of 3 is:", representative) +else: + print("Value 3 is not found.") From 5fef6adf217222d6124a0892a063cf6135565c6c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 26 Jun 2023 22:40:05 +0530 Subject: [PATCH 1470/1894] add union find in javascript --- Graphs/union_find.js | 127 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 Graphs/union_find.js diff --git a/Graphs/union_find.js b/Graphs/union_find.js new file mode 100644 index 00000000..ab5ae771 --- /dev/null +++ b/Graphs/union_find.js @@ -0,0 +1,127 @@ +/* + Write a UnionFind class that implements the union-find (also called a disjoint set) data structure. + This class should support three methods: + + + The union-find data structure is similar to a traditional set data structure in that it contains a collection + of unique values. However, these values are spread out amongst a variety of distinct disjoint sets, meaning that no set + can have duplicate values, and no two sets can contain the same value. + + createSet(value) : : Adds a given value in a new set containing only that value. + + union(valueOne, valueTwo) : : Takes in two values and determines which sets they are in. If they are in different sets, the sets are combined + into a single set. If either value is not in a set or they are in the same set, the function should have no effect. + + find(value): : Returns the "representative" value of the set for which a value belongs to. This can be any value in the set, but it should + always be the same value, regardless of which value in the set find is passed. If the value is not in a set, the function + should return null / none + + Explanation: + The provided code snippet is an optimized version of the Union-Find data structure. Here's a detailed explanation: + + - `UnionFind` struct: It contains two fields, `parents` and `ranks`. The `parents` map stores the parent of + each element, and the `ranks` map stores the rank of each element. The rank is used to optimize the Union operation. + + - `NewUnionFind` function: It initializes a new instance of the UnionFind struct by creating empty maps for + `parents` and `ranks`. + + - `CreateSet` method: It creates a new set with the given value. It sets the parent of the value to itself and + initializes its rank to 0. + + - `Find` method: It finds the root/representative of the set to which the given value belongs. It starts from the + given value and traverses the parent pointers until it reaches the root. It uses path compression optimization to + update the parent pointers along the path to the root. Finally, it returns a pointer to the root. + + `Union` method: It performs the union of two sets represented by the given values. It first checks if both values exist + in the data structure. If either value is missing, it returns without performing any union operation. Otherwise, it finds + the roots of the two sets using the `Find` method. It compares the ranks of the two roots and performs the union accordingly: + + If the rank of the root of `valueOne` is less than the rank of the root of `valueTwo`, it sets the parent of `valueOne`'s + root to `valueTwo`'s root. + + If the rank of the root of `valueOne` is greater than the rank of the root of `valueTwo`, it sets the parent of `valueTwo`'s + root to `valueOne`'s root. + + If the ranks are equal, it chooses one root as the parent and increments its rank by 1. + + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. + + The time and space complexity of the operations in the `UnionFind` data structure are as follows: + + CreateSet : O(n) time O(1) space + Find : O(log(n)) time O(1) space where n is total number of values + Union : O(log(n)) time O(1) space where n is total number of values + +*/ +class UnionFind { + constructor() { + this.parents = {}; // Map to store the parent of each element + this.ranks = {}; // Map to store the rank of each element + } + + createSet(value) { + this.parents[value] = value; // Set the parent of the value to itself + this.ranks[value] = 0; // Initialize the rank of the value to 0 + } + + find(value) { + if (!(value in this.parents)) { + return null; // Return null if the value is not found (not part of any set) + } + + let currentParent = value; + while (currentParent !== this.parents[currentParent]) { + currentParent = this.parents[currentParent]; // Traverse the parent pointers until reaching the root + } + + // Perform path compression by updating parent pointers along the path to the root + // This optimization flattens the tree structure, reducing future lookup time + while (value !== currentParent) { + const nextParent = this.parents[value]; + this.parents[value] = currentParent; + value = nextParent; + } + + return currentParent; // Return the root/representative + } + + union(valueOne, valueTwo) { + if (!(valueOne in this.parents) || !(valueTwo in this.parents)) { + return; // Return if either value is not found (not part of any set) + } + + const valueOneRoot = this.find(valueOne); // Find the root of the set containing valueOne + const valueTwoRoot = this.find(valueTwo); // Find the root of the set containing valueTwo + + if (this.ranks[valueOneRoot] < this.ranks[valueTwoRoot]) { + this.parents[valueOneRoot] = valueTwoRoot; // Set the parent of valueOne's root to valueTwo's root + } else if (this.ranks[valueOneRoot] > this.ranks[valueTwoRoot]) { + this.parents[valueTwoRoot] = valueOneRoot; // Set the parent of valueTwo's root to valueOne's root + } else { + this.parents[valueOneRoot] = valueTwoRoot; // Set the parent of valueOne's root to valueTwo's root + this.ranks[valueTwoRoot] += 1; // Increment the rank of valueTwo's root + } + } +} + +// Create a new instance of UnionFind +const union = new UnionFind(); + +// Create individual sets +union.createSet(1); +union.createSet(2); +union.createSet(3); + +// Perform union operations +union.union(1, 2); +union.union(2, 3); + +// Find representatives of values +const representative = union.find(3); + +// Check if the representative is found +if (representative !== null) { + console.log("The representative of 3 is:", representative); +} else { + console.log("Value 3 is not found."); +} From 7df95df9eda79b9cf64ab4d78cad32127a28969d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 26 Jun 2023 22:41:52 +0530 Subject: [PATCH 1471/1894] add union find in c++ --- Graphs/union_find.cpp | 132 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 Graphs/union_find.cpp diff --git a/Graphs/union_find.cpp b/Graphs/union_find.cpp new file mode 100644 index 00000000..ea7d19f3 --- /dev/null +++ b/Graphs/union_find.cpp @@ -0,0 +1,132 @@ +/* + Write a UnionFind class that implements the union-find (also called a disjoint set) data structure. + This class should support three methods: + + + The union-find data structure is similar to a traditional set data structure in that it contains a collection + of unique values. However, these values are spread out amongst a variety of distinct disjoint sets, meaning that no set + can have duplicate values, and no two sets can contain the same value. + + createSet(value) : : Adds a given value in a new set containing only that value. + + union(valueOne, valueTwo) : : Takes in two values and determines which sets they are in. If they are in different sets, the sets are combined + into a single set. If either value is not in a set or they are in the same set, the function should have no effect. + + find(value): : Returns the "representative" value of the set for which a value belongs to. This can be any value in the set, but it should + always be the same value, regardless of which value in the set find is passed. If the value is not in a set, the function + should return null / none + + Explanation: + The provided code snippet is an optimized version of the Union-Find data structure. Here's a detailed explanation: + + - `UnionFind` struct: It contains two fields, `parents` and `ranks`. The `parents` map stores the parent of + each element, and the `ranks` map stores the rank of each element. The rank is used to optimize the Union operation. + + - `NewUnionFind` function: It initializes a new instance of the UnionFind struct by creating empty maps for + `parents` and `ranks`. + + - `CreateSet` method: It creates a new set with the given value. It sets the parent of the value to itself and + initializes its rank to 0. + + - `Find` method: It finds the root/representative of the set to which the given value belongs. It starts from the + given value and traverses the parent pointers until it reaches the root. It uses path compression optimization to + update the parent pointers along the path to the root. Finally, it returns a pointer to the root. + + `Union` method: It performs the union of two sets represented by the given values. It first checks if both values exist + in the data structure. If either value is missing, it returns without performing any union operation. Otherwise, it finds + the roots of the two sets using the `Find` method. It compares the ranks of the two roots and performs the union accordingly: + + If the rank of the root of `valueOne` is less than the rank of the root of `valueTwo`, it sets the parent of `valueOne`'s + root to `valueTwo`'s root. + + If the rank of the root of `valueOne` is greater than the rank of the root of `valueTwo`, it sets the parent of `valueTwo`'s + root to `valueOne`'s root. + + If the ranks are equal, it chooses one root as the parent and increments its rank by 1. + + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. + + The time and space complexity of the operations in the `UnionFind` data structure are as follows: + + CreateSet : O(n) time O(1) space + Find : O(log(n)) time O(1) space where n is total number of values + Union : O(log(n)) time O(1) space where n is total number of values + +*/ +#include +#include + +class UnionFind { +public: + std::unordered_map parents; // Map to store the parent of each element + std::unordered_map ranks; // Map to store the rank of each element + + void createSet(int value) { + parents[value] = value; // Set the parent of the value to itself + ranks[value] = 0; // Initialize the rank of the value to 0 + } + + int find(int value) { + if (parents.find(value) == parents.end()) { + return -1; // Return -1 if the value is not found (not part of any set) + } + + int currentParent = value; + while (currentParent != parents[currentParent]) { + currentParent = parents[currentParent]; // Traverse the parent pointers until reaching the root + } + + // Perform path compression by updating parent pointers along the path to the root + // This optimization flattens the tree structure, reducing future lookup time + while (value != currentParent) { + int nextParent = parents[value]; + parents[value] = currentParent; + value = nextParent; + } + + return currentParent; // Return the root/representative + } + + void unionSets(int valueOne, int valueTwo) { + if (parents.find(valueOne) == parents.end() || parents.find(valueTwo) == parents.end()) { + return; // Return if either value is not found (not part of any set) + } + + int valueOneRoot = find(valueOne); // Find the root of the set containing valueOne + int valueTwoRoot = find(valueTwo); // Find the root of the set containing valueTwo + + if (ranks[valueOneRoot] < ranks[valueTwoRoot]) { + parents[valueOneRoot] = valueTwoRoot; // Set the parent of valueOne's root to valueTwo's root + } else if (ranks[valueOneRoot] > ranks[valueTwoRoot]) { + parents[valueTwoRoot] = valueOneRoot; // Set the parent of valueTwo's root to valueOne's root + } else { + parents[valueOneRoot] = valueTwoRoot; // Set the parent of valueOne's root to valueTwo's root + ranks[valueTwoRoot] += 1; // Increment the rank of valueTwo's root + } + } +}; + +int main() { + UnionFind unionFind; + + // Create individual sets + unionFind.createSet(1); + unionFind.createSet(2); + unionFind.createSet(3); + + // Perform union operations + unionFind.unionSets(1, 2); + unionFind.unionSets(2, 3); + + // Find representatives of values + int representative = unionFind.find(3); + + // Check if the representative is found + if (representative != -1) { + std::cout << "The representative of 3 is: " << representative << std::endl; + } else { + std::cout << "Value 3 is not found." << std::endl; + } + + return 0; +} From 4652709aa4da893b004a3422061e9d2aa688d22e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 26 Jun 2023 22:43:31 +0530 Subject: [PATCH 1472/1894] add union find in java --- Graphs/union_find.java | 136 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 Graphs/union_find.java diff --git a/Graphs/union_find.java b/Graphs/union_find.java new file mode 100644 index 00000000..0d3a4bcc --- /dev/null +++ b/Graphs/union_find.java @@ -0,0 +1,136 @@ +/* + Write a UnionFind class that implements the union-find (also called a disjoint set) data structure. + This class should support three methods: + + + The union-find data structure is similar to a traditional set data structure in that it contains a collection + of unique values. However, these values are spread out amongst a variety of distinct disjoint sets, meaning that no set + can have duplicate values, and no two sets can contain the same value. + + createSet(value) : : Adds a given value in a new set containing only that value. + + union(valueOne, valueTwo) : : Takes in two values and determines which sets they are in. If they are in different sets, the sets are combined + into a single set. If either value is not in a set or they are in the same set, the function should have no effect. + + find(value): : Returns the "representative" value of the set for which a value belongs to. This can be any value in the set, but it should + always be the same value, regardless of which value in the set find is passed. If the value is not in a set, the function + should return null / none + + Explanation: + The provided code snippet is an optimized version of the Union-Find data structure. Here's a detailed explanation: + + - `UnionFind` struct: It contains two fields, `parents` and `ranks`. The `parents` map stores the parent of + each element, and the `ranks` map stores the rank of each element. The rank is used to optimize the Union operation. + + - `NewUnionFind` function: It initializes a new instance of the UnionFind struct by creating empty maps for + `parents` and `ranks`. + + - `CreateSet` method: It creates a new set with the given value. It sets the parent of the value to itself and + initializes its rank to 0. + + - `Find` method: It finds the root/representative of the set to which the given value belongs. It starts from the + given value and traverses the parent pointers until it reaches the root. It uses path compression optimization to + update the parent pointers along the path to the root. Finally, it returns a pointer to the root. + + `Union` method: It performs the union of two sets represented by the given values. It first checks if both values exist + in the data structure. If either value is missing, it returns without performing any union operation. Otherwise, it finds + the roots of the two sets using the `Find` method. It compares the ranks of the two roots and performs the union accordingly: + + If the rank of the root of `valueOne` is less than the rank of the root of `valueTwo`, it sets the parent of `valueOne`'s + root to `valueTwo`'s root. + + If the rank of the root of `valueOne` is greater than the rank of the root of `valueTwo`, it sets the parent of `valueTwo`'s + root to `valueOne`'s root. + + If the ranks are equal, it chooses one root as the parent and increments its rank by 1. + + By considering the ranks of the roots during the union, the height of the resulting union-find tree can be minimized. + + The time and space complexity of the operations in the `UnionFind` data structure are as follows: + + CreateSet : O(n) time O(1) space + Find : O(log(n)) time O(1) space where n is total number of values + Union : O(log(n)) time O(1) space where n is total number of values + +*/ +import java.util.HashMap; +import java.util.Map; + +class UnionFind { + private Map parents; // Map to store the parent of each element + private Map ranks; // Map to store the rank of each element + + public UnionFind() { + parents = new HashMap<>(); + ranks = new HashMap<>(); + } + + public void createSet(int value) { + parents.put(value, value); // Set the parent of the value to itself + ranks.put(value, 0); // Initialize the rank of the value to 0 + } + + public int find(int value) { + if (!parents.containsKey(value)) { + return -1; // Return -1 if the value is not found (not part of any set) + } + + int currentParent = value; + while (currentParent != parents.get(currentParent)) { + currentParent = parents.get(currentParent); // Traverse the parent pointers until reaching the root + } + + // Perform path compression by updating parent pointers along the path to the root + // This optimization flattens the tree structure, reducing future lookup time + while (value != currentParent) { + int nextParent = parents.get(value); + parents.put(value, currentParent); + value = nextParent; + } + + return currentParent; // Return the root/representative + } + + public void unionSets(int valueOne, int valueTwo) { + if (!parents.containsKey(valueOne) || !parents.containsKey(valueTwo)) { + return; // Return if either value is not found (not part of any set) + } + + int valueOneRoot = find(valueOne); // Find the root of the set containing valueOne + int valueTwoRoot = find(valueTwo); // Find the root of the set containing valueTwo + + if (ranks.get(valueOneRoot) < ranks.get(valueTwoRoot)) { + parents.put(valueOneRoot, valueTwoRoot); // Set the parent of valueOne's root to valueTwo's root + } else if (ranks.get(valueOneRoot) > ranks.get(valueTwoRoot)) { + parents.put(valueTwoRoot, valueOneRoot); // Set the parent of valueTwo's root to valueOne's root + } else { + parents.put(valueOneRoot, valueTwoRoot); // Set the parent of valueOne's root to valueTwo's root + ranks.put(valueTwoRoot, ranks.get(valueTwoRoot) + 1); // Increment the rank of valueTwo's root + } + } +} + +public class Main { + public static void main(String[] args) { + UnionFind unionFind = new UnionFind(); + + // Create individual sets + unionFind.createSet(1); + unionFind.createSet(2); + unionFind.createSet(3); + + // Perform union operations + unionFind.unionSets(1, 2); + unionFind.unionSets(2, 3); + + // Find representatives of values + int representative = unionFind.find(3); + + // Check if the representative is found + if (representative != -1) { + System.out.println("The representative of 3 is: " + representative); + } else { + System.out.println("Value 3 is not found."); + } + } +} From f7f07f36977468e587e0bbdde852619da8b995dc Mon Sep 17 00:00:00 2001 From: Munyao Kelvin Date: Tue, 27 Jun 2023 04:08:12 +0300 Subject: [PATCH 1473/1894] add question and explanation --- Dynamic Programming/max_path_sum.go | 31 ++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/max_path_sum.go b/Dynamic Programming/max_path_sum.go index 0474a05f..a8029b6f 100644 --- a/Dynamic Programming/max_path_sum.go +++ b/Dynamic Programming/max_path_sum.go @@ -1,4 +1,33 @@ -// Dynamic Programming: Find Binary Tree Maximum Path Sum in Go +/// How would you approach finding the maximum path sum in a binary tree using dynamic programming in Go? +// Provide a sample input and output, explain your approach using comments, +// and analyze the time and space complexity of your solution. + +// sample input: 1 +// / \ +// 2 3 +// sample output: Maximum Path Sum: 6 + +/// Explanation : +// 1. Implement a function that calculates the maximum path sum in a binary tree using dynamic programming. +// 2. Create a struct treeNode to represent each node in the binary tree, including a Val field for the node's value, Left field for the left child, and Right field for the right child. +// 3. Define a helper function pathMaxSum that takes the root node as input and returns the maximum path sum. +// 4 Within maxPathSum, initialize a variable maxSum with the minimum integer value to track the maximum path sum. +// 5. Call the recursive helper function findMaxSum and pass the root node and the maxSum variable as arguments. +// 6. In the findMaxSum function, handle the base case: if the node is nil, return 0. +// 7. Recursively find the maximum path sum for the left and right subtrees by calling findMaxSum on the left and right children of the current node. +// 8. Calculate the maximum path sum that includes the current node: + // Check if the left sum is negative (less than 0), assign it as 0. + // Check if the right sum is negative (less than 0), assign it as 0. + // Update the maxSum by comparing it with the sum of the current node's value, left sum, and right sum.// +// 9. Return the maximum path sum including the current node (either the current node's value plus the maximum of left or right sum). +// 10. Finally, return the maxSum from the pathMaxSum function. +// 11. In the main function, create a sample binary tree and call pathMaxSum to find the maximum path sum. Print the result. + +// Time Complexity: The time complexity of this solution is O(N), where N is the number of nodes in the binary tree, as we need to traverse each node once. + +// Space Complexity: The space complexity is O(H), where H is the height of the binary tree. This is due to the recursive calls on the stack, which can go up to the height of the tree. + + package main import ( From 8727d08c73e867e0e6818996a2df6ab7a3e98c0b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:30:46 +0530 Subject: [PATCH 1474/1894] add sample io --- Dynamic Programming/best_time_to_buy_and_sell_stock.cpp | 3 +++ Dynamic Programming/best_time_to_buy_and_sell_stock.go | 3 +++ Dynamic Programming/best_time_to_buy_and_sell_stock.java | 3 +++ Dynamic Programming/best_time_to_buy_and_sell_stock.js | 3 +++ Dynamic Programming/best_time_to_buy_and_sell_stock.py | 4 ++++ 5 files changed, 16 insertions(+) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp index a03f9074..147d4c5b 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -6,6 +6,9 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + + Sample Input [7, 1, 5, 3, 6, 4] + Output: 5 buy at 1 sell at 6 Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.go b/Dynamic Programming/best_time_to_buy_and_sell_stock.go index 916b5949..ebaa477f 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.go +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.go @@ -7,6 +7,9 @@ Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + Sample Input [7, 1, 5, 3, 6, 4] + Output: 5 buy at 1 sell at 6 + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit */ diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.java b/Dynamic Programming/best_time_to_buy_and_sell_stock.java index 1300a1cd..c6e9c3a7 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.java +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.java @@ -6,6 +6,9 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + + Sample Input [7, 1, 5, 3, 6, 4] + Output: 5 buy at 1 sell at 6 Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.js b/Dynamic Programming/best_time_to_buy_and_sell_stock.js index 72cbd63b..8e1ee1da 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.js +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.js @@ -6,6 +6,9 @@ If the price is less than the current minimum price, we update the minimum price. Otherwise, if the difference between the price and the minimum price is greater than the current maximum profit, we update the maximum profit. Finally, we return the maximum profit + + Sample Input [7, 1, 5, 3, 6, 4] + Output: 5 buy at 1 sell at 6 Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.py b/Dynamic Programming/best_time_to_buy_and_sell_stock.py index 046a7c4a..3a582401 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.py +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.py @@ -8,6 +8,10 @@ price, and updating the maximum profit if the difference between the current price and the minimum price is greater than the current maximum profit. Finally, it returns the maximum profit. + + Sample Input [7, 1, 5, 3, 6, 4] + Output: 5 buy at 1 sell at 6 + Time Complexity: O(n), where n is the length of the prices array. Space Complexity: O(1), as we are only using two variables to keep track of the minimum price and maximum profit ''' From 647e524d3c9a6da3d5783b7ebe319e9ac57ae5d1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:32:38 +0530 Subject: [PATCH 1475/1894] add sample io --- Dynamic Programming/coin_change.cpp | 3 +++ Dynamic Programming/coin_change.go | 3 +++ Dynamic Programming/coin_change.py | 3 +++ 3 files changed, 9 insertions(+) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index 02240674..30edc692 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -10,6 +10,9 @@ the amount and the code returns -1. Otherwise, the code returns the minimum number of coins needed to make the target amount. + Sample Input : [1, 2, 5] target : 11 + Output 3 (5, 5, 1) + The time complexity is O(n * V), where n is the number of coins and V is the value we want to make change for. The space complexity is also O(n * V) as we need to store the minimum number of coins required to make change for every value up to V for every coin. diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go index 940c9dbf..f631b452 100644 --- a/Dynamic Programming/coin_change.go +++ b/Dynamic Programming/coin_change.go @@ -16,6 +16,9 @@ target amount. If this value is infinity, then it's not possible to make the amount using the given coins, so we return -1. + Sample Input : [1, 2, 5] target : 11 + Output 3 (5, 5, 1) + The time complexity of this implementation is O(nm), where n is the number of coins and m is the target amount. The space complexity is also O(nm) because we're storing a 2D table of size (n+1) x (m+1). diff --git a/Dynamic Programming/coin_change.py b/Dynamic Programming/coin_change.py index b388c5c4..583e0922 100644 --- a/Dynamic Programming/coin_change.py +++ b/Dynamic Programming/coin_change.py @@ -3,6 +3,9 @@ target value as inputs, and returns the minimum number of coins required to reach the target value. It uses a bottom-up approach to build a table of minimum coin counts for each target value up to the input target. + + Sample Input : [1, 2, 5] target : 11 + Output 3 (5, 5, 1) The time complexity of this implementation is O(amount * n), where n is the number of coins. The space complexity is O(amount). From f30ff968347880b4ab07fbdc4354bd4540c8ba7c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:33:33 +0530 Subject: [PATCH 1476/1894] add question --- Dynamic Programming/coin_change.cpp | 6 ++++- Dynamic Programming/coin_change.go | 5 ++++ Dynamic Programming/coin_change.java | 39 ++++++++++++++-------------- Dynamic Programming/coin_change.py | 5 ++++ 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/Dynamic Programming/coin_change.cpp b/Dynamic Programming/coin_change.cpp index 30edc692..fe971c89 100644 --- a/Dynamic Programming/coin_change.cpp +++ b/Dynamic Programming/coin_change.cpp @@ -1,5 +1,9 @@ -// Coin Change problem using DP /* + Coin Change Problem + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. + The code uses a dynamic programming approach to solve the coin change problem. The dp vector is used to store the minimum number of coins needed to make each amount from 0 to amount. The minimum number of coins needed to make an amount of 0 is 0. Then, for each coin, the code iterates through each diff --git a/Dynamic Programming/coin_change.go b/Dynamic Programming/coin_change.go index f631b452..3f1412c0 100644 --- a/Dynamic Programming/coin_change.go +++ b/Dynamic Programming/coin_change.go @@ -1,4 +1,9 @@ /* + Coin Change Problem + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. + This implementation uses a bottom-up approach to fill in a 2D table of minimum coin counts for each amount up to the target amount. The table is initialized with the base cases (0 coins for an amount of 0, infinity for an amount greater than 0) and then filled in using the recurrence relation: diff --git a/Dynamic Programming/coin_change.java b/Dynamic Programming/coin_change.java index 1a710d61..1055d038 100644 --- a/Dynamic Programming/coin_change.java +++ b/Dynamic Programming/coin_change.java @@ -1,27 +1,28 @@ -/* QCoin Change Problem -You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount - of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any - combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. +/* + Coin Change Problem + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. - Example 1: + Example 1: -Input: coins = [1,2,5], amount = 11 -Output: 3 -Explanation: 11 = 5 + 5 + 1 + Input: coins = [1,2,5], amount = 11 + Output: 3 + Explanation: 11 = 5 + 5 + 1 -Example 2: -Input: coins = [2], amount = 3 -Output: -1 + Example 2: + Input: coins = [2], amount = 3 + Output: -1 -Example 3: -Input: coins = [1], amount = 0 -Output: 0 - -Constraints: + Example 3: + Input: coins = [1], amount = 0 + Output: 0 -1 <= coins.length <= 12 -1 <= coins[i] <= 231 - 1 -0 <= amount <= 104 */ + Constraints: + + 1 <= coins.length <= 12 + 1 <= coins[i] <= 231 - 1 + 0 <= amount <= 104 */ //SOLUTION //EXPLANATION OF CODE diff --git a/Dynamic Programming/coin_change.py b/Dynamic Programming/coin_change.py index 583e0922..60f672cf 100644 --- a/Dynamic Programming/coin_change.py +++ b/Dynamic Programming/coin_change.py @@ -1,4 +1,9 @@ ''' + Coin Change Problem + You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount + of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any + combination of the coins, return -1.You may assume that you have an infinite number of each kind of coin. + The coin change problem is a dynamic programming solution that takes a list of coin denominations and a target value as inputs, and returns the minimum number of coins required to reach the target value. It uses a bottom-up approach to build a table of minimum coin counts for each target value up to the From c7ac2908429b6807a563ce13a7478e57a638ea95 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:35:53 +0530 Subject: [PATCH 1477/1894] make file name consistent and update documentation --- .../distance_of_nearest_zero.js | 24 +++++++++++++++---- ..._matrix.java => distane_of_nearest_0.java} | 0 2 files changed, 20 insertions(+), 4 deletions(-) rename Dynamic Programming/{distane_of_nearest_zero_in_matrix.java => distane_of_nearest_0.java} (100%) diff --git a/Dynamic Programming/distance_of_nearest_zero.js b/Dynamic Programming/distance_of_nearest_zero.js index 9495c1c6..4b0410ab 100644 --- a/Dynamic Programming/distance_of_nearest_zero.js +++ b/Dynamic Programming/distance_of_nearest_zero.js @@ -1,8 +1,24 @@ -Example: -Input: mat = [[0,0,0],[0,1,0],[0,0,0]] -Output: [[0,0,0],[0,1,0],[0,0,0]] +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java -It can be solved using a Breadth First Search Algorithm(BFS) + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). + +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). function updateMatrix(mat) { const m = mat.length; diff --git a/Dynamic Programming/distane_of_nearest_zero_in_matrix.java b/Dynamic Programming/distane_of_nearest_0.java similarity index 100% rename from Dynamic Programming/distane_of_nearest_zero_in_matrix.java rename to Dynamic Programming/distane_of_nearest_0.java From 1bd1be8641c272c2c4cf8eead498462fcae54519 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:39:08 +0530 Subject: [PATCH 1478/1894] add findClosestValue in c++ --- .../find_closest_value.cpp | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Trees/Binary Search Trees/find_closest_value.cpp diff --git a/Trees/Binary Search Trees/find_closest_value.cpp b/Trees/Binary Search Trees/find_closest_value.cpp new file mode 100644 index 00000000..37ac82e8 --- /dev/null +++ b/Trees/Binary Search Trees/find_closest_value.cpp @@ -0,0 +1,81 @@ +/* + Write a function that takes in a Binary Search Tree (BST) and a target integer + value and returns the closest value to that target value contained in the BST. + +Sample Input : 12 + + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 +Output : 13 + + Time and Space complexity: + + Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST + Worst: O(n) time | O(1) space - where n is the number of nodes in the BST +*/ +#include + +class BST { +public: + int value; + BST* left; + BST* right; + + BST(int val) { + value = val; + left = nullptr; + right = nullptr; + } + + int findClosestValue(int target) { + // Call the helper function with the initial closest value as the root value + return findClosestValueHelper(target, value); + } + +private: + int findClosestValueHelper(int target, int closest) { + // Compare the absolute difference between the target and the current closest value + // with the absolute difference between the target and the current node value + if (std::abs(target - closest) > std::abs(target - value)) { + closest = value; + } + + // Look for the target in the left subtree if the target is smaller than the current node value + if (target < value && left != nullptr) { + return left->findClosestValueHelper(target, closest); + } + // Look for the target in the right subtree if the target is greater than the current node value + else if (target > value && right != nullptr) { + return right->findClosestValueHelper(target, closest); + } + + return closest; + } +}; + +int main() { + // Create a BST instance + BST* bst = new BST(10); + bst->left = new BST(5); + bst->right = new BST(15); + bst->left->left = new BST(2); + bst->left->right = new BST(5); + bst->right->left = new BST(13); + bst->right->right = new BST(22); + bst->left->left->left = new BST(1); + bst->right->left->right = new BST(14); + + // Find the closest value to the target + int target = 12; + int closestValue = bst->findClosestValue(target); + + // Print the result + std::cout << "The closest value to " << target << " is " << closestValue << std::endl; + + return 0; +} From adf673cefae2b2acbc6f5243bcc54a250d9d1cc9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:40:13 +0530 Subject: [PATCH 1479/1894] add explanation --- Trees/Binary Search Trees/find_closest_value.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Trees/Binary Search Trees/find_closest_value.cpp b/Trees/Binary Search Trees/find_closest_value.cpp index 37ac82e8..40c769d9 100644 --- a/Trees/Binary Search Trees/find_closest_value.cpp +++ b/Trees/Binary Search Trees/find_closest_value.cpp @@ -13,6 +13,15 @@ Sample Input : 12 1 14 Output : 13 + Explanation: + + The code defines a BST (Binary Search Tree) class with member functions to find the closest value to a given target value. + The findClosestValue function is the public interface that initializes the closest value with the root value and calls + the helper function. The findClosestValueHelper function recursively traverses the tree, updating the closest value based + on the absolute difference between the target and the current node value. It then continues the search in the appropriate + subtree based on the comparison with the target value. The absDiff function calculates the absolute difference between two + integers. + Time and Space complexity: Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST From 503f866609bf9245ff38b87f1c3655e2eed41a45 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:40:34 +0530 Subject: [PATCH 1480/1894] add explanation --- Trees/Binary Search Trees/find_closest_value.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Trees/Binary Search Trees/find_closest_value.go b/Trees/Binary Search Trees/find_closest_value.go index 0c09b8bf..f65a16be 100644 --- a/Trees/Binary Search Trees/find_closest_value.go +++ b/Trees/Binary Search Trees/find_closest_value.go @@ -13,6 +13,15 @@ Sample Input : 12 1 14 Output : 13 + Explanation: + + The code defines a BST (Binary Search Tree) class with member functions to find the closest value to a given target value. + The findClosestValue function is the public interface that initializes the closest value with the root value and calls + the helper function. The findClosestValueHelper function recursively traverses the tree, updating the closest value based + on the absolute difference between the target and the current node value. It then continues the search in the appropriate + subtree based on the comparison with the target value. The absDiff function calculates the absolute difference between two + integers. + Time and Space complexity: Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST From af401f9ac865e8d09b0a380d2070e27e57bde33b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 22:41:29 +0530 Subject: [PATCH 1481/1894] add find closest value in python --- .../Binary Search Trees/find_closest_value.py | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Trees/Binary Search Trees/find_closest_value.py diff --git a/Trees/Binary Search Trees/find_closest_value.py b/Trees/Binary Search Trees/find_closest_value.py new file mode 100644 index 00000000..cc32a3e9 --- /dev/null +++ b/Trees/Binary Search Trees/find_closest_value.py @@ -0,0 +1,71 @@ +''' + Write a function that takes in a Binary Search Tree (BST) and a target integer + value and returns the closest value to that target value contained in the BST. + +Sample Input : 12 + + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 +Output : 13 + + Explanation: + + The code defines a BST (Binary Search Tree) class with member functions to find the closest value to a given target value. + The findClosestValue function is the public interface that initializes the closest value with the root value and calls + the helper function. The findClosestValueHelper function recursively traverses the tree, updating the closest value based + on the absolute difference between the target and the current node value. It then continues the search in the appropriate + subtree based on the comparison with the target value. The absDiff function calculates the absolute difference between two + integers. + + Time and Space complexity: + + Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST + Worst: O(n) time | O(1) space - where n is the number of nodes in the BST +''' +class BST: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + + def find_closest_value(self, target): + # Call the helper function with the initial closest value as the root value + return self._find_closest_value_helper(target, self.value) + + def _find_closest_value_helper(self, target, closest): + # Compare the absolute difference between the target and the current closest value + # with the absolute difference between the target and the current node value + if abs(target - closest) > abs(target - self.value): + closest = self.value + + # Look for the target in the left subtree if the target is smaller than the current node value + if target < self.value and self.left: + return self.left._find_closest_value_helper(target, closest) + # Look for the target in the right subtree if the target is greater than the current node value + elif target > self.value and self.right: + return self.right._find_closest_value_helper(target, closest) + + return closest + +# Create a BST instance +bst = BST(10) +bst.left = BST(5) +bst.right = BST(15) +bst.left.left = BST(2) +bst.left.right = BST(5) +bst.right.left = BST(13) +bst.right.right = BST(22) +bst.left.left.left = BST(1) +bst.right.left.right = BST(14) + +# Find the closest value to the target +target = 12 +closest_value = bst.find_closest_value(target) + +# Print the result +print(f"The closest value to {target} is {closest_value}") From fbcd61308c0ac9bab78f794aab8f2cfc93a855f9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 27 Jun 2023 23:06:45 +0530 Subject: [PATCH 1482/1894] add find closest value in js --- .../Binary Search Trees/find_closest_value.js | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Trees/Binary Search Trees/find_closest_value.js diff --git a/Trees/Binary Search Trees/find_closest_value.js b/Trees/Binary Search Trees/find_closest_value.js new file mode 100644 index 00000000..8bbdf488 --- /dev/null +++ b/Trees/Binary Search Trees/find_closest_value.js @@ -0,0 +1,78 @@ +/* + Write a function that takes in a Binary Search Tree (BST) and a target integer + value and returns the closest value to that target value contained in the BST. + +Sample Input : 12 + + 10 + / \ + 5 15 + / \ / \ + 2 5 13 22 + / \ +1 14 +Output : 13 + + Explanation: + + The code defines a BST (Binary Search Tree) class with member functions to find the closest value to a given target value. + The findClosestValue function is the public interface that initializes the closest value with the root value and calls + the helper function. The findClosestValueHelper function recursively traverses the tree, updating the closest value based + on the absolute difference between the target and the current node value. It then continues the search in the appropriate + subtree based on the comparison with the target value. The absDiff function calculates the absolute difference between two + integers. + + Time and Space complexity: + + Average: O(log(n)) time | O(1) space - where n is the number of nodes in the BST + Worst: O(n) time | O(1) space - where n is the number of nodes in the BST +*/ +class BST { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } + + findClosestValue(target) { + // Call the helper function with the initial closest value as the root value + return this._findClosestValueHelper(target, this.value); + } + + _findClosestValueHelper(target, closest) { + // Compare the absolute difference between the target and the current closest value + // with the absolute difference between the target and the current node value + if (Math.abs(target - closest) > Math.abs(target - this.value)) { + closest = this.value; + } + + // Look for the target in the left subtree if the target is smaller than the current node value + if (target < this.value && this.left) { + return this.left._findClosestValueHelper(target, closest); + } + // Look for the target in the right subtree if the target is greater than the current node value + else if (target > this.value && this.right) { + return this.right._findClosestValueHelper(target, closest); + } + + return closest; + } +} + +// Create a BST instance +const bst = new BST(10); +bst.left = new BST(5); +bst.right = new BST(15); +bst.left.left = new BST(2); +bst.left.right = new BST(5); +bst.right.left = new BST(13); +bst.right.right = new BST(22); +bst.left.left.left = new BST(1); +bst.right.left.right = new BST(14); + +// Find the closest value to the target +const target = 12; +const closestValue = bst.findClosestValue(target); + +// Print the result +console.log(`The closest value to ${target} is ${closestValue}`); From 82090fa941f48d00976987170dce23c7e1b673c9 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 28 Jun 2023 00:06:38 +0530 Subject: [PATCH 1483/1894] Update stacks_with_queues.py --- Stacks/stacks_with_queues.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Stacks/stacks_with_queues.py b/Stacks/stacks_with_queues.py index d258c85c..09cf95f8 100644 --- a/Stacks/stacks_with_queues.py +++ b/Stacks/stacks_with_queues.py @@ -57,3 +57,26 @@ def size(self): Return the number of items in the stack. """ return self.queue2.qsize() + +''' +__init__() - This method initializes the stack by creating two queues. Since no operations are performed on the queues in this method, the time complexity is O(1). + +push(item) - This method adds an item to the top of the stack. Initially, it adds the item to an empty queue, which takes O(1) time. Then, it moves all the elements from the other queue to the empty queue, which takes O(n) time, where n is the number of elements in the stack. Finally, it swaps the names of the two queues, which is a constant time operation. Therefore, the overall time complexity of push(item) is O(n). + +pop() - This method removes and returns the item at the top of the stack. It checks if the stack is empty, which takes O(1) time. Then, it removes and returns the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of pop() is O(1). + +top() - This method returns the item at the top of the stack without removing it. It checks if the stack is empty, which takes O(1) time. Then, it retrieves the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of top() is O(1). + +is_empty() - This method checks if the stack is empty by checking if the queue is empty, which takes O(1) time. Therefore, the time complexity of is_empty() is O(1). + +size() - This method returns the number of items in the stack by returning the size of the queue, which is a constant time operation. Therefore, the time complexity of size() is O(1). + +the time complexity of the operations in the Stack class implemented using queues is as follows: + +push(item): O(n) +pop(): O(1) +top(): O(1) +is_empty(): O(1) +size(): O(1) + +''' From 9a7c4e721de38c153191af3eb032ea45c7084be9 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 28 Jun 2023 00:10:44 +0530 Subject: [PATCH 1484/1894] Create stacks_with_queues.cpp closes issue number #261 --- Stacks/stacks_with_queues.cpp | 65 +++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Stacks/stacks_with_queues.cpp diff --git a/Stacks/stacks_with_queues.cpp b/Stacks/stacks_with_queues.cpp new file mode 100644 index 00000000..eb94a2a7 --- /dev/null +++ b/Stacks/stacks_with_queues.cpp @@ -0,0 +1,65 @@ +#include + +class MyStack { +private: + std::queue queue1; + std::queue queue2; + +public: + MyStack() { + + } + + void push(int x) { + // Add the new element to queue2 + queue2.push(x); + + // Move all elements from queue1 to queue2 + while (!queue1.empty()) { + queue2.push(queue1.front()); + queue1.pop(); + } + + // Swap the names of the two queues + std::swap(queue1, queue2); + } + + int pop() { + if (queue1.empty()) { + throw std::runtime_error("Stack is empty"); + } + + int topElement = queue1.front(); + queue1.pop(); + return topElement; + } + + int top() { + if (queue1.empty()) { + throw std::runtime_error("Stack is empty"); + } + + return queue1.front(); + } + + bool empty() { + return queue1.empty(); + } +}; + + +/* +This implementation maintains two queues, queue1 and queue2, where queue1 always holds the elements in the stack. When pushing a new element, it is added to queue2, and then all the elements from queue1 are moved to queue2, making the newly added element the front/top of the stack. Finally, the names of the two queues are swapped to maintain the order. + +The pop() function removes and returns the front/top element of queue1, while the top() function returns the front/top element without removing it. Both functions check if queue1 is empty and throw an exception if the stack is empty. + +The empty() function checks if queue1 is empty and returns true if it is, indicating an empty stack. + +Time complexity + +push(x): O(n) +pop(): O(1) +top(): O(1) +empty(): O(1) +*/ + From ca28719bf3fd91b36c7479de21dfd3e3a780f2cd Mon Sep 17 00:00:00 2001 From: Mudit Jain <97677133+Mudit-Jxin7@users.noreply.github.com> Date: Wed, 28 Jun 2023 13:20:13 +0530 Subject: [PATCH 1485/1894] Create min_steps_to_make_string_pallindrome.go --- .../min_steps_to_make_string_pallindrome.go | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Dynamic Programming/min_steps_to_make_string_pallindrome.go diff --git a/Dynamic Programming/min_steps_to_make_string_pallindrome.go b/Dynamic Programming/min_steps_to_make_string_pallindrome.go new file mode 100644 index 00000000..360d3812 --- /dev/null +++ b/Dynamic Programming/min_steps_to_make_string_pallindrome.go @@ -0,0 +1,70 @@ +/* + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) +*/ + +package main + +import ( + "fmt" +) + +func lcs(s1, s2 string) int { + n, m := len(s1), len(s2) + dp := make([][]int, n+1) + for i := 0; i <= n; i++ { + dp[i] = make([]int, m+1) + } + + for i := 1; i <= n; i++ { + for j := 1; j <= m; j++ { + if s1[i-1] == s2[j-1] { + dp[i][j] = 1 + dp[i-1][j-1] + } else { + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + } + } + } + + return dp[n][m] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func minInsertions(s string) int { + reverseS := "" + for i := len(s) - 1; i >= 0; i-- { + reverseS += string(s[i]) + } + + lcsLength := lcs(s, reverseS) + return len(s) - lcsLength +} + +func main() { + var s string + fmt.Scanln(&s) + ans := minInsertions(s) + fmt.Println(ans) +} From 8c32cbb15af4480d4dbb57c582ecf83dc1ab954d Mon Sep 17 00:00:00 2001 From: Mudit Jain <97677133+Mudit-Jxin7@users.noreply.github.com> Date: Wed, 28 Jun 2023 13:20:37 +0530 Subject: [PATCH 1486/1894] Rename min_steps_to_make_string_pallindrome.go to min_steps_to_make_string_palindrome.go --- ...ring_pallindrome.go => min_steps_to_make_string_palindrome.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{min_steps_to_make_string_pallindrome.go => min_steps_to_make_string_palindrome.go} (100%) diff --git a/Dynamic Programming/min_steps_to_make_string_pallindrome.go b/Dynamic Programming/min_steps_to_make_string_palindrome.go similarity index 100% rename from Dynamic Programming/min_steps_to_make_string_pallindrome.go rename to Dynamic Programming/min_steps_to_make_string_palindrome.go From d8c4df88e0c290da22476119f72c5f2a0e753039 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 28 Jun 2023 14:32:29 +0530 Subject: [PATCH 1487/1894] Update Ladder_Pattern.java --- Famous Algorithms/Ladder_Pattern.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Famous Algorithms/Ladder_Pattern.java b/Famous Algorithms/Ladder_Pattern.java index 59d71f43..d49394fa 100644 --- a/Famous Algorithms/Ladder_Pattern.java +++ b/Famous Algorithms/Ladder_Pattern.java @@ -1,3 +1,11 @@ +/* +Problem: Given an integer N, the task is to print the ladder with N steps using ‘*’. The ladder will be with the gap of 3 spaces between two side rails. + +Time complexity: O(N) for given input N steps +Auxiliary Space: O(1) as constant extra space is used + +*/ + import java.util.Scanner; public class Ladder_Pattern { From f7a803373be2bdb6a3d81b91aa6ab0abb0ffc458 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:18:21 +0530 Subject: [PATCH 1488/1894] Create search_2d_sorted_array.py >>added time and space complexity >>added i/o samples --- search_2d_sorted_array.py | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 search_2d_sorted_array.py diff --git a/search_2d_sorted_array.py b/search_2d_sorted_array.py new file mode 100644 index 00000000..50aa6a32 --- /dev/null +++ b/search_2d_sorted_array.py @@ -0,0 +1,61 @@ +''' +Date:28/6/23 +About:Search in 2D sorted array in Python + +Input: +You are given an m x n integer matrix matrix with the following two properties: +Each row is sorted in non-decreasing order. +The first integer of each row is greater than the last integer of the previous row. +Given an integer target, return true if target is in matrix or false otherwise. + +Time Complexity: +You must write a solution in O(log(m * n)) time complexity. +Space Complexity:O(1) + +//Example 1: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true +//Example 2: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false + +//Explanation +The searchMatrix function takes two parameters: matrix (a 2D array) and target (the value to be searched). +It initializes the variable m to store the length of the matrix (number of rows). +It then iterates through each row of the matrix using a for loop. +Inside the outer loop, there's another nested loop that iterates through each element of the current row. +It checks if the current element is equal to the target value. +If a match is found, it immediately returns True, indicating that the target is present in the matrix. +Else the function returns False, indicating that the target is not present in the matrix. +In the main section, an instance of the Solution class is created. +A sample matrix is defined with some values. +The target value is set to 5. +The searchMatrix function is called with the matrix and target as arguments, and the result is stored in the variable found. +Finally, it prints whether the target was found or not. + +''' +class Solution: + def searchMatrix(self, matrix, target): + m = len(matrix) + for i in range(m): + for j in range(len(matrix[i])): + if matrix[i][j] == target: + return True + return False + +if __name__ == "__main__": + solution = Solution() + matrix = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ] + target = 5 + + found = solution.searchMatrix(matrix, target) + print("Target found:", found) + + + + + From 21b89079667722db2124d2c0fcafa2ab793a340b Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 28 Jun 2023 18:39:11 +0530 Subject: [PATCH 1489/1894] Update stacks_with_queues.cpp --- Stacks/stacks_with_queues.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Stacks/stacks_with_queues.cpp b/Stacks/stacks_with_queues.cpp index eb94a2a7..e68fcffb 100644 --- a/Stacks/stacks_with_queues.cpp +++ b/Stacks/stacks_with_queues.cpp @@ -1,3 +1,20 @@ +/* +This implementation maintains two queues, queue1 and queue2, where queue1 always holds the elements in the stack. When pushing a new element, it is added to queue2, and then all the elements from queue1 are moved to queue2, making the newly added element the front/top of the stack. Finally, the names of the two queues are swapped to maintain the order. + +The pop() function removes and returns the front/top element of queue1, while the top() function returns the front/top element without removing it. Both functions check if queue1 is empty and throw an exception if the stack is empty. + +The empty() function checks if queue1 is empty and returns true if it is, indicating an empty stack. + +Time complexity + +push(x): O(n) +pop(): O(1) +top(): O(1) +empty(): O(1) +*/ + + + #include class MyStack { From 00992ddcae3a92ed74623c1e66098ff4f1c9e315 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 28 Jun 2023 18:40:16 +0530 Subject: [PATCH 1490/1894] Update stacks_with_queues.py --- Stacks/stacks_with_queues.py | 44 +++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/Stacks/stacks_with_queues.py b/Stacks/stacks_with_queues.py index 09cf95f8..9cc3a655 100644 --- a/Stacks/stacks_with_queues.py +++ b/Stacks/stacks_with_queues.py @@ -1,3 +1,26 @@ +''' +__init__() - This method initializes the stack by creating two queues. Since no operations are performed on the queues in this method, the time complexity is O(1). + +push(item) - This method adds an item to the top of the stack. Initially, it adds the item to an empty queue, which takes O(1) time. Then, it moves all the elements from the other queue to the empty queue, which takes O(n) time, where n is the number of elements in the stack. Finally, it swaps the names of the two queues, which is a constant time operation. Therefore, the overall time complexity of push(item) is O(n). + +pop() - This method removes and returns the item at the top of the stack. It checks if the stack is empty, which takes O(1) time. Then, it removes and returns the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of pop() is O(1). + +top() - This method returns the item at the top of the stack without removing it. It checks if the stack is empty, which takes O(1) time. Then, it retrieves the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of top() is O(1). + +is_empty() - This method checks if the stack is empty by checking if the queue is empty, which takes O(1) time. Therefore, the time complexity of is_empty() is O(1). + +size() - This method returns the number of items in the stack by returning the size of the queue, which is a constant time operation. Therefore, the time complexity of size() is O(1). + +the time complexity of the operations in the Stack class implemented using queues is as follows: + +push(item): O(n) +pop(): O(1) +top(): O(1) +is_empty(): O(1) +size(): O(1) + +''' + from queue import Queue class Stack: @@ -58,25 +81,4 @@ def size(self): """ return self.queue2.qsize() -''' -__init__() - This method initializes the stack by creating two queues. Since no operations are performed on the queues in this method, the time complexity is O(1). - -push(item) - This method adds an item to the top of the stack. Initially, it adds the item to an empty queue, which takes O(1) time. Then, it moves all the elements from the other queue to the empty queue, which takes O(n) time, where n is the number of elements in the stack. Finally, it swaps the names of the two queues, which is a constant time operation. Therefore, the overall time complexity of push(item) is O(n). - -pop() - This method removes and returns the item at the top of the stack. It checks if the stack is empty, which takes O(1) time. Then, it removes and returns the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of pop() is O(1). - -top() - This method returns the item at the top of the stack without removing it. It checks if the stack is empty, which takes O(1) time. Then, it retrieves the front element of the non-empty queue, which is a constant time operation. Therefore, the overall time complexity of top() is O(1). - -is_empty() - This method checks if the stack is empty by checking if the queue is empty, which takes O(1) time. Therefore, the time complexity of is_empty() is O(1). - -size() - This method returns the number of items in the stack by returning the size of the queue, which is a constant time operation. Therefore, the time complexity of size() is O(1). - -the time complexity of the operations in the Stack class implemented using queues is as follows: -push(item): O(n) -pop(): O(1) -top(): O(1) -is_empty(): O(1) -size(): O(1) - -''' From 77c4ce06c03eabbd160c8c209abca37a1eab4345 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 28 Jun 2023 18:41:01 +0530 Subject: [PATCH 1491/1894] Update stacks_with_queues.cpp --- Stacks/stacks_with_queues.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Stacks/stacks_with_queues.cpp b/Stacks/stacks_with_queues.cpp index e68fcffb..6931018a 100644 --- a/Stacks/stacks_with_queues.cpp +++ b/Stacks/stacks_with_queues.cpp @@ -64,19 +64,3 @@ class MyStack { } }; - -/* -This implementation maintains two queues, queue1 and queue2, where queue1 always holds the elements in the stack. When pushing a new element, it is added to queue2, and then all the elements from queue1 are moved to queue2, making the newly added element the front/top of the stack. Finally, the names of the two queues are swapped to maintain the order. - -The pop() function removes and returns the front/top element of queue1, while the top() function returns the front/top element without removing it. Both functions check if queue1 is empty and throw an exception if the stack is empty. - -The empty() function checks if queue1 is empty and returns true if it is, indicating an empty stack. - -Time complexity - -push(x): O(n) -pop(): O(1) -top(): O(1) -empty(): O(1) -*/ - From 60e75d4e23a86ecaecbf70adc9747b5140a8c1a1 Mon Sep 17 00:00:00 2001 From: Mudit Jain <97677133+Mudit-Jxin7@users.noreply.github.com> Date: Wed, 28 Jun 2023 23:05:29 +0530 Subject: [PATCH 1492/1894] Added comments --- .../min_steps_to_make_string_palindrome.go | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Dynamic Programming/min_steps_to_make_string_palindrome.go b/Dynamic Programming/min_steps_to_make_string_palindrome.go index 360d3812..040086c5 100644 --- a/Dynamic Programming/min_steps_to_make_string_palindrome.go +++ b/Dynamic Programming/min_steps_to_make_string_palindrome.go @@ -27,22 +27,22 @@ import ( func lcs(s1, s2 string) int { n, m := len(s1), len(s2) - dp := make([][]int, n+1) + dp := make([][]int, n+1) // Create a 2D matrix dp to store the lengths of LCS for i := 0; i <= n; i++ { dp[i] = make([]int, m+1) } for i := 1; i <= n; i++ { for j := 1; j <= m; j++ { - if s1[i-1] == s2[j-1] { - dp[i][j] = 1 + dp[i-1][j-1] + if s1[i-1] == s2[j-1] { // If characters at the current positions match + dp[i][j] = 1 + dp[i-1][j-1] // Increase the length of LCS by 1 } else { - dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) // Take the maximum length from the previous positions } } } - return dp[n][m] + return dp[n][m] // Return the length of the LCS of s1 and s2 } func max(a, b int) int { @@ -55,16 +55,16 @@ func max(a, b int) int { func minInsertions(s string) int { reverseS := "" for i := len(s) - 1; i >= 0; i-- { - reverseS += string(s[i]) + reverseS += string(s[i]) // Reverse the string s } - lcsLength := lcs(s, reverseS) - return len(s) - lcsLength + lcsLength := lcs(s, reverseS) // Find the length of the LCS of s and its reverse + return len(s) - lcsLength // Return the number of insertions required to make s a palindrome } func main() { var s string - fmt.Scanln(&s) - ans := minInsertions(s) - fmt.Println(ans) + fmt.Scanln(&s) // Read input string + ans := minInsertions(s) // Calculate the minimum number of insertions required + fmt.Println(ans) // Print the result } From da319af3315fa8958c01b88e405945dacb850fa8 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Thu, 29 Jun 2023 08:16:53 +0530 Subject: [PATCH 1493/1894] Update search_2d_sorted_array.py >>provided optimal solution --- search_2d_sorted_array.py | 74 ++++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 29 deletions(-) diff --git a/search_2d_sorted_array.py b/search_2d_sorted_array.py index 50aa6a32..f5117b30 100644 --- a/search_2d_sorted_array.py +++ b/search_2d_sorted_array.py @@ -20,40 +20,56 @@ Output: false //Explanation -The searchMatrix function takes two parameters: matrix (a 2D array) and target (the value to be searched). -It initializes the variable m to store the length of the matrix (number of rows). -It then iterates through each row of the matrix using a for loop. -Inside the outer loop, there's another nested loop that iterates through each element of the current row. -It checks if the current element is equal to the target value. -If a match is found, it immediately returns True, indicating that the target is present in the matrix. -Else the function returns False, indicating that the target is not present in the matrix. -In the main section, an instance of the Solution class is created. -A sample matrix is defined with some values. -The target value is set to 5. -The searchMatrix function is called with the matrix and target as arguments, and the result is stored in the variable found. -Finally, it prints whether the target was found or not. +The method takes two parameters: matrix, which represents the sorted matrix, and target, which is the value we want to find in the matrix. + +The code initializes variables nRows and nCols to store the number of rows and columns in the matrix, respectively. + +The starting position for the search is set to the bottom-left corner of the matrix (row = nRows - 1, col = 0). + +The code enters a while loop that continues as long as the current row index (row) is within the bounds of the matrix (0 to nRows - 1 +and the current column index (col) is within the bounds of the matrix (0 to nCols - 1). + +Inside the loop, the code retrieves the value at the current position in the matrix (val = matrix[row][col]). + +If the current value (val) == value, the method returns True, indicating that the target is found in the matrix. + +If the current value (val) < target value, it means the target can only be found in the rows above the current row. +Therefore, the column index (col) is incremented to move to the next column. + +If the current value (val) >target value, it means the target can only be found in the columns to the left of the current column. +Therefore, the row index (row) is decremented to move to the previous row. + +If the loop completes without finding the target value, the method returns False. ''' -class Solution: +class Solution(object): def searchMatrix(self, matrix, target): - m = len(matrix) - for i in range(m): - for j in range(len(matrix[i])): - if matrix[i][j] == target: - return True + nRows = len(matrix) + nCols = len(matrix[0]) + row = nRows - 1 + col = 0 + while 0 <= row < nRows and 0 <= col < nCols: + val = matrix[row][col] + if val == target: + return True + elif val < target: + col += 1 + else: + row -= 1 return False -if __name__ == "__main__": - solution = Solution() - matrix = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] - target = 5 - - found = solution.searchMatrix(matrix, target) - print("Target found:", found) + +# Create an instance of the Solution class +solution = Solution() + +# Define the matrix and target value +matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] +target = 3 + +# Call the searchMatrix method and print the result +result = solution.searchMatrix(matrix, target) +print(result) + From 2022c8348a1e4e75080a76014658bd0444db1c3b Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Thu, 29 Jun 2023 11:03:20 +0530 Subject: [PATCH 1494/1894] adding first_missing_positve in hash table --- Hash Table/first_missing_positve.py.py | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Hash Table/first_missing_positve.py.py diff --git a/Hash Table/first_missing_positve.py.py b/Hash Table/first_missing_positve.py.py new file mode 100644 index 00000000..2e912df4 --- /dev/null +++ b/Hash Table/first_missing_positve.py.py @@ -0,0 +1,36 @@ +# first positive missing in python +''' +To find the smallest missing positive integer in an unsorted integer array nums with the given time and space constraints, +you can utilize the concept of in-place swapping and indexing. + +Explanation:- + + -> Iterate through the array nums and ignore any non-positive numbers (i.e., negative numbers and zero). + Also, ignore numbers greater than the length of the array since they cannot be the smallest missing positive integer. + + -> For each positive number num encountered, find its correct index targetIndex as num - 1. + + -> Check if the number at index targetIndex is already in its correct place or not. If it is not, + swap the numbers at indices i and targetIndex to move num to its correct place. Continue this swapping + process until the number at index i is either non-positive or already in its correct place. + + -> After completing the iteration, perform a second pass through the array. The first index i that does not + contain the value i + 1 represents the smallest missing positive integer. Return i + 1. +''' + +def firstMissingPositive(nums): + n = len(nums) + + # Step 1: Move positive numbers to their correct positions + for i in range(n): + while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: + nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] + + # Step 2: Find the first missing positive + for i in range(n): + if nums[i] != i + 1: + return i + 1 + + # If all positive integers are present, return n + 1 + return n + 1 + From f8d75d2230a04928230d95a0bcfe3530f1d18a0f Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Thu, 29 Jun 2023 11:49:46 +0530 Subject: [PATCH 1495/1894] Delete first_missing_positve.py.py --- Hash Table/first_missing_positve.py.py | 36 -------------------------- 1 file changed, 36 deletions(-) delete mode 100644 Hash Table/first_missing_positve.py.py diff --git a/Hash Table/first_missing_positve.py.py b/Hash Table/first_missing_positve.py.py deleted file mode 100644 index 2e912df4..00000000 --- a/Hash Table/first_missing_positve.py.py +++ /dev/null @@ -1,36 +0,0 @@ -# first positive missing in python -''' -To find the smallest missing positive integer in an unsorted integer array nums with the given time and space constraints, -you can utilize the concept of in-place swapping and indexing. - -Explanation:- - - -> Iterate through the array nums and ignore any non-positive numbers (i.e., negative numbers and zero). - Also, ignore numbers greater than the length of the array since they cannot be the smallest missing positive integer. - - -> For each positive number num encountered, find its correct index targetIndex as num - 1. - - -> Check if the number at index targetIndex is already in its correct place or not. If it is not, - swap the numbers at indices i and targetIndex to move num to its correct place. Continue this swapping - process until the number at index i is either non-positive or already in its correct place. - - -> After completing the iteration, perform a second pass through the array. The first index i that does not - contain the value i + 1 represents the smallest missing positive integer. Return i + 1. -''' - -def firstMissingPositive(nums): - n = len(nums) - - # Step 1: Move positive numbers to their correct positions - for i in range(n): - while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: - nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] - - # Step 2: Find the first missing positive - for i in range(n): - if nums[i] != i + 1: - return i + 1 - - # If all positive integers are present, return n + 1 - return n + 1 - From 7e291b5b485c5bc768b90b8016b9202d5f94682b Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Thu, 29 Jun 2023 11:50:33 +0530 Subject: [PATCH 1496/1894] Add files via upload --- Hash Table/first_missing_positve.py.py | 57 ++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Hash Table/first_missing_positve.py.py diff --git a/Hash Table/first_missing_positve.py.py b/Hash Table/first_missing_positve.py.py new file mode 100644 index 00000000..1671ca17 --- /dev/null +++ b/Hash Table/first_missing_positve.py.py @@ -0,0 +1,57 @@ +# first positive missing in python +''' +To find the smallest missing positive integer in an unsorted integer array nums with the given time and space constraints, +you can utilize the concept of in-place swapping and indexing. + +Explanation:- + + -> Iterate through the array nums and ignore any non-positive numbers (i.e., negative numbers and zero). + Also, ignore numbers greater than the length of the array since they cannot be the smallest missing positive integer. + + -> For each positive number num encountered, find its correct index targetIndex as num - 1. + + -> Check if the number at index targetIndex is already in its correct place or not. If it is not, + swap the numbers at indices i and targetIndex to move num to its correct place. Continue this swapping + process until the number at index i is either non-positive or already in its correct place. + + -> After completing the iteration, perform a second pass through the array. The first index i that does not + contain the value i + 1 represents the smallest missing positive integer. Return i + 1. +''' + +# Time complexity O(n) and Space complexity O(1). + +'''Examples- + +Example 1: +Input: nums = [1, 2, 0] +Output: 3 +Explanation: The smallest missing positive integer in the array is 3. + +Example 2: +Input: nums = [3, 4, -1, 1] +Output: 2 +Explanation: The smallest missing positive integer in the array is 2. + +Example 3: +Input: nums = [7, 8, 9, 11, 12] +Output: 1 +Explanation: The smallest missing positive integer in the array is 1. + +''' + +def firstMissingPositive(nums): + n = len(nums) + + # Step 1: Move positive numbers to their correct positions + for i in range(n): + while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: + nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] + + # Step 2: Find the first missing positive + for i in range(n): + if nums[i] != i + 1: + return i + 1 + + # If all positive integers are present, return n + 1 + return n + 1 + From 52a44465685f034c3c40edd6110c95761e3d6f3d Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Thu, 29 Jun 2023 12:10:37 +0530 Subject: [PATCH 1497/1894] Add first missing positive in js --- Hash Table/first_missing_positve.js | 74 +++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Hash Table/first_missing_positve.js diff --git a/Hash Table/first_missing_positve.js b/Hash Table/first_missing_positve.js new file mode 100644 index 00000000..a465ac76 --- /dev/null +++ b/Hash Table/first_missing_positve.js @@ -0,0 +1,74 @@ +// First Missing Positve +/* + -> The firstMissingPositive function takes an array of integers called nums as input. + + -> The function first determines the length of the array nums and assigns it to the variable n. + + -> Step 1: Move positive numbers to their correct positions + - The algorithm iterates through each element of the array using a for loop. + - Inside the loop, it checks if the current number (nums[i]) is positive and within the range of 1 to n. + - If the number is valid, it checks whether the number at its correct position (nums[nums[i] - 1]) is + different from the current number itself. This ensures that the number is not already in its correct place. + - If the numbers are different, it swaps the current number with the number at its correct position using + array destructuring ([nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]). This moves the current + number to its correct place in the array. + - The swapping process continues until the number at index i is either non-positive or already in its correct + place. This step ensures that all positive numbers are placed in their respective positions. + + Step 2: Find the first missing positive + - After completing the first pass through the array, the algorithm performs a second pass using another for loop. + - Inside the loop, it checks if the number at index i is equal to i + 1. If not, it means that i + 1 is + missing from the array. + - In this case, the algorithm returns i + 1 as the smallest missing positive integer. + + -> If all positive integers from 1 to n are present in the array, the function reaches the end without finding a + missing positive. In this case, it returns n + 1 as the smallest missing positive integer. + + + +The algorithm meets the given time complexity requirement of O(n) because it performs two passes through the array, +and each pass visits each element once. It also satisfies the space complexity requirement of O(1) since it modifies +the input array in-place without using any additional data structures. +*/ + + +/* +Examples- + +Example 1: +Input: nums = [1, 2, 0] +Output: 3 +Explanation: The smallest missing positive integer in the array is 3. + +Example 2: +Input: nums = [3, 4, -1, 1] +Output: 2 +Explanation: The smallest missing positive integer in the array is 2. + +Example 3: +Input: nums = [7, 8, 9, 11, 12] +Output: 1 +Explanation: The smallest missing positive integer in the array is 1. +*/ + + +function firstMissingPositive(nums) { + const n = nums.length; + + // Step 1: Move positive numbers to their correct positions + for (let i = 0; i < n; i++) { + while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) { + [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; + } + } + + // Step 2: Find the first missing positive + for (let i = 0; i < n; i++) { + if (nums[i] !== i + 1) { + return i + 1; + } + } + + // If all positive integers are present, return n + 1 + return n + 1; +} \ No newline at end of file From 223e090dec5145b86009e2410236131b7c6decb0 Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Thu, 29 Jun 2023 16:49:56 +0530 Subject: [PATCH 1498/1894] adding first missing positive in go --- Hash Table/first_missing_positve.go | 68 +++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Hash Table/first_missing_positve.go diff --git a/Hash Table/first_missing_positve.go b/Hash Table/first_missing_positve.go new file mode 100644 index 00000000..143d535a --- /dev/null +++ b/Hash Table/first_missing_positve.go @@ -0,0 +1,68 @@ +/* + -> The firstMissingPositive function takes a slice of integers called nums as input. + + -> The function determines the length of the slice nums and assigns it to the variable n. + + -> Step 1: Move positive numbers to their correct positions + - The algorithm iterates through each element of the slice using a for loop. + - Inside the loop, it checks if the current number (nums[i]) is positive and within the range of 1 to n. + - If the number is valid, it checks whether the number at its correct position (nums[nums[i]-1]) is different + from the current number itself. This ensures that the number is not already in its correct place. + - If the numbers are different, it swaps the current number with the number at its correct position using the + Go idiomatic way of swapping values (nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]). + - The swapping process continues until the number at index i is either non-positive or already in its correct + place. This step ensures that all positive numbers are placed in their respective positions. + + -> Step 2: Find the first missing positive + After completing the first pass through the slice, the algorithm performs a second pass using another for loop. + Inside the loop, it checks if the number at index i is equal to i + 1. If not, it means that i + 1 is missing from the slice. + In this case, the algorithm returns i + 1 as the smallest missing positive integer. + + -> If all positive integers from 1 to n are present in the slice, the function reaches the end without finding a + missing positive. In this case, it returns n + 1 as the smallest missing positive integer. + +The Go implementation of the algorithm ensures that it modifies the input slice nums in-place without using any +additional data structures, meeting the O(1) auxiliary space requirement. The time complexity of the algorithm +remains O(n) as it performs two passes through the slice, visiting each element once. +*/ + +/* +Example-> + +Example 1: +Input: nums := []int{1, 2, 0} +Output: 3 +Explanation: The smallest missing positive integer in the slice is 3. + +Example 2: +Input: nums := []int{3, 4, -1, 1} +Output: 2 +Explanation: The smallest missing positive integer in the slice is 2. + +Example 3: +Input: nums := []int{7, 8, 9, 11, 12} +Output: 1 +Explanation: The smallest missing positive integer in the slice is 1. + +*/ + +func firstMissingPositive(nums []int) int { + n := len(nums) + + // Step 1: Move positive numbers to their correct positions + for i := 0; i < n; i++ { + for nums[i] > 0 && nums[i] <= n && nums[nums[i]-1] != nums[i] { + nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] + } + } + + // Step 2: Find the first missing positive + for i := 0; i < n; i++ { + if nums[i] != i+1 { + return i + 1 + } + } + + // If all positive integers are present, return n + 1 + return n + 1 +} From ce1d9ceae86405ff5be28fdcf10cc7e6b0e963c0 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 29 Jun 2023 17:15:24 +0530 Subject: [PATCH 1499/1894] Create find_Optimal Partition of String.go closes #1428 --- .../find_Optimal Partition of String.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Hash Table/find_Optimal Partition of String.go diff --git a/Hash Table/find_Optimal Partition of String.go b/Hash Table/find_Optimal Partition of String.go new file mode 100644 index 00000000..2c42fbc7 --- /dev/null +++ b/Hash Table/find_Optimal Partition of String.go @@ -0,0 +1,64 @@ +/*The function isPalindrome checks if a given substring of s is a palindrome. The minCut function utilizes dynamic programming to find the minimum cuts needed for each substring. It initializes a table cuts to store the minimum cuts for each position in the string. It also creates a palindrome table to check if a substring is a palindrome or not. + +The algorithm iterates through the string s from left to right and checks all possible substrings to find palindromes. If a palindrome is found, it updates the cuts table based on the previous cuts. Finally, it returns the minimum cuts needed for the entire string. + +In the main function, we provide an example string "aabba" and print the minimum cuts required. You can replace "aabba" with your own string to find its optimal partition. +*/ + + + + +func min(x, y int) int { + if x < y { + return x + } + return y +} + +func isPalindrome(s string, i, j int) bool { + for i < j { + if s[i] != s[j] { + return false + } + i++ + j-- + } + return true +} + +func minCut(s string) int { + n := len(s) + if n <= 1 { + return 0 + } + + // Create a table to store the minimum cuts for each substring + cuts := make([]int, n) + palindrome := make([][]bool, n) + + for i := 0; i < n; i++ { + palindrome[i] = make([]bool, n) + cuts[i] = i + } + + for j := 0; j < n; j++ { + for i := 0; i <= j; i++ { + if s[i] == s[j] && (j-i <= 1 || palindrome[i+1][j-1]) { + palindrome[i][j] = true + if i > 0 { + cuts[j] = min(cuts[j], cuts[i-1]+1) + } else { + cuts[j] = 0 + } + } + } + } + + return cuts[n-1] +} + +func main() { + s := "aabba" + minimumCuts := minCut(s) + fmt.Println("Minimum cuts:", minimumCuts) +} From cd7aa7318977e105f68f385cd07b18eef45ebdc7 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 29 Jun 2023 17:40:34 +0530 Subject: [PATCH 1500/1894] Update find_Optimal Partition of String.go --- Hash Table/find_Optimal Partition of String.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Hash Table/find_Optimal Partition of String.go b/Hash Table/find_Optimal Partition of String.go index 2c42fbc7..21d47e09 100644 --- a/Hash Table/find_Optimal Partition of String.go +++ b/Hash Table/find_Optimal Partition of String.go @@ -3,6 +3,14 @@ The algorithm iterates through the string s from left to right and checks all possible substrings to find palindromes. If a palindrome is found, it updates the cuts table based on the previous cuts. Finally, it returns the minimum cuts needed for the entire string. In the main function, we provide an example string "aabba" and print the minimum cuts required. You can replace "aabba" with your own string to find its optimal partition. + +Time Complexity: +The outer loop iterates through the string s once, and for each character, it checks all possible substrings. Therefore, the time complexity of the solution is O(n^2), where n is the length of the string. + +Space Complexity: +The space complexity is determined by the two tables used: cuts and palindrome. Both tables have a size of n, where n is the length of the string s. Therefore, the space complexity is O(n). + +Overall, the solution has a time complexity of O(n^2) and a space complexity of O(n). */ From 0b9ae5d55a28591059d3fec6b51fd5ea57ce66e9 Mon Sep 17 00:00:00 2001 From: erennatala Date: Thu, 29 Jun 2023 20:38:41 +0300 Subject: [PATCH 1501/1894] Add solution for finding first missing positive integer in Java (#1516) --- Hash Table/add_first_missing_positive.java | 55 ++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Hash Table/add_first_missing_positive.java diff --git a/Hash Table/add_first_missing_positive.java b/Hash Table/add_first_missing_positive.java new file mode 100644 index 00000000..d5f198ee --- /dev/null +++ b/Hash Table/add_first_missing_positive.java @@ -0,0 +1,55 @@ +/* + Given an unsorted integer array nums, return the smallest missing positive integer. + You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. + + Sample Input: [3, 4, -1, 1] + Sample Output: 2 + + Explanation: + This code implements a solution to find the first missing positive integer from an unsorted array. The function first separates positive and negative numbers. + It then considers the array with only positive numbers, and marks the index corresponding to every positive number in this array. + The first index which is unmarked corresponds to the first missing positive number. + + This solution uses the array itself as a pseudo-hash table where the keys are the array indices, and the values are whether or not a positive integer is present in the array. + By using the array in this way, we are able to find the solution in O(1) auxiliary space. + + Time complexity: O(n) + Space complexity: O(1) +*/ + +public class AddFirstMissingPositive{ + public int firstMissingPositive(int[] nums) { + int n = nums.length; + + // Mark numbers that are out of range as 0 + for(int i = 0; i < n; i++) { + if(nums[i] <= 0 || nums[i] > n) { + nums[i] = 0; + } + } + + // Mark the index corresponding to the value of each number + for(int i = 0; i < n; i++) { + int num = Math.abs(nums[i]); + + if(num > 0) { + num--; // subtract 1 because of 0-based indexing + + // Mark as negative + if(nums[num] > 0) { + nums[num] = -nums[num]; + } + } + } + + // Find the first number greater than 0 + for(int i = 0; i < n; i++) { + if(nums[i] >= 0) { + return i + 1; // add 1 because of 0-based indexing + } + } + + // If no number is missing + return n + 1; + } +} From a1fd8f1d5f58d637f764ff78cc7ded382c6d30fe Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Fri, 30 Jun 2023 00:05:55 +0530 Subject: [PATCH 1502/1894] Update Ladder_Pattern.java --- Famous Algorithms/Ladder_Pattern.java | 75 +++++++++++++++++---------- 1 file changed, 49 insertions(+), 26 deletions(-) diff --git a/Famous Algorithms/Ladder_Pattern.java b/Famous Algorithms/Ladder_Pattern.java index d49394fa..4ef6518b 100644 --- a/Famous Algorithms/Ladder_Pattern.java +++ b/Famous Algorithms/Ladder_Pattern.java @@ -1,34 +1,57 @@ /* Problem: Given an integer N, the task is to print the ladder with N steps using ‘*’. The ladder will be with the gap of 3 spaces between two side rails. +Approach: +First, we take input from the user for the number of steps in the ladder. +We then iterate from 1 to N, where N is the number of steps, to print each step of the ladder. +Inside the loop, we call the printSideRail() function to print a side rail at the beginning of each step. +We then call the printStep(stepNumber) function to print the actual step. This function prints stepNumber asterisks with 3 spaces between each asterisk. +Finally, we again call the printSideRail() function to print a side rail at the end of each step and move to the next line to start a new step. + +Note: The number of spaces between the asterisks in each step can be adjusted by modifying the value inside the 'printSideRail()' and 'printStep(stepNumber)' functions. + Time complexity: O(N) for given input N steps Auxiliary Space: O(1) as constant extra space is used */ -import java.util.Scanner; -public class Ladder_Pattern -{ - public static void main(String args[]) - { - Scanner sc=new Scanner(System.in); - System.out.print("Enter the number of steps: " ); - //reads an integer form the user - //n is the number of steps in ladder - int n=sc.nextInt(); - for(int i=1;i<=n*3+2;i++) - { - for(int j=1;j<=5;j++) - { - if(i%3==0) - System.out.print("*"); - else if(j==1||j==5) - System.out.print("*"); - else - System.out.print(" "); - } - //throws cursor to the new line - System.out.println(); - } - } -} +import java.util.Scanner; + +public class LadderPattern { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter the number of steps in the ladder: "); + int N = sc.nextInt(); + + // Print the ladder with N steps + for (int i = 1; i <= N; i++) { + printSideRail(); + printStep(i); + printSideRail(); + System.out.println(); + } + } + + // Function to print a side rail + public static void printSideRail() { + System.out.print("* "); + } + + // Function to print a step + public static void printStep(int stepNumber) { + for (int i = 1; i <= stepNumber; i++) { + System.out.print("* "); + } + } +} + +/* + +Enter the number of steps in the ladder: 5 +* * +* * * +* * * * +* * * * * +* * * * * * + +*/ From 43e777e9fa849c604a42845978c46e3cc482f5d8 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Fri, 30 Jun 2023 00:13:29 +0530 Subject: [PATCH 1503/1894] Create Maximal_Square.java --- 2D Arrays (Matrix)/Maximal_Square.java | 57 ++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 2D Arrays (Matrix)/Maximal_Square.java diff --git a/2D Arrays (Matrix)/Maximal_Square.java b/2D Arrays (Matrix)/Maximal_Square.java new file mode 100644 index 00000000..dd36c4ae --- /dev/null +++ b/2D Arrays (Matrix)/Maximal_Square.java @@ -0,0 +1,57 @@ +/* +Problem: +Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. + +Approach: +1. Initialize a variable `maxSide` to 0 to store the maximum side length of the square. +2. Check if the given matrix is empty, if so, return 0. +3. Create a dynamic programming array `dp` with dimensions (rows + 1) x (cols + 1), where `rows` and `cols` are the dimensions of the matrix. +4. Traverse through the matrix starting from index (1, 1) to (rows, cols). +5. For each cell, if the value is '1', calculate the side length of the square by taking the minimum of the values from the top, left, and diagonal cells in the `dp` array, and add 1. +6. Update the `maxSide` variable with the maximum side length found so far. +7. Finally, return the area of the largest square by multiplying `maxSide` with itself. + +Time Complexity: O(m*n), where m is the number of rows and n is the number of columns in the matrix. + +Space Complexity: O(m*n), as we use an additional dp array of the same dimensions as the matrix. + +Sample Input: +char[][] matrix = { + {'1', '0', '1', '0', '0'}, + {'1', '0', '1', '1', '1'}, + {'1', '1', '1', '1', '1'}, + {'1', '0', '0', '1', '0'} +}; + +Sample Output: +4 + +Note: In the given sample input, the largest square containing only 1's has a side length of 2, so the area is 4. +*/ + + +public class LargestSquare { + public int maximalSquare(char[][] matrix) { + int maxSide = 0; // variable to store the maximum side length of the square + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { + return maxSide; // return 0 if the matrix is empty + } + + int rows = matrix.length; + int cols = matrix[0].length; + int[][] dp = new int[rows + 1][cols + 1]; // create a dynamic programming array to store the side length of the square + + for (int i = 1; i <= rows; i++) { + for (int j = 1; j <= cols; j++) { + if (matrix[i-1][j-1] == '1') { // if current cell is 1 + dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1; // calculate the side length of the square based on top, left, and diagonal cells + maxSide = Math.max(maxSide, dp[i][j]); // update the maximum side length + } + } + } + + return maxSide * maxSide; // return the area of the largest square + } +} + + From 0dbd9300fa3460ee6186ce06a92be21ef8757835 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Fri, 30 Jun 2023 00:19:31 +0530 Subject: [PATCH 1504/1894] Create Factorial.java --- Math/Factorial.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Math/Factorial.java diff --git a/Math/Factorial.java b/Math/Factorial.java new file mode 100644 index 00000000..d07e8153 --- /dev/null +++ b/Math/Factorial.java @@ -0,0 +1,37 @@ +/* +What is a factorial of a number? +The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example, the factorial of 5 is 5! = 5 x 4 x 3 x 2 x 1 = 120. + +Approach: +The recursive approach is used to calculate the factorial. The function `factorial()` takes an integer `n` as input. In each recursive call, we check if `n` is either 0 or 1 (base case), and if so, we return 1. Otherwise, we multiply `n` with the factorial of `n-1` and return the result. + +Time Complexity: O(n) +The time complexity of this algorithm is O(n) because the recursion depth is equal to n, and in each recursion, we perform a constant-time operation. + +Space Complexity: O(n) +The space complexity is O(n) because, in the worst-case scenario, the recursion depth can reach up to n. So, n frames will be added to the call stack. + +Sample Input: 5 +Sample Output: Factorial of 5 is: 120 + +*/ + +public class Factorial { + // Recursive function to calculate the factorial + public static int factorial(int n) { + // Base case: if n is 0 or 1, the factorial is always 1 + if (n == 0 || n == 1) { + return 1; + } + + // Recursive case: multiply n with factorial of (n-1) + return n * factorial(n - 1); + } + + public static void main(String[] args) { + int number = 5; // Sample input: calculate factorial of 5 + int result = factorial(number); + System.out.println("Factorial of " + number + " is: " + result); + } +} + From 7dac8caff4182a0a07c21903bf636f894ef4bfba Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Fri, 30 Jun 2023 00:27:35 +0530 Subject: [PATCH 1505/1894] Create factorial.py --- Math/factorial.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Math/factorial.py diff --git a/Math/factorial.py b/Math/factorial.py new file mode 100644 index 00000000..d06dd8e5 --- /dev/null +++ b/Math/factorial.py @@ -0,0 +1,36 @@ +''' +Approach: +We will take the number as input from the user and calculate its factorial. +To calculate the factorial, we will start from 1 and multiply it with all the numbers from 1 to n. +Finally, we will return the factorial. + +Time Complexity: O(n) +Space Complexity: O(1) + +''' + +# Initializing the factorial to 1 +fact = 1 +def factorial(num): + # If the number is 0 or 1, then the factorial is 1. + if num == 0 or num == 1: + return 1 + # Calculating factorial by multiplying every number from 1 to num + for i in range(1, num+1): + fact *= i + return fact + +#Taking input from user +num = int(input("Enter a number: ")) +#Calculating and printing the factorial of the number +print("Factorial of", num, "is", factorial(num)) + + +''' +Sample Input: 5 +Sample Output: Factorial of 5 is 120 +''' + + + + From 978f0d6e7f3c09c7d111e4d650e6c92c0136468e Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Fri, 30 Jun 2023 12:01:54 +0530 Subject: [PATCH 1506/1894] Adding maximal sqaure in cpp --- Dynamic Programming/maximal_sqaure.cpp | 120 +++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Dynamic Programming/maximal_sqaure.cpp diff --git a/Dynamic Programming/maximal_sqaure.cpp b/Dynamic Programming/maximal_sqaure.cpp new file mode 100644 index 00000000..51cc44fc --- /dev/null +++ b/Dynamic Programming/maximal_sqaure.cpp @@ -0,0 +1,120 @@ +/* + -> The maximalSquare function takes a matrix as input and returns the area of the maximal square found in the matrix. + -> The function first checks if the matrix is empty (no rows or columns). In such cases, there can't be any squares, + so it returns 0. + -> Next, it initializes some variables. rows stores the number of rows in the matrix, cols stores the number of + columns, and maxSide keeps track of the maximum side length of the square encountered so far. + -> It creates a new matrix called dp using the Array.from method. This matrix will store the side lengths of squares. + -> The next step is to initialize the first row and the first column of dp with the values from the input matrix. It + iterates over each element in the first row and sets the corresponding element in dp to either 0 or 1, depending on + whether the element in the input matrix is '0' or '1'. It also updates maxSide accordingly. + -> Similarly, it iterates over each element in the first column and sets the corresponding element in dp to either + 0 or 1, based on the input matrix. Again, maxSide is updated. + -> Now, the function enters a nested loop to iterate over the remaining elements of the matrix, starting from the + second row and the second column. For each element at position (i, j), it checks if the corresponding element in the + input matrix is '1'. + -> If the element is '1', it calculates the value of dp[i][j] by taking the minimum of the three adjacent elements: + dp[i-1][j] (above), dp[i][j-1] (left), and dp[i-1][j-1] (diagonally above-left). It adds 1 to the minimum value and + assigns it to dp[i][j]. Additionally, it updates maxSide if the current dp[i][j] value is greater. + -> After the nested loop completes, the function has calculated the side lengths of squares for all positions in the + matrix. It returns the area of the maximal square by squaring the value of maxSide. + -> Finally, outside the function, an example usage is shown. The matrix variable represents a 2D array with 0s and 1s. + The maximalSquare function is called with this matrix, and the returned result is logged to the console. In this + example, the maximal square in the matrix has a side length of 2, so the output is 4 (2 * 2). + +The code utilizes dynamic programming to efficiently calculate the maximal square in the given matrix by storing the +side lengths of squares in a separate matrix. By using previously calculated values, the algorithm avoids redundant +calculations and improves performance. + +//Time complexity + +The time complexity of the provided maximal square algorithm is O(m * n), where m is the number of rows +in the matrix and n is the number of columns. This is because we iterate over each element in the matrix +once to calculate the side lengths of squares. The nested loops contribute to the linear time complexity. + +The space complexity is O(m * n) as well. We create an additional matrix, dp, with the same dimensions as +the input matrix to store the side lengths of squares. Hence, the space required is proportional to the +number of elements in the matrix. + +In summary, the time complexity and space complexity of the maximal square algorithm are both O(m * n), +where m is the number of rows and n is the number of columns in the matrix. +*/ + + +/* + +Example 1: +Input: + +1 0 1 0 0 +1 0 1 1 1 +1 1 1 1 1 +1 0 0 1 0 + +Output: 4 +The maximal square in the matrix is a 2x2 square with the top-left corner at position (1, 2) and the bottom-right corner at position (2, 3). The area of this square is 4. + +Example 2: +Input: +0 1 1 1 1 +1 1 0 1 0 +0 1 1 1 1 +1 1 1 1 0 + + +Output: 9 +The maximal square in the matrix is a 3x3 square with the top-left corner at position (0, 1) and the bottom-right corner at position (2, 3). The area of this square is 9. + +Example 3: +Input: + +0 0 0 +0 0 0 +0 0 0 + +Output: 0 +There are no squares with side length greater than 0 in the matrix. Therefore, the output is 0. + +*/ +#include +#include +#include + +int maximalSquare(std::vector>& matrix) { + if (matrix.empty() || matrix[0].empty()) { + return 0; + } + + int rows = matrix.size(); + int cols = matrix[0].size(); + int maxSide = 0; + + // Create a new matrix to store the side lengths of squares + std::vector> dp(rows, std::vector(cols, 0)); + + // Initialize the first row of the dp matrix + for (int i = 0; i < rows; i++) { + dp[i][0] = matrix[i][0] - '0'; + maxSide = std::max(maxSide, dp[i][0]); + } + + // Initialize the first column of the dp matrix + for (int j = 0; j < cols; j++) { + dp[0][j] = matrix[0][j] - '0'; + maxSide = std::max(maxSide, dp[0][j]); + } + + // Iterate over the remaining elements of the matrix + for (int i = 1; i < rows; i++) { + for (int j = 1; j < cols; j++) { + if (matrix[i][j] == '1') { + // Calculate the minimum of the three adjacent squares and add 1 + dp[i][j] = std::min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}) + 1; + maxSide = std::max(maxSide, dp[i][j]); + } + } + } + + // Return the area of the maximal square + return maxSide * maxSide; +} \ No newline at end of file From 2aaa87b321a90915427a1ee0061f5fa70149f589 Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Fri, 30 Jun 2023 12:02:33 +0530 Subject: [PATCH 1507/1894] Adding maximal sqaure in go --- Dynamic Programming/maximal_sqaure.go | 141 ++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 Dynamic Programming/maximal_sqaure.go diff --git a/Dynamic Programming/maximal_sqaure.go b/Dynamic Programming/maximal_sqaure.go new file mode 100644 index 00000000..c744e63e --- /dev/null +++ b/Dynamic Programming/maximal_sqaure.go @@ -0,0 +1,141 @@ +/* + -> The maximalSquare function takes a matrix as input and returns the area of the maximal square found in the matrix. + -> The function first checks if the matrix is empty (no rows or columns). In such cases, there can't be any squares, + so it returns 0. + -> Next, it initializes some variables. rows stores the number of rows in the matrix, cols stores the number of + columns, and maxSide keeps track of the maximum side length of the square encountered so far. + -> It creates a new matrix called dp using the Array.from method. This matrix will store the side lengths of squares. + -> The next step is to initialize the first row and the first column of dp with the values from the input matrix. It + iterates over each element in the first row and sets the corresponding element in dp to either 0 or 1, depending on + whether the element in the input matrix is '0' or '1'. It also updates maxSide accordingly. + -> Similarly, it iterates over each element in the first column and sets the corresponding element in dp to either + 0 or 1, based on the input matrix. Again, maxSide is updated. + -> Now, the function enters a nested loop to iterate over the remaining elements of the matrix, starting from the + second row and the second column. For each element at position (i, j), it checks if the corresponding element in the + input matrix is '1'. + -> If the element is '1', it calculates the value of dp[i][j] by taking the minimum of the three adjacent elements: + dp[i-1][j] (above), dp[i][j-1] (left), and dp[i-1][j-1] (diagonally above-left). It adds 1 to the minimum value and + assigns it to dp[i][j]. Additionally, it updates maxSide if the current dp[i][j] value is greater. + -> After the nested loop completes, the function has calculated the side lengths of squares for all positions in the + matrix. It returns the area of the maximal square by squaring the value of maxSide. + -> Finally, outside the function, an example usage is shown. The matrix variable represents a 2D array with 0s and 1s. + The maximalSquare function is called with this matrix, and the returned result is logged to the console. In this + example, the maximal square in the matrix has a side length of 2, so the output is 4 (2 * 2). + +The code utilizes dynamic programming to efficiently calculate the maximal square in the given matrix by storing the +side lengths of squares in a separate matrix. By using previously calculated values, the algorithm avoids redundant +calculations and improves performance. + +//Time complexity + +The time complexity of the provided maximal square algorithm is O(m * n), where m is the number of rows +in the matrix and n is the number of columns. This is because we iterate over each element in the matrix +once to calculate the side lengths of squares. The nested loops contribute to the linear time complexity. + +The space complexity is O(m * n) as well. We create an additional matrix, dp, with the same dimensions as +the input matrix to store the side lengths of squares. Hence, the space required is proportional to the +number of elements in the matrix. + +In summary, the time complexity and space complexity of the maximal square algorithm are both O(m * n), +where m is the number of rows and n is the number of columns in the matrix. +*/ + + +/* + +Example 1: +Input: + +1 0 1 0 0 +1 0 1 1 1 +1 1 1 1 1 +1 0 0 1 0 + +Output: 4 +The maximal square in the matrix is a 2x2 square with the top-left corner at position (1, 2) and the bottom-right corner at position (2, 3). The area of this square is 4. + +Example 2: +Input: +0 1 1 1 1 +1 1 0 1 0 +0 1 1 1 1 +1 1 1 1 0 + + +Output: 9 +The maximal square in the matrix is a 3x3 square with the top-left corner at position (0, 1) and the bottom-right corner at position (2, 3). The area of this square is 9. + +Example 3: +Input: + +0 0 0 +0 0 0 +0 0 0 + +Output: 0 +There are no squares with side length greater than 0 in the matrix. Therefore, the output is 0. + +*/ + + +package main + +import ( + "fmt" +) + +func maximalSquare(matrix [][]byte) int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return 0 + } + + rows := len(matrix) + cols := len(matrix[0]) + maxSide := 0 + + // Create a new matrix to store the side lengths of squares + dp := make([][]int, rows) + for i := range dp { + dp[i] = make([]int, cols) + } + + // Initialize the first row of the dp matrix + for i := 0; i < rows; i++ { + dp[i][0] = int(matrix[i][0] - '0') + maxSide = max(maxSide, dp[i][0]) + } + + // Initialize the first column of the dp matrix + for j := 0; j < cols; j++ { + dp[0][j] = int(matrix[0][j] - '0') + maxSide = max(maxSide, dp[0][j]) + } + + // Iterate over the remaining elements of the matrix + for i := 1; i < rows; i++ { + for j := 1; j < cols; j++ { + if matrix[i][j] == '1' { + // Calculate the minimum of the three adjacent squares and add 1 + dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1 + maxSide = max(maxSide, dp[i][j]) + } + } + } + + // Return the area of the maximal square + return maxSide * maxSide +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} From 0febdad0a22dd571c163af7f88d55f12516fec19 Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Fri, 30 Jun 2023 12:03:04 +0530 Subject: [PATCH 1508/1894] Adding maximal sqaure in js --- Dynamic Programming/maximal_sqaure.js | 117 ++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Dynamic Programming/maximal_sqaure.js diff --git a/Dynamic Programming/maximal_sqaure.js b/Dynamic Programming/maximal_sqaure.js new file mode 100644 index 00000000..70835f46 --- /dev/null +++ b/Dynamic Programming/maximal_sqaure.js @@ -0,0 +1,117 @@ +/* + -> The maximalSquare function takes a matrix as input and returns the area of the maximal square found in the matrix. + -> The function first checks if the matrix is empty (no rows or columns). In such cases, there can't be any squares, + so it returns 0. + -> Next, it initializes some variables. rows stores the number of rows in the matrix, cols stores the number of + columns, and maxSide keeps track of the maximum side length of the square encountered so far. + -> It creates a new matrix called dp using the Array.from method. This matrix will store the side lengths of squares. + -> The next step is to initialize the first row and the first column of dp with the values from the input matrix. It + iterates over each element in the first row and sets the corresponding element in dp to either 0 or 1, depending on + whether the element in the input matrix is '0' or '1'. It also updates maxSide accordingly. + -> Similarly, it iterates over each element in the first column and sets the corresponding element in dp to either + 0 or 1, based on the input matrix. Again, maxSide is updated. + -> Now, the function enters a nested loop to iterate over the remaining elements of the matrix, starting from the + second row and the second column. For each element at position (i, j), it checks if the corresponding element in the + input matrix is '1'. + -> If the element is '1', it calculates the value of dp[i][j] by taking the minimum of the three adjacent elements: + dp[i-1][j] (above), dp[i][j-1] (left), and dp[i-1][j-1] (diagonally above-left). It adds 1 to the minimum value and + assigns it to dp[i][j]. Additionally, it updates maxSide if the current dp[i][j] value is greater. + -> After the nested loop completes, the function has calculated the side lengths of squares for all positions in the + matrix. It returns the area of the maximal square by squaring the value of maxSide. + -> Finally, outside the function, an example usage is shown. The matrix variable represents a 2D array with 0s and 1s. + The maximalSquare function is called with this matrix, and the returned result is logged to the console. In this + example, the maximal square in the matrix has a side length of 2, so the output is 4 (2 * 2). + +The code utilizes dynamic programming to efficiently calculate the maximal square in the given matrix by storing the +side lengths of squares in a separate matrix. By using previously calculated values, the algorithm avoids redundant +calculations and improves performance. + +//Time complexity + +The time complexity of the provided maximal square algorithm is O(m * n), where m is the number of rows +in the matrix and n is the number of columns. This is because we iterate over each element in the matrix +once to calculate the side lengths of squares. The nested loops contribute to the linear time complexity. + +The space complexity is O(m * n) as well. We create an additional matrix, dp, with the same dimensions as +the input matrix to store the side lengths of squares. Hence, the space required is proportional to the +number of elements in the matrix. + +In summary, the time complexity and space complexity of the maximal square algorithm are both O(m * n), +where m is the number of rows and n is the number of columns in the matrix. +*/ + +/* + +Example 1: +Input: + +1 0 1 0 0 +1 0 1 1 1 +1 1 1 1 1 +1 0 0 1 0 + +Output: 4 +The maximal square in the matrix is a 2x2 square with the top-left corner at position (1, 2) and the bottom-right corner at position (2, 3). The area of this square is 4. + +Example 2: +Input: +0 1 1 1 1 +1 1 0 1 0 +0 1 1 1 1 +1 1 1 1 0 + + +Output: 9 +The maximal square in the matrix is a 3x3 square with the top-left corner at position (0, 1) and the bottom-right corner at position (2, 3). The area of this square is 9. + +Example 3: +Input: + +0 0 0 +0 0 0 +0 0 0 + +Output: 0 +There are no squares with side length greater than 0 in the matrix. Therefore, the output is 0. + +*/ + +function maximalSquare(matrix) { + if (matrix.length === 0 || matrix[0].length === 0) { + return 0; + } + + const rows = matrix.length; + const cols = matrix[0].length; + let maxSide = 0; + + // Create a new matrix to store the side lengths of squares + const dp = Array.from({ length: rows }, () => Array(cols).fill(0)); + + // Initialize the first row of the dp matrix + for (let i = 0; i < rows; i++) { + dp[i][0] = Number(matrix[i][0]); + maxSide = Math.max(maxSide, dp[i][0]); + } + + // Initialize the first column of the dp matrix + for (let j = 0; j < cols; j++) { + dp[0][j] = Number(matrix[0][j]); + maxSide = Math.max(maxSide, dp[0][j]); + } + + // Iterate over the remaining elements of the matrix + for (let i = 1; i < rows; i++) { + for (let j = 1; j < cols; j++) { + if (matrix[i][j] === '1') { + // Calculate the minimum of the three adjacent squares and add 1 + dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1; + maxSide = Math.max(maxSide, dp[i][j]); + } + } + } + + // Return the area of the maximal square + return maxSide * maxSide; +} + From 7ef8eafa674711112ea4b4f4fc47f31343840333 Mon Sep 17 00:00:00 2001 From: Rishi sharma Date: Fri, 30 Jun 2023 12:03:23 +0530 Subject: [PATCH 1509/1894] Adding maximal sqaure in py --- Dynamic Programming/maximal_sqaure.py | 110 ++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Dynamic Programming/maximal_sqaure.py diff --git a/Dynamic Programming/maximal_sqaure.py b/Dynamic Programming/maximal_sqaure.py new file mode 100644 index 00000000..3c079957 --- /dev/null +++ b/Dynamic Programming/maximal_sqaure.py @@ -0,0 +1,110 @@ +''' + -> The maximalSquare function takes a matrix as input and returns the area of the maximal square found in the matrix. + -> The function first checks if the matrix is empty (no rows or columns). In such cases, there can't be any squares, + so it returns 0. + -> Next, it initializes some variables. rows stores the number of rows in the matrix, cols stores the number of + columns, and maxSide keeps track of the maximum side length of the square encountered so far. + -> It creates a new matrix called dp using the Array.from method. This matrix will store the side lengths of squares. + -> The next step is to initialize the first row and the first column of dp with the values from the input matrix. It + iterates over each element in the first row and sets the corresponding element in dp to either 0 or 1, depending on + whether the element in the input matrix is '0' or '1'. It also updates maxSide accordingly. + -> Similarly, it iterates over each element in the first column and sets the corresponding element in dp to either + 0 or 1, based on the input matrix. Again, maxSide is updated. + -> Now, the function enters a nested loop to iterate over the remaining elements of the matrix, starting from the + second row and the second column. For each element at position (i, j), it checks if the corresponding element in the + input matrix is '1'. + -> If the element is '1', it calculates the value of dp[i][j] by taking the minimum of the three adjacent elements: + dp[i-1][j] (above), dp[i][j-1] (left), and dp[i-1][j-1] (diagonally above-left). It adds 1 to the minimum value and + assigns it to dp[i][j]. Additionally, it updates maxSide if the current dp[i][j] value is greater. + -> After the nested loop completes, the function has calculated the side lengths of squares for all positions in the + matrix. It returns the area of the maximal square by squaring the value of maxSide. + -> Finally, outside the function, an example usage is shown. The matrix variable represents a 2D array with 0s and 1s. + The maximalSquare function is called with this matrix, and the returned result is logged to the console. In this + example, the maximal square in the matrix has a side length of 2, so the output is 4 (2 * 2). + +The code utilizes dynamic programming to efficiently calculate the maximal square in the given matrix by storing the +side lengths of squares in a separate matrix. By using previously calculated values, the algorithm avoids redundant +calculations and improves performance. + +//Time complexity + +The time complexity of the provided maximal square algorithm is O(m * n), where m is the number of rows +in the matrix and n is the number of columns. This is because we iterate over each element in the matrix +once to calculate the side lengths of squares. The nested loops contribute to the linear time complexity. + +The space complexity is O(m * n) as well. We create an additional matrix, dp, with the same dimensions as +the input matrix to store the side lengths of squares. Hence, the space required is proportional to the +number of elements in the matrix. + +In summary, the time complexity and space complexity of the maximal square algorithm are both O(m * n), +where m is the number of rows and n is the number of columns in the matrix. +''' + + +''' + +Example 1: +Input: + +1 0 1 0 0 +1 0 1 1 1 +1 1 1 1 1 +1 0 0 1 0 + +Output: 4 +The maximal square in the matrix is a 2x2 square with the top-left corner at position (1, 2) and the bottom-right corner at position (2, 3). The area of this square is 4. + +Example 2: +Input: +0 1 1 1 1 +1 1 0 1 0 +0 1 1 1 1 +1 1 1 1 0 + + +Output: 9 +The maximal square in the matrix is a 3x3 square with the top-left corner at position (0, 1) and the bottom-right corner at position (2, 3). The area of this square is 9. + +Example 3: +Input: + +0 0 0 +0 0 0 +0 0 0 + +Output: 0 +There are no squares with side length greater than 0 in the matrix. Therefore, the output is 0. + +''' + +def maximalSquare(matrix): + if len(matrix) == 0 or len(matrix[0]) == 0: + return 0 + + rows = len(matrix) + cols = len(matrix[0]) + maxSide = 0 + + # Create a new matrix to store the side lengths of squares + dp = [[0] * cols for _ in range(rows)] + + # Initialize the first row of the dp matrix + for i in range(rows): + dp[i][0] = int(matrix[i][0]) + maxSide = max(maxSide, dp[i][0]) + + # Initialize the first column of the dp matrix + for j in range(cols): + dp[0][j] = int(matrix[0][j]) + maxSide = max(maxSide, dp[0][j]) + + # Iterate over the remaining elements of the matrix + for i in range(1, rows): + for j in range(1, cols): + if matrix[i][j] == '1': + # Calculate the minimum of the three adjacent squares and add 1 + dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 + maxSide = max(maxSide, dp[i][j]) + + # Return the area of the maximal square + return maxSide * maxSide From 56ddfd5339d183258c14bb43abd843e33ba5cbab Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 30 Jun 2023 20:03:14 +0530 Subject: [PATCH 1510/1894] Create stacks_API.cpp closes #279 --- Stacks/stacks_API.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Stacks/stacks_API.cpp diff --git a/Stacks/stacks_API.cpp b/Stacks/stacks_API.cpp new file mode 100644 index 00000000..59f1730e --- /dev/null +++ b/Stacks/stacks_API.cpp @@ -0,0 +1,67 @@ +/* + In this implementation, we use a std::priority_queue named heap to simulate the behavior of a stack. The push operation inserts elements into the heap with a unique sequence number generated for each element. The pop operation removes the top element from the heap. The top operation returns the top element without removing it. The empty operation checks if the heap is empty. + +The time complexity of the stack operations implemented using a heap is as follows: + +push: O(log n), where n is the number of elements in the stack. +pop: O(log n), where n is the number of elements in the stack. +top: O(1) +empty: O(1) +The push and pop operations have a time complexity of O(log n) because the std::priority_queue internally maintains the heap property, ensuring that the highest priority (in this case, the highest sequence number) element is always at the top + */ + + + +#include +#include + +class Stack { +private: + std::priority_queue heap; // Using max heap to simulate stack behavior + int sequenceNumber; // To keep track of the order of elements + +public: + Stack() : sequenceNumber(0) {} + + void push(int value) { + heap.push(std::make_pair(sequenceNumber++, value)); + } + + int pop() { + if (heap.empty()) { + throw std::runtime_error("Stack is empty"); + } + + int value = heap.top().second; + heap.pop(); + return value; + } + + int top() const { + if (heap.empty()) { + throw std::runtime_error("Stack is empty"); + } + + return heap.top().second; + } + + bool empty() const { + return heap.empty(); + } +}; + +int main() { + Stack stack; + + stack.push(5); + stack.push(10); + stack.push(3); + + std::cout << stack.top() << std::endl; // Output: 3 + + stack.pop(); + + std::cout << stack.top() << std::endl; // Output: 10 + + return 0; +} From 809acb34c288af1b8861b4c9ec847007080b225b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 30 Jun 2023 22:23:27 +0530 Subject: [PATCH 1511/1894] move to dp directory --- .../maximal_square.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2D Arrays (Matrix)/Maximal_Square.java => Dynamic Programming/maximal_square.java (100%) diff --git a/2D Arrays (Matrix)/Maximal_Square.java b/Dynamic Programming/maximal_square.java similarity index 100% rename from 2D Arrays (Matrix)/Maximal_Square.java rename to Dynamic Programming/maximal_square.java From 2a6cb6a6a04ef8f90cd63f3b6f6a4f9bfe380fad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 30 Jun 2023 22:24:19 +0530 Subject: [PATCH 1512/1894] match file name --- ...Partition of String.go => find_optimal_partition_of_string.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hash Table/{find_Optimal Partition of String.go => find_optimal_partition_of_string.go} (100%) diff --git a/Hash Table/find_Optimal Partition of String.go b/Hash Table/find_optimal_partition_of_string.go similarity index 100% rename from Hash Table/find_Optimal Partition of String.go rename to Hash Table/find_optimal_partition_of_string.go From 28f0248d2b6bf5626dffece2e28147c2bfb885ae Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 30 Jun 2023 22:24:30 +0530 Subject: [PATCH 1513/1894] rename file --- ...positve.py.py => first_missing_positve.py} | 114 +++++++++--------- 1 file changed, 57 insertions(+), 57 deletions(-) rename Hash Table/{first_missing_positve.py.py => first_missing_positve.py} (97%) diff --git a/Hash Table/first_missing_positve.py.py b/Hash Table/first_missing_positve.py similarity index 97% rename from Hash Table/first_missing_positve.py.py rename to Hash Table/first_missing_positve.py index 1671ca17..d7284d1f 100644 --- a/Hash Table/first_missing_positve.py.py +++ b/Hash Table/first_missing_positve.py @@ -1,57 +1,57 @@ -# first positive missing in python -''' -To find the smallest missing positive integer in an unsorted integer array nums with the given time and space constraints, -you can utilize the concept of in-place swapping and indexing. - -Explanation:- - - -> Iterate through the array nums and ignore any non-positive numbers (i.e., negative numbers and zero). - Also, ignore numbers greater than the length of the array since they cannot be the smallest missing positive integer. - - -> For each positive number num encountered, find its correct index targetIndex as num - 1. - - -> Check if the number at index targetIndex is already in its correct place or not. If it is not, - swap the numbers at indices i and targetIndex to move num to its correct place. Continue this swapping - process until the number at index i is either non-positive or already in its correct place. - - -> After completing the iteration, perform a second pass through the array. The first index i that does not - contain the value i + 1 represents the smallest missing positive integer. Return i + 1. -''' - -# Time complexity O(n) and Space complexity O(1). - -'''Examples- - -Example 1: -Input: nums = [1, 2, 0] -Output: 3 -Explanation: The smallest missing positive integer in the array is 3. - -Example 2: -Input: nums = [3, 4, -1, 1] -Output: 2 -Explanation: The smallest missing positive integer in the array is 2. - -Example 3: -Input: nums = [7, 8, 9, 11, 12] -Output: 1 -Explanation: The smallest missing positive integer in the array is 1. - -''' - -def firstMissingPositive(nums): - n = len(nums) - - # Step 1: Move positive numbers to their correct positions - for i in range(n): - while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: - nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] - - # Step 2: Find the first missing positive - for i in range(n): - if nums[i] != i + 1: - return i + 1 - - # If all positive integers are present, return n + 1 - return n + 1 - +# first positive missing in python +''' +To find the smallest missing positive integer in an unsorted integer array nums with the given time and space constraints, +you can utilize the concept of in-place swapping and indexing. + +Explanation:- + + -> Iterate through the array nums and ignore any non-positive numbers (i.e., negative numbers and zero). + Also, ignore numbers greater than the length of the array since they cannot be the smallest missing positive integer. + + -> For each positive number num encountered, find its correct index targetIndex as num - 1. + + -> Check if the number at index targetIndex is already in its correct place or not. If it is not, + swap the numbers at indices i and targetIndex to move num to its correct place. Continue this swapping + process until the number at index i is either non-positive or already in its correct place. + + -> After completing the iteration, perform a second pass through the array. The first index i that does not + contain the value i + 1 represents the smallest missing positive integer. Return i + 1. +''' + +# Time complexity O(n) and Space complexity O(1). + +'''Examples- + +Example 1: +Input: nums = [1, 2, 0] +Output: 3 +Explanation: The smallest missing positive integer in the array is 3. + +Example 2: +Input: nums = [3, 4, -1, 1] +Output: 2 +Explanation: The smallest missing positive integer in the array is 2. + +Example 3: +Input: nums = [7, 8, 9, 11, 12] +Output: 1 +Explanation: The smallest missing positive integer in the array is 1. + +''' + +def firstMissingPositive(nums): + n = len(nums) + + # Step 1: Move positive numbers to their correct positions + for i in range(n): + while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: + nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] + + # Step 2: Find the first missing positive + for i in range(n): + if nums[i] != i + 1: + return i + 1 + + # If all positive integers are present, return n + 1 + return n + 1 + From 9df34133cf7fab5e81df53449cfd82bc848a6c7a Mon Sep 17 00:00:00 2001 From: Avantika Date: Sat, 1 Jul 2023 16:08:01 +0530 Subject: [PATCH 1514/1894] Adding ladders.java --- {Famous Algorithms => Patterns}/Ladder_Pattern.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {Famous Algorithms => Patterns}/Ladder_Pattern.java (100%) diff --git a/Famous Algorithms/Ladder_Pattern.java b/Patterns/Ladder_Pattern.java similarity index 100% rename from Famous Algorithms/Ladder_Pattern.java rename to Patterns/Ladder_Pattern.java From 978028e16fd8a793afcc4497280a74892dbcbdb3 Mon Sep 17 00:00:00 2001 From: Mudit Jain <97677133+Mudit-Jxin7@users.noreply.github.com> Date: Sat, 1 Jul 2023 17:17:06 +0530 Subject: [PATCH 1515/1894] Create add_first_missing_positive.cpp --- Hash Table/add_first_missing_positive.cpp | 60 +++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Hash Table/add_first_missing_positive.cpp diff --git a/Hash Table/add_first_missing_positive.cpp b/Hash Table/add_first_missing_positive.cpp new file mode 100644 index 00000000..cc80c5b9 --- /dev/null +++ b/Hash Table/add_first_missing_positive.cpp @@ -0,0 +1,60 @@ +/* + Given an unsorted integer array nums, return the smallest missing positive integer. + You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space. + Sample Input: [3, 4, -1, 1] + Sample Output: 2 + Explanation: + This code implements a solution to find the first missing positive integer from an unsorted array. The function first separates positive and negative numbers. + It then considers the array with only positive numbers, and marks the index corresponding to every positive number in this array. + The first index which is unmarked corresponds to the first missing positive number. + This solution uses the array itself as a pseudo-hash table where the keys are the array indices, and the values are whether or not a positive integer is present in the array. + By using the array in this way, we are able to find the solution in O(1) auxiliary space. + Time complexity: O(n) + Space complexity: O(1) +*/ + +#include +#include +#include + +int firstMissingPositive(std::vector& nums) { + int n = nums.size(); + + // Mark numbers that are out of range as 0 + for (int i = 0; i < n; i++) { + if (nums[i] <= 0 || nums[i] > n) { + nums[i] = 0; + } + } + + // Mark the index corresponding to the value of each number + for (int i = 0; i < n; i++) { + int num = std::abs(nums[i]); + + if (num > 0) { + num--; // subtract 1 because of 0-based indexing + + // Mark as negative + if (nums[num] > 0) { + nums[num] = -nums[num]; + } + } + } + + // Find the first number greater than 0 + for (int i = 0; i < n; i++) { + if (nums[i] >= 0) { + return i + 1; // add 1 because of 0-based indexing + } + } + + // If no number is missing + return n + 1; +} + +int main() { + std::vector nums = {3, 4, -1, 1}; + int result = firstMissingPositive(nums); + std::cout << "Smallest missing positive integer: " << result << std::endl; + return 0; +} From a65d4e3ddf6cdaf2a8bf7b059bdd6200b2accea3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:25:54 +0530 Subject: [PATCH 1516/1894] add sample io --- Arrays/move_element_to_end.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Arrays/move_element_to_end.go b/Arrays/move_element_to_end.go index 553ddd38..9e6188c9 100644 --- a/Arrays/move_element_to_end.go +++ b/Arrays/move_element_to_end.go @@ -1,4 +1,8 @@ /* + Move 0's to end + Sample Input : [1, 0, 3, 0, 0, 5] + Output : [1, 3, 5, 0, 0, 0] + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, and returns a modified array with all instances of toMove moved to the end of the array. From 223ada10a85daf8cbe7bd5e66a78c9945444a1c4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:26:02 +0530 Subject: [PATCH 1517/1894] add move 0s to end in python --- Arrays/move_element_to_end.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Arrays/move_element_to_end.py diff --git a/Arrays/move_element_to_end.py b/Arrays/move_element_to_end.py new file mode 100644 index 00000000..85b18c3f --- /dev/null +++ b/Arrays/move_element_to_end.py @@ -0,0 +1,31 @@ +''' + Move 0's to end + Sample Input : [1, 0, 3, 0, 0, 5] + Output : [1, 3, 5, 0, 0, 0] + + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, + and returns a modified array with all instances of toMove moved to the end of the array. + + The function first initializes an integer variable index to 0, which will keep track of the index of the first + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the + current element is not equal to toMove, it replaces the element at the index position with the current element + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the + beginning of the array. + + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the + end of the array. + + Finally, the modified array is returned. + + O(n) time | O(1) space - where n is the length of the array +''' +def move_element_to_end(array, to_move): + index = 0 # initialize a variable to keep track of the index where elements should be moved to + for i in range(len(array)): # loop through the entire array + if array[i] != to_move: # check if the current element is not equal to the element to be moved + array[index] = array[i] # move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i]) + index += 1 # increment the index variable by 1 to keep track of the index where the next non-target element should be moved + for i in range(index, len(array)): # loop through the remaining elements in the array from index to the end + array[i] = to_move # set each element to be the target element + return array # return the modified array From 27c4596481369985288aab818565548deb66f670 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:26:44 +0530 Subject: [PATCH 1518/1894] rename to move elements to end --- Arrays/move_element_to_end.cpp | 37 ++++++++++++++++++++++++++++++++++ Arrays/move_zeros.cpp | 28 ------------------------- 2 files changed, 37 insertions(+), 28 deletions(-) create mode 100644 Arrays/move_element_to_end.cpp delete mode 100644 Arrays/move_zeros.cpp diff --git a/Arrays/move_element_to_end.cpp b/Arrays/move_element_to_end.cpp new file mode 100644 index 00000000..74fec773 --- /dev/null +++ b/Arrays/move_element_to_end.cpp @@ -0,0 +1,37 @@ +/* + Move 0's to end + Sample Input : [1, 0, 3, 0, 0, 5] + Output : [1, 3, 5, 0, 0, 0] + + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, + and returns a modified array with all instances of toMove moved to the end of the array. + + The function first initializes an integer variable index to 0, which will keep track of the index of the first + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the + current element is not equal to toMove, it replaces the element at the index position with the current element + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the + beginning of the array. + + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the + end of the array. + + Finally, the modified array is returned. + + O(n) time | O(1) space - where n is the length of the array +*/ +#include + +std::vector MoveElementToEnd(std::vector& array, int toMove) { + int index = 0; // initialize a variable to keep track of the index where elements should be moved to + for (int i = 0; i < array.size(); i++) { // loop through the entire array + if (array[i] != toMove) { // check if the current element is not equal to the element to be moved + array[index] = array[i]; // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i]) + index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved + } + } + for (int i = index; i < array.size(); i++) { // loop through the remaining elements in the array from index to the end + array[i] = toMove; // set each element to be the target element + } + return array; // return the modified array +} diff --git a/Arrays/move_zeros.cpp b/Arrays/move_zeros.cpp deleted file mode 100644 index 8b7a9c06..00000000 --- a/Arrays/move_zeros.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. -// Input : [1, 0, 0, 4, 3] -// Output : [1, 4, 3, 0, 0] -#include -using namespace std; - -int main(){ - int n; - cin >> n; - vector V(n); - for(int i = 0; i < n; i++){ - cin >> V[i]; - } - int x = 0; - for(int i = 0; i < n; i++){ - if(V[i] != 0){ - V[x] = V[i]; - x++; - } - } - for(int i = x; i < n; i++){ - V[i] = 0; - } - for(int i = 0; i < n; i++){ - cout << V[i] << " "; - } - return 0; -} \ No newline at end of file From 9cfa0bdf97efa2efd334b9c2c0bf273d5e5fb276 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:27:22 +0530 Subject: [PATCH 1519/1894] modify description --- Arrays/move_element_to_end.cpp | 4 ++-- Arrays/move_element_to_end.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Arrays/move_element_to_end.cpp b/Arrays/move_element_to_end.cpp index 74fec773..dffc815a 100644 --- a/Arrays/move_element_to_end.cpp +++ b/Arrays/move_element_to_end.cpp @@ -1,6 +1,6 @@ /* - Move 0's to end - Sample Input : [1, 0, 3, 0, 0, 5] + Move Element to end + Sample Input : [1, 0, 3, 0, 0, 5] To move: 0 Output : [1, 3, 5, 0, 0, 0] This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, diff --git a/Arrays/move_element_to_end.go b/Arrays/move_element_to_end.go index 9e6188c9..15c210f9 100644 --- a/Arrays/move_element_to_end.go +++ b/Arrays/move_element_to_end.go @@ -1,6 +1,6 @@ /* - Move 0's to end - Sample Input : [1, 0, 3, 0, 0, 5] + Move Element to end + Sample Input : [1, 0, 3, 0, 0, 5] To move: 0 Output : [1, 3, 5, 0, 0, 0] This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, From 0fa0b37c0b89e7c5800906915158ebd35c97fd91 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:28:35 +0530 Subject: [PATCH 1520/1894] add move element to end in javascript --- Arrays/move_element_to_end.js | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Arrays/move_element_to_end.js diff --git a/Arrays/move_element_to_end.js b/Arrays/move_element_to_end.js new file mode 100644 index 00000000..f6aed32c --- /dev/null +++ b/Arrays/move_element_to_end.js @@ -0,0 +1,38 @@ +/* + Move Element to end + Sample Input : [1, 0, 3, 0, 0, 5] To move: 0 + Output : [1, 3, 5, 0, 0, 0] + + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, + and returns a modified array with all instances of toMove moved to the end of the array. + + The function first initializes an integer variable index to 0, which will keep track of the index of the first + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the + current element is not equal to toMove, it replaces the element at the index position with the current element + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the + beginning of the array. + + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the + end of the array. + + Finally, the modified array is returned. + + O(n) time | O(1) space - where n is the length of the array +*/ +function moveElementToEnd(array, toMove) { + let index = 0; // initialize a variable to keep track of the index where elements should be moved to + for (let i = 0; i < array.length; i++) { + // loop through the entire array + if (array[i] !== toMove) { + // check if the current element is not equal to the element to be moved + array[index] = array[i]; // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i]) + index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved + } + } + for (let i = index; i < array.length; i++) { + // loop through the remaining elements in the array from index to the end + array[i] = toMove; // set each element to be the target element + } + return array; // return the modified array +} From 1325930463d379d3ed2359146d5a23ecfd964475 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 1 Jul 2023 22:29:03 +0530 Subject: [PATCH 1521/1894] add move element to end in java --- Arrays/move_element_to_end.java | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Arrays/move_element_to_end.java diff --git a/Arrays/move_element_to_end.java b/Arrays/move_element_to_end.java new file mode 100644 index 00000000..25959ad1 --- /dev/null +++ b/Arrays/move_element_to_end.java @@ -0,0 +1,40 @@ +/* + Move Element to end + Sample Input : [1, 0, 3, 0, 0, 5] To move: 0 + Output : [1, 3, 5, 0, 0, 0] + + This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input, + and returns a modified array with all instances of toMove moved to the end of the array. + + The function first initializes an integer variable index to 0, which will keep track of the index of the first + element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the + current element is not equal to toMove, it replaces the element at the index position with the current element + and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the + beginning of the array. + + Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in + the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the + end of the array. + + Finally, the modified array is returned. + + O(n) time | O(1) space - where n is the length of the array +*/ + +import java.util.List; + +public class MoveElementToEnd { + public static List moveElementToEnd(List array, int toMove) { + int index = 0; // initialize a variable to keep track of the index where elements should be moved to + for (int i = 0; i < array.size(); i++) { // loop through the entire array + if (array.get(i) != toMove) { // check if the current element is not equal to the element to be moved + array.set(index, array.get(i)); // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array.get(i)) + index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved + } + } + for (int i = index; i < array.size(); i++) { // loop through the remaining elements in the array from index to the end + array.set(i, toMove); // set each element to be the target element + } + return array; // return the modified array + } +} From 00bb170ffe95e8330d541c1a4b4947ed8682bfea Mon Sep 17 00:00:00 2001 From: Arsh Date: Sun, 2 Jul 2023 00:09:26 +0530 Subject: [PATCH 1522/1894] Add Implementation for Trie in java --- Trees/Binary Trees/trie.java | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Trees/Binary Trees/trie.java diff --git a/Trees/Binary Trees/trie.java b/Trees/Binary Trees/trie.java new file mode 100644 index 00000000..0d27435b --- /dev/null +++ b/Trees/Binary Trees/trie.java @@ -0,0 +1,58 @@ +class Trie { + Node root; + + public Trie() { + root = new Node(); + } + + public void insert(String word) { + root.insert(word, 0); + } + + public boolean search(String word) { + return root.search(word, 0); + } + + public boolean startsWith(String prefix) { + return root.startsWith(prefix, 0); + } + + class Node { + Node[] nodes; + boolean isEnd; + + Node() { + nodes = new Node[26]; + } + + private void insert(String word, int idx) { + if (idx >= word.length()) return; + int i = word.charAt(idx) - 'a'; + if (nodes[i] == null) { + nodes[i] = new Node(); + } + + if (idx == word.length()-1) nodes[i].isEnd = true; + nodes[i].insert(word, idx+1); + } + + private boolean search(String word, int idx) { + if (idx >= word.length()) return false; + Node node = nodes[word.charAt(idx) - 'a']; + if (node == null) return false; + if (idx == word.length() - 1 && node.isEnd) return true; + + return node.search(word, idx+1); + + } + + private boolean startsWith(String prefix, int idx) { + if (idx >= prefix.length()) return false; + Node node = nodes[prefix.charAt(idx) - 'a']; + if (node == null) return false; + if (idx == prefix.length() - 1) return true; + + return node.startsWith(prefix, idx+1); + } + } +} \ No newline at end of file From e5e0c704b041a14028523b04328cb97d3b4e864f Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sun, 2 Jul 2023 00:15:12 +0530 Subject: [PATCH 1523/1894] Create Implement_Trie.py --- Trees/Implement_Trie.py | 77 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Trees/Implement_Trie.py diff --git a/Trees/Implement_Trie.py b/Trees/Implement_Trie.py new file mode 100644 index 00000000..6718bb9a --- /dev/null +++ b/Trees/Implement_Trie.py @@ -0,0 +1,77 @@ +''' +Approach: +1. We implement the TrieNode class with a dictionary of children nodes and a flag to indicate the end of a word. +2. The Trie class is implemented with a root TrieNode as its member variable. +3. The insert function traverses through each character of the input word and creates new TrieNode objects if necessary. +4. The search function traverses through each character of the input word and returns True only if the last node is marked as the end of a word. +5. The startsWith function is similar to the search function but returns True as long as the prefix exists in the Trie. + +Time Complexity: +- Insertion: O(m), where m is the length of the word being inserted. +- Search: O(m), where m is the length of the word being searched. +- Starts With: O(m), where m is the length of the prefix being checked. + +Space Complexity: +- O(n*m), where n is the number of words inserted and m is the average length of the words. + +Sample input and output: + +trie = Trie() +trie.insert("apple") +print(trie.search("apple")) # Output: True +print(trie.search("app")) # Output: False +print(trie.startsWith("app")) # Output: True +trie.insert("app") +print(trie.search("app")) # Output: True + +Here's an implementation of the Trie data structure, also known as the Prefix Tree, in Python: +''' + +# Trie node class +class TrieNode: + def __init__(self): + self.children = {} + self.is_end_of_word = False + + +# Trie class +class Trie: + def __init__(self): + self.root = TrieNode() + + # Function to insert a word into the Trie + def insert(self, word: str) -> None: + node = self.root + for char in word: + # If the current character doesn't exist in the Trie, create a new node + if char not in node.children: + node.children[char] = TrieNode() + # Move to next node + node = node.children[char] + # Mark the end of a word + node.is_end_of_word = True + + # Function to search for a word in the Trie + def search(self, word: str) -> bool: + node = self.root + for char in word: + # If the current character doesn't exist, the word doesn't exist + if char not in node.children: + return False + # Move to next node + node = node.children[char] + # Return True only if the last node is marked as the end of a word + return node.is_end_of_word + + # Function to check if a word is a prefix of any existing word in the Trie + def startsWith(self, prefix: str) -> bool: + node = self.root + for char in prefix: + # If the current character doesn't exist, the prefix doesn't exist + if char not in node.children: + return False + # Move to next node + node = node.children[char] + # The prefix exists if we reach this point + return True + From 41022242f274ba822dc12ae5fa6283e771557a45 Mon Sep 17 00:00:00 2001 From: Arsh Date: Sun, 2 Jul 2023 00:40:21 +0530 Subject: [PATCH 1524/1894] update trie.java --- Trees/{Binary Trees => }/trie.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) rename Trees/{Binary Trees => }/trie.java (69%) diff --git a/Trees/Binary Trees/trie.java b/Trees/trie.java similarity index 69% rename from Trees/Binary Trees/trie.java rename to Trees/trie.java index 0d27435b..86b472e3 100644 --- a/Trees/Binary Trees/trie.java +++ b/Trees/trie.java @@ -1,3 +1,15 @@ +/* +Description +A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + +Implement the Trie class: + +Trie() Initializes the trie object. +void insert(String word) Inserts the string word into the trie. +boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. +boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. +*/ + class Trie { Node root; From 656e4c7d7c47ff28a34ce617c350d11b3c91d6bd Mon Sep 17 00:00:00 2001 From: Arsh Date: Sun, 2 Jul 2023 01:10:34 +0530 Subject: [PATCH 1525/1894] Add comments --- Trees/trie.java | 43 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/Trees/trie.java b/Trees/trie.java index 86b472e3..2873d701 100644 --- a/Trees/trie.java +++ b/Trees/trie.java @@ -8,6 +8,30 @@ A trie (pronounced as "try") or prefix tree is a tree data structure used to eff void insert(String word) Inserts the string word into the trie. boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. + +Input +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] +Output +[null, null, true, false, true, null, true] + +Explanation +Trie trie = new Trie(); +trie.insert("apple"); +trie.search("apple"); // return True +trie.search("app"); // return False +trie.startsWith("app"); // return True +trie.insert("app"); +trie.search("app"); // return True + +Time Complexity for each operation is O(n) +Space Complexity O(n*m) where n is the number of words inserted and m is the average length of the words. + +Explanation: +insert() -> traverse through each character of the input word and initializes it if necessary. If the end of the word is reached set isEnd to true. +search() -> Search In each child node until the end of the word is reached, then if end of the node is also reached return true else false. +startsWith() -> Similar to search method but we only check if end of the prefix is reached and we don't need to check if it is the end of the node. + */ class Trie { @@ -37,32 +61,35 @@ class Node { nodes = new Node[26]; } + // Function to insert the word in the tree private void insert(String word, int idx) { - if (idx >= word.length()) return; + if (idx >= word.length()) return; // handle edge case int i = word.charAt(idx) - 'a'; if (nodes[i] == null) { - nodes[i] = new Node(); + nodes[i] = new Node(); // initialize the node[i] if the letter was not found before } - if (idx == word.length()-1) nodes[i].isEnd = true; - nodes[i].insert(word, idx+1); + if (idx == word.length()-1) nodes[i].isEnd = true; // signifies that this is the end of the word + nodes[i].insert(word, idx+1); // recursive call to populate the child node } + // Function to search the word in the tree private boolean search(String word, int idx) { if (idx >= word.length()) return false; Node node = nodes[word.charAt(idx) - 'a']; - if (node == null) return false; - if (idx == word.length() - 1 && node.isEnd) return true; + if (node == null) return false; // if the node is null it means that it was not initialised hence the character was never found. + if (idx == word.length() - 1 && node.isEnd) return true; //if it is the last character and the end of the node then return true - return node.search(word, idx+1); + return node.search(word, idx+1); // recursive call search in the child node } + //Function to search the prefix in tree private boolean startsWith(String prefix, int idx) { if (idx >= prefix.length()) return false; Node node = nodes[prefix.charAt(idx) - 'a']; if (node == null) return false; - if (idx == prefix.length() - 1) return true; + if (idx == prefix.length() - 1) return true; // Very similar to above method but here we don't need to check if it is the end of the node. return node.startsWith(prefix, idx+1); } From d2251ac175ddd092d3dd0487b48df2725d0dbc67 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Jul 2023 21:25:59 +0530 Subject: [PATCH 1526/1894] update contributing.md --- CONTRIBUTING.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7ad2931..806e47c3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -108,13 +108,3 @@ func SmallestDifference(array1, array2 []int) []int { } ``` - -## What if the problem you want to add is not present in the issue? - -- You can suggest an idea for this project under issues tab (add list of questions you think it is important, it will be assigned to you) -- You can directly make a PR against dev branch with the proposed problems with appropriate comments and description - -## What if the changes are inconsistent? - -- Keep pulling from origin/main see below, this way you will be up to date with the latest changes in main branch -- git pull origin main From a71fe019882f19341b7f3524906cb95c59a13e57 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Jul 2023 21:29:18 +0530 Subject: [PATCH 1527/1894] update c++ link for bs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f37eddb1..21f09fc5 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,7 @@ while (a <= b) { ## Example -[Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search_iterative.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.py) +[Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search_iterative.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.py) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.cpp) ## Method 2 From 09851e3600417ba0d98788a25c7ab9e79742420e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 2 Jul 2023 21:31:05 +0530 Subject: [PATCH 1528/1894] update link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 21f09fc5..9d1fec1d 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,7 @@ while (a <= b) { ## Example -[Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search_iterative.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.py) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.cpp) +[Go](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search_iterative.go) [Python](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.py) [C++](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.cpp) [JS](https://github.com/akgmage/data-structures-and-algorithms/blob/main/Binary%20Search/binary_search.js) ## Method 2 From 14f5df633cda82f29b1d5c12f86dcddba7ccfd1f Mon Sep 17 00:00:00 2001 From: Leapheng <93420923+leap-heng@users.noreply.github.com> Date: Mon, 3 Jul 2023 01:53:56 +0700 Subject: [PATCH 1529/1894] Add queries_on_number_of_points_inside_a_circles.cpp #448 --- ...s_on_number_of_points_inside_a_circles.cpp | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Math/queries_on_number_of_points_inside_a_circles.cpp diff --git a/Math/queries_on_number_of_points_inside_a_circles.cpp b/Math/queries_on_number_of_points_inside_a_circles.cpp new file mode 100644 index 00000000..c1060234 --- /dev/null +++ b/Math/queries_on_number_of_points_inside_a_circles.cpp @@ -0,0 +1,60 @@ +/* + You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. + You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. + For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. + Return an array answer, where answer[j] is the answer to the jth query. + + Example 1: + Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]] + Output: [3,2,2] + Explanation: + queries[0] is the first circle [2,3,1], which include the points [1,3], [2,2] and [3,3]. + queries[1] is the second circle [4,3,1], which include the points [3,3] and [5,3]. + and queries[2] is the third circle [1,1,2], which include the point [1,3] and [2,2]. + + + Example 2: + Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]] + Output: [2,3,2,4] + Explanation: + queries[0] is the first circle [1,2,2], which include the points [1,1] and [2,2]. + queries[1] is the second circle [2,2,2], which include the points [1,1], [2,2] and [3,3]. + queries[2] is the third circle [4,3,2], which include the points [3,3] and [4,4]. + and queries[3] is the fourth circle [4,3,3], which include the points [2,2], [3,3], [4,4] and [5,5]. + + Explanation of the approach: + 1. We will use the formula of distance between two points to find the distance between the center of the circle and the given point. + 2. If the distance is less than or equal to the radius of the circle, then the point lies inside the circle. + + Time Complexity: O(N * Q), where N is the number of points and Q is the number of queries. + Space Complexity: O(1) +*/ + +class Solution +{ +public: + vector countPoints(vector> &points, vector> &queries) + { + vector ans; + // Iterating over the queries. + for (int i = 0; i < queries.size(); i++) + { + // Initializing the count to 0. This will store the number of points inside the circle. + int count = 0; + // Iterating over the points. + for (int j = 0; j < points.size(); j++) + { + // Calculating the distance between the center of the circle and the given point. + int distance = pow(points[j][0] - queries[i][0], 2) + pow(points[j][1] - queries[i][1], 2); + // If the distance is less than or equal to the radius of the circle, then the point lies inside the circle. + if (distance <= pow(queries[i][2], 2)) + count++; // If the point lies inside the circle, then increment the count. + } + // Pushing the count to the answer vector. + ans.push_back(count); + } + return ans; + } + + // Further reading: https://www.geeksforgeeks.org/queries-points-number-points-lie-given-circle/ +}; \ No newline at end of file From 8edc1ce3511f2130a9ce443ca52b4f9c62ec0df9 Mon Sep 17 00:00:00 2001 From: Mridul Tripathi <98095736+mridul588@users.noreply.github.com> Date: Mon, 3 Jul 2023 15:05:01 +0530 Subject: [PATCH 1530/1894] Create max_ar_histogram.cpp --- Stacks/max_ar_histogram.cpp | 92 +++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Stacks/max_ar_histogram.cpp diff --git a/Stacks/max_ar_histogram.cpp b/Stacks/max_ar_histogram.cpp new file mode 100644 index 00000000..2154b8ba --- /dev/null +++ b/Stacks/max_ar_histogram.cpp @@ -0,0 +1,92 @@ +/*Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, +return the area of the largest rectangle in the histogram + +sample Input +1.Input: heights = [2,1,5,6,2,3] +Output: 10 +Explanation: The output represents the maximum area of a rectangle that can be formed using the heights in the given list. +The maximum area is achieved by selecting heights [2, 5, 6, 2], forming a rectangle of width 4 and height 2, resulting in +an area of 4 * 2 = 10. + +2.Input: heights = [2,4] +Output: 4 + + +Code LOGIC : +this code uses two stacks to find the left and right boundaries of each rectangle in the histogram. It then calculates the areas for each +rectangle and returns the maximum area found. + +Here's an explanation of the code: + +1.The largestRectangleArea function takes a vector a as input and returns an integer representing the largest rectangular area. + +2.The first step is to initialize some variables and containers. The variable n is assigned the size of the input vector a. If the size is 1, +the function immediately returns the single element as the largest area. + +3.Two additional vectors, l and r, are created to store the indices of the left and right boundaries of each rectangle. Two stacks, s1 and s2, +are used to keep track of elements and their corresponding indices. + +4.The first loop iterates through the elements of the vector a from left to right. For each element, it compares its value with the top element of s1. +If the top element is greater than or equal to the current element, it is popped from the stack until the stack is empty or the top element is smaller. +The index of the top element at the point of popping is assigned as the left boundary of the current element (stored in l). If the stack is empty after +the popping, it means there is no smaller element on the left, so -1 is assigned as the left boundary. Finally, the current element and its index are pushed onto s1. + +5.The second loop iterates through the elements of the vector a from right to left. It performs a similar operation as the first loop but using s2 instead of s1. +The right boundary indices are assigned to the vector r in this loop. + +6.After obtaining the left and right boundaries for each element, a new vector ans is created to store the areas of the rectangles. The area for each element is calculated +as the height of the rectangle (the value of the element) multiplied by the width (the difference between the right and left boundaries minus 1). + +7.The max_element function is used to find the maximum value in the ans vector, representing the largest area. This value is stored in the variable h. + +8.The function returns h, which is the largest rectangular area found in the histogram + +TIME and SPACE complexity +The time complexity of the code is O(n) because it involves iterating through the input vector a once, where n is the size of the vector. The space complexity is also O(n) because the code uses additional stacks and vectors to store intermediate results, each with a maximum size of n. +*/ + +class Solution { +public: + int largestRectangleArea(vector& a) { + int n = a.size(); + if(n==1){ + return a[0]; + } + vector l(n); vector r(n); + stack> s1; + stack> s2; + + for(int i=0;i 0 && (s1.top().first >= a[i])){ + s1.pop(); + } + if(s1.size()==0) l[i] = -1; + else l[i] = (s1.top().second); + + s1.push(make_pair(a[i],i)); + } + + + for(int i=a.size()-1;i>=0;i--){ + while(s2.size() > 0 && (s2.top().first >= a[i])){ + s2.pop(); + } + if(s2.size()==0) r[i] = (n); + else r[i] = (s2.top().second); + + s2.push(make_pair(a[i],i)); + } + + vector ans(n); + //int ans = -1; + for(int i=0 ;i Date: Mon, 3 Jul 2023 23:44:58 +0700 Subject: [PATCH 1531/1894] Find Longest Increasing Subsequence C++ #310 --- Math/find_longest_increasing_subsequence.cpp | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Math/find_longest_increasing_subsequence.cpp diff --git a/Math/find_longest_increasing_subsequence.cpp b/Math/find_longest_increasing_subsequence.cpp new file mode 100644 index 00000000..dbd928be --- /dev/null +++ b/Math/find_longest_increasing_subsequence.cpp @@ -0,0 +1,55 @@ +/* + Given an integer array nums, return the length of the longest strictly increasing subsequence. + + Example 1: + Input: nums = [10,9,2,5,3,7,101,18] + Output: 4 + Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. + + Example 2: + Input: nums = [0,1,0,3,2,3] + Output: 4 + Explanation: The longest increasing subsequence is [0,1,2,3], therefore the length is 4. + + Example 3: + Input: nums = [7,7,7,7,7,7,7] + Output: 1 + + Explanation of the approach: + 1. We will use the concept of Dynamic Programming to solve this problem. + 2. We will create a dp array of size n, where n is the size of the given array. + 3. We will initialize the dp array with 1, as the length of the longest increasing subsequence ending at any index is atleast 1. + 4. We will iterate over the array from the second index to the last index. + 5. For each index, we will iterate over the array from the first index to the current index. + 6. If the current element is greater than the element at the inner loop, then we will update the dp array at the current index with the maximum of the current value and the value at the inner loop + 1. + 7. We will return the maximum value in the dp array. + + Time Complexity: O(N^2), where N is the size of the given array. + Space Complexity: O(N), where N is the size of the given array. + +*/ + +class Solution{ +public: + int lengthOfLIS(vector &nums) + { + // Initializing the dp array with 1, as the length of the longest increasing subsequence ending at any index is atleast 1. + vector dp(nums.size(), 1); + // Iterating over the array from the second index to the last index. + for (int i = 1; i < nums.size(); i++) + { + // Iterating over the array from the first index to the current index. + for (int j = 0; j < i; j++) + { + // If the current element is greater than the element at the inner loop, then we will update the dp array at the current index with the maximum of the current value and the value at the inner loop + 1. + // This is because, if the current element is greater than the element at the inner loop, then we can add the current element to the increasing subsequence ending at the inner loop element, and the length of the increasing subsequence ending at the current element will be the length of the increasing subsequence ending at the inner loop element + 1. + // We will take the maximum of the current value and the value at the inner loop + 1, because we want to find the length of the longest increasing subsequence ending at the current element. + // We will update the dp array at the current index with the maximum of the current value and the value at the inner loop + 1. + if (nums[i] > nums[j]) + dp[i] = max(dp[i], dp[j] + 1); + } + } + // Returning the maximum value in the dp array. + return *max_element(dp.begin(), dp.end()); + } +}; \ No newline at end of file From 2d5ef95f1424cf2114f756df92e2a69b75f8b18c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Jul 2023 23:16:15 +0530 Subject: [PATCH 1532/1894] add remove island --- Graphs/remove_island.go | 91 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Graphs/remove_island.go diff --git a/Graphs/remove_island.go b/Graphs/remove_island.go new file mode 100644 index 00000000..37ce91d9 --- /dev/null +++ b/Graphs/remove_island.go @@ -0,0 +1,91 @@ +package main + +// Function to remove islands in a binary matrix +func RemoveIslands(matrix [][]int) [][]int { + // Create a boolean matrix to track if each cell is connected to the border + onesConnectedToBorder := make([][]bool, len(matrix)) + for i := range matrix { + onesConnectedToBorder[i] = make([]bool, len(matrix[0])) + } + + // Mark 1s connected to the border + for row := 0; row < len(matrix); row++ { + for col := 0; col < len(matrix[row]); col++ { + rowIsBorder := row == 0 || row == len(matrix)-1 + colIsBorder := col == 0 || col == len(matrix[row])-1 + isBorder := rowIsBorder || colIsBorder + + if !isBorder { + continue // Skip if not a border cell + } + + if matrix[row][col] != 1 { + continue // Skip if not a 1 + } + + findOnesConnectedToBorder(matrix, row, col, onesConnectedToBorder) + } + } + + // Remove non-border islands + for row := 0; row < len(matrix)-1; row++ { + for col := 0; col < len(matrix[row])-1; col++ { + if onesConnectedToBorder[row][col] { + continue // Skip if connected to the border + } + + matrix[row][col] = 0 // Set non-border island to 0 + } + } + + return matrix +} + +// Function to perform DFS and mark 1s connected to the border +func findOnesConnectedToBorder(matrix [][]int, startRow, startCol int, onesConnectedToBorder [][]bool) { + stack := [][]int{{startRow, startCol}} + var currentPosition []int + + for len(stack) > 0 { + currentPosition, stack = stack[len(stack)-1], stack[:len(stack)-1] + currentRow, currentCol := currentPosition[0], currentPosition[1] + alreadyVisited := onesConnectedToBorder[currentRow][currentCol] + + if alreadyVisited { + continue // Skip if already visited + } + + onesConnectedToBorder[currentRow][currentCol] = true // Mark cell as connected to the border + + neighbors := getNeighbors(matrix, currentRow, currentCol) + for _, neighbor := range neighbors { + row, col := neighbor[0], neighbor[1] + if matrix[row][col] != 1 { + continue // Skip if not a 1 + } + stack = append(stack, neighbor) // Add neighbor to the stack + } + } +} + +// Function to get valid neighboring cells +func getNeighbors(matrix [][]int, row, col int) [][]int { + neighbors := make([][]int, 0) + numRows := len(matrix) + numCols := len(matrix[row]) + + if row-1 >= 0 { + neighbors = append(neighbors, []int{row - 1, col}) // Top neighbor + } + if row+1 < numRows { + neighbors = append(neighbors, []int{row + 1, col}) // Bottom neighbor + } + if col-1 >= 0 { + neighbors = append(neighbors, []int{row, col - 1}) // Left neighbor + } + if col+1 < numCols { + neighbors = append(neighbors, []int{row, col + 1}) // Right neighbor + } + + return neighbors +} From 6cf8edc6ae7e9faa28a15741f9280df4112d9ed2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Jul 2023 23:18:23 +0530 Subject: [PATCH 1533/1894] add explanation --- Graphs/remove_island.go | 56 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Graphs/remove_island.go b/Graphs/remove_island.go index 37ce91d9..df2adf32 100644 --- a/Graphs/remove_island.go +++ b/Graphs/remove_island.go @@ -1,3 +1,59 @@ +/* + Explanation: + The provided code snippet is an implementation of the "Remove Islands" algorithm. This algorithm aims to identify and remove islands in a binary matrix. An island is a connected region of 1s surrounded by 0s. The algorithm marks islands connected to the border of the matrix as non-islands and returns the modified matrix. + + Let's break down the code snippet and explain each part: + + 1. Initialization: + + onesConnectedToBorder := make([][]bool, len(matrix)) + for i := range matrix { + onesConnectedToBorder[i] = make([]bool, len(matrix[0])) + } + + This part initializes a 2D boolean array `onesConnectedToBorder`, which has the same dimensions as the input matrix. It is used to mark cells that are connected to the border. + + 2. Marking Ones Connected to Border: + + for row := 0; row < len(matrix); row++ { + for col := 0; col < len(matrix[row]); col++ { + rowIsBorder := row == 0 || row == len(matrix)-1 + colIsBorder := col == 0 || col == len(matrix[row])-1 + isBorder := rowIsBorder || colIsBorder + if !isBorder { + continue + } + if matrix[row][col] != 1 { + continue + } + findOnesConnectedToBorder(matrix, row, col, onesConnectedToBorder) + } + } + + This part iterates through the matrix and checks if each cell is on the border. If a cell is on the border and contains a 1, it calls the `findOnesConnectedToBorder` function to mark the connected 1s using a depth-first search approach. The connected 1s are marked in the `onesConnectedToBorder` array. + + 3. Removing Non-Border Islands: + + for row := 0; row < len(matrix)-1; row++ { + for col := 0; col < len(matrix[row])-1; col++ { + if onesConnectedToBorder[row][col] { + continue + } + matrix[row][col] = 0 + } + } + + This part iterates through the matrix again, excluding the border cells. If a cell is not marked as connected to the border (an island cell), it is set to 0, effectively removing the island. + + 4. Utility Functions: + The code also includes two utility functions: + - `findOnesConnectedToBorder`: This function performs a depth-first search (DFS) to mark all the 1s connected to a border cell. It uses a stack to keep track of the cells to visit next. + - `getNeighbors`: This function returns the valid neighboring cells (up, down, left, right) for a given cell in the matrix. + + Finally, the modified matrix is returned as the result. + + Note: The code snippet provided assumes that the matrix is a 2D integer slice (`[][]int`) and uses Go syntax.. +*/ package main // Function to remove islands in a binary matrix From 425b442bc3b584eeb719f06a4c53f8efe2e2afa5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Jul 2023 23:19:38 +0530 Subject: [PATCH 1534/1894] add main func --- Graphs/remove_island.go | 48 +++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/Graphs/remove_island.go b/Graphs/remove_island.go index df2adf32..4839a6c6 100644 --- a/Graphs/remove_island.go +++ b/Graphs/remove_island.go @@ -5,16 +5,16 @@ Let's break down the code snippet and explain each part: 1. Initialization: - + onesConnectedToBorder := make([][]bool, len(matrix)) for i := range matrix { onesConnectedToBorder[i] = make([]bool, len(matrix[0])) } - + This part initializes a 2D boolean array `onesConnectedToBorder`, which has the same dimensions as the input matrix. It is used to mark cells that are connected to the border. 2. Marking Ones Connected to Border: - + for row := 0; row < len(matrix); row++ { for col := 0; col < len(matrix[row]); col++ { rowIsBorder := row == 0 || row == len(matrix)-1 @@ -29,11 +29,11 @@ findOnesConnectedToBorder(matrix, row, col, onesConnectedToBorder) } } - + This part iterates through the matrix and checks if each cell is on the border. If a cell is on the border and contains a 1, it calls the `findOnesConnectedToBorder` function to mark the connected 1s using a depth-first search approach. The connected 1s are marked in the `onesConnectedToBorder` array. 3. Removing Non-Border Islands: - + for row := 0; row < len(matrix)-1; row++ { for col := 0; col < len(matrix[row])-1; col++ { if onesConnectedToBorder[row][col] { @@ -42,7 +42,7 @@ matrix[row][col] = 0 } } - + This part iterates through the matrix again, excluding the border cells. If a cell is not marked as connected to the border (an island cell), it is set to 0, effectively removing the island. 4. Utility Functions: @@ -56,6 +56,8 @@ */ package main +import "fmt" + // Function to remove islands in a binary matrix func RemoveIslands(matrix [][]int) [][]int { // Create a boolean matrix to track if each cell is connected to the border @@ -145,3 +147,37 @@ func getNeighbors(matrix [][]int, row, col int) [][]int { return neighbors } + +func main() { + // Example usage + matrix := [][]int{ + {1, 0, 0, 0, 0, 0}, + {0, 1, 0, 1, 0, 1}, + {0, 0, 1, 0, 1, 1}, + {1, 1, 0, 0, 1, 0}, + {1, 0, 1, 1, 0, 0}, + } + + fmt.Println("Original Matrix:") + printMatrix(matrix) + + updatedMatrix := RemoveIslands(matrix) + + fmt.Println("Updated Matrix:") + printMatrix(updatedMatrix) +} + +// Helper function to print the matrix +func printMatrix(matrix [][]int) { + for _, row := range matrix { + for _, val := range row { + fmt.Printf("%d ", val) + } + fmt.Println() + } +} + + + + + From c68db1049969e44f8124c2d6a535f299bbac07fe Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Jul 2023 23:21:02 +0530 Subject: [PATCH 1535/1894] add sample io --- Graphs/remove_island.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Graphs/remove_island.go b/Graphs/remove_island.go index 4839a6c6..cd56d03a 100644 --- a/Graphs/remove_island.go +++ b/Graphs/remove_island.go @@ -1,6 +1,25 @@ /* + Remoev island that are not connected to Border + + Sample Input: + + 1 0 0 0 0 0 + 0 1 0 1 0 1 + 0 0 1 0 1 1 + 1 1 0 0 1 0 + 1 0 1 1 0 0 + + Output: + 1 0 0 0 0 0 + 0 0 0 0 0 1 + 0 0 0 0 1 1 + 1 1 0 0 1 0 + 1 0 1 1 0 0 + Explanation: - The provided code snippet is an implementation of the "Remove Islands" algorithm. This algorithm aims to identify and remove islands in a binary matrix. An island is a connected region of 1s surrounded by 0s. The algorithm marks islands connected to the border of the matrix as non-islands and returns the modified matrix. + The provided code snippet is an implementation of the "Remove Islands" algorithm. This algorithm aims to identify and remove + islands in a binary matrix. An island is a connected region of 1s surrounded by 0s. The algorithm marks islands connected + to the border of the matrix as non-islands and returns the modified matrix. Let's break down the code snippet and explain each part: From e6cda604594cd50da4daf879a34c28b8c922d543 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 3 Jul 2023 23:21:31 +0530 Subject: [PATCH 1536/1894] add time and space --- Graphs/remove_island.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Graphs/remove_island.go b/Graphs/remove_island.go index cd56d03a..e2ded215 100644 --- a/Graphs/remove_island.go +++ b/Graphs/remove_island.go @@ -71,6 +71,8 @@ Finally, the modified matrix is returned as the result. + O(wh) time | O(wh) space - where w and h are the width and height of the input matrix + Note: The code snippet provided assumes that the matrix is a 2D integer slice (`[][]int`) and uses Go syntax.. */ package main From bc21d371838ef07eefbf09186b90aa9c586eb03c Mon Sep 17 00:00:00 2001 From: Gilrav Date: Tue, 4 Jul 2023 12:41:17 +0300 Subject: [PATCH 1537/1894] cpp trie --- Trees/trie.cpp | 326 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 Trees/trie.cpp diff --git a/Trees/trie.cpp b/Trees/trie.cpp new file mode 100644 index 00000000..6773d8d8 --- /dev/null +++ b/Trees/trie.cpp @@ -0,0 +1,326 @@ +/* + trie for only lowercase English letters. +*/ + + +#include +#include +#include //TODO: + +enum{CHARS_IN_ALPHABET = 26}; + +class TrieNode{ +public: + TrieNode() : vec(CHARS_IN_ALPHABET, nullptr), end_of_str(false) {}; + + std::vector vec; + bool end_of_str; +}; +/****************************************************************************/ +class Trie { +public: + Trie(); + ~Trie(); + Trie(const Trie& other) = delete; + Trie& operator= (const Trie& other) = delete; + + void Insert(std::string word); + bool Delete(std::string word); + bool Search(std::string word); + bool startWith(std::string prefix); + void Destroy(TrieNode* root); + +private: + enum RecDeleteStatus{NOT_FOUND = -1, DELETE = 0 , COMPLITE = 1}; + + RecDeleteStatus RecDelete(TrieNode* curr_node, const char* string_ptr); + bool IsLeaf(TrieNode* node); + TrieNode* CreatNodes(TrieNode* node_runner, const char* rest_letters); + TrieNode* FindLastChar(const char* first_char_string); + + TrieNode* m_root; +}; +/****************************************************************************/ +Trie::Trie() +{ + m_root = new TrieNode(); +} +/****************************************************************************/ +Trie::~Trie() +{ + Destroy(m_root); + delete m_root; +} +/****************************************************************************/ +void Trie::Insert(std::string word) +{ + const char* string_ptr = word.data(); + TrieNode* node_runner = m_root; + + while(*string_ptr) + { + if(!node_runner->vec[*string_ptr - 'a']) + { + node_runner = CreatNodes(node_runner, string_ptr); + break; + } + + node_runner = node_runner->vec[*string_ptr - 'a']; + ++string_ptr; + } + node_runner->end_of_str = true; +} +/****************************************************************************/ +bool Trie::Delete(std::string word) +{ + if(RecDelete(m_root, word.data()) != NOT_FOUND) + { + return true; + } + return false; +} +/****************************************************************************/ +bool Trie::Search(std::string word) +{ + TrieNode* node = FindLastChar(word.data()); + + if(node == nullptr || node->end_of_str == false){ + return false; + } + return true; +} +/****************************************************************************/ +bool Trie::startWith(std::string prefix) +{ + TrieNode* node = FindLastChar(prefix.data()); + + if(node == nullptr){ + return false; + } + return true; +} +/****************************************************************************/ +Trie::RecDeleteStatus Trie::RecDelete(TrieNode* curr_node, const char* string_ptr) +{ + if(curr_node == nullptr) + { + return NOT_FOUND; + } + if(*string_ptr == '\0') + { + return DELETE; + } + + int char_idx = *string_ptr - 'a'; + RecDeleteStatus status = RecDelete(curr_node->vec[char_idx], string_ptr + 1); + + if(status == DELETE) + { + if(IsLeaf(curr_node->vec[char_idx])) + { + delete curr_node->vec[char_idx]; + curr_node->vec[char_idx] = nullptr; + return DELETE; + } + else if(*(string_ptr + 1) == '\0') + { + if(curr_node->vec[char_idx]->end_of_str) + { + curr_node->vec[char_idx]->end_of_str = false; + return DELETE; + } + else + { + return NOT_FOUND; + } + } + } + if(status == NOT_FOUND) + { + return NOT_FOUND; + } + return COMPLITE; +} +/****************************************************************************/ +bool Trie::IsLeaf(TrieNode* curr_node) +{ + for(auto it : curr_node->vec) + { + if(it != nullptr) + { + return false; + } + } + return true; +} +/****************************************************************************/ +TrieNode* Trie::CreatNodes(TrieNode* node_runner, const char* string_ptr) +{ + while(*string_ptr) + { + TrieNode* new_node = new TrieNode(); + + node_runner->vec[*string_ptr - 'a'] = new_node; + node_runner = new_node; + ++string_ptr; + } + + return node_runner; +} +/****************************************************************************/ +TrieNode* Trie::FindLastChar(const char* string_ptr) +{ + TrieNode* node_runner = m_root; + + while(*string_ptr) + { + TrieNode* next_node = node_runner->vec[*string_ptr - 'a']; + if(nullptr == next_node) + { + return nullptr; + } + + node_runner = next_node; + ++string_ptr; + } + return node_runner; +} +/****************************************************************************/ +void Trie::Destroy(TrieNode* node) +{ + if(node == nullptr) + { + return; + } + for(auto it : node->vec) + { + Destroy(it); + delete it; + } +} + +///////////////////////////////////////////// + +void search(); +void deleteaa(); +void startw(); + +int main(){ + + search(); + deleteaa(); + startw(); + + return 0; +} +void startw() +{ + Trie trie; + + if(trie.startWith("abc") != false){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("z") != false){ + std::cout << "faile" << std::endl; + } + trie.Insert("abcd"); + if(trie.startWith("a") != true){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("ab") != true){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("abc") != true){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("abcd") != true){ + std::cout << "faile" << std::endl; + } + + if(trie.startWith("as") != false){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("abs") != false){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("abcs") != false){ + std::cout << "faile" << std::endl; + } + if(trie.startWith("abcds") != false){ + std::cout << "faile" << std::endl; + } +} +void deleteaa() +{ + Trie trie; + + if(trie.Delete("abc") != false){ + std::cout << "faile" << std::endl; + } + + trie.Insert("abcd"); + + if(trie.Delete("abcd") != true){ + std::cout << "faile" << std::endl; + } + if(trie.Search("abcd") != false){ + std::cout << "faile" << std::endl; + } + + trie.Insert("abcd"); + + if(trie.Delete("abc") != false){ + std::cout << "faile" << std::endl; + } + + trie.Insert("abc"); + if(trie.Search("abcd") != true){ + std::cout << "faile" << std::endl; + } + + if(trie.Delete("abc") != true){ + std::cout << "faile" << std::endl; + } + if(trie.Search("abc") != false){ + std::cout << "faile" << std::endl; + } + + trie.Insert("abcd"); + + if(trie.Delete("abcd") != true){ + std::cout << "faile" << std::endl; + } +} +void search() +{ + Trie trie; + + if(trie.Search("abcd") != false){ + std::cout << "faile" << std::endl; + } + if(trie.Search("") != false){ + std::cout << "faile" << std::endl; + } + if(trie.Search("c") != false){ + std::cout << "faile" << std::endl; + } + + + trie.Insert("abcd"); + + if(trie.Search("abc") != false){ + std::cout << "faile" << std::endl; + } + + if(trie.Search("abcde") != false){ + std::cout << "faile" << std::endl; + } + + if(trie.Search("vdds") != false){ + std::cout << "faile" << std::endl; + } + + if(trie.Search("abcd") != true){ + std::cout << "faile" << std::endl; + } +} \ No newline at end of file From 54bdca016b1531fcc523c9acee170ae072a3f0d2 Mon Sep 17 00:00:00 2001 From: Gilrav Date: Tue, 4 Jul 2023 12:56:55 +0300 Subject: [PATCH 1538/1894] cpp trie --- Trees/trie.cpp | 127 ------------------------------------------------- 1 file changed, 127 deletions(-) diff --git a/Trees/trie.cpp b/Trees/trie.cpp index 6773d8d8..9c95be52 100644 --- a/Trees/trie.cpp +++ b/Trees/trie.cpp @@ -5,7 +5,6 @@ #include #include -#include //TODO: enum{CHARS_IN_ALPHABET = 26}; @@ -198,129 +197,3 @@ void Trie::Destroy(TrieNode* node) delete it; } } - -///////////////////////////////////////////// - -void search(); -void deleteaa(); -void startw(); - -int main(){ - - search(); - deleteaa(); - startw(); - - return 0; -} -void startw() -{ - Trie trie; - - if(trie.startWith("abc") != false){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("z") != false){ - std::cout << "faile" << std::endl; - } - trie.Insert("abcd"); - if(trie.startWith("a") != true){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("ab") != true){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("abc") != true){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("abcd") != true){ - std::cout << "faile" << std::endl; - } - - if(trie.startWith("as") != false){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("abs") != false){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("abcs") != false){ - std::cout << "faile" << std::endl; - } - if(trie.startWith("abcds") != false){ - std::cout << "faile" << std::endl; - } -} -void deleteaa() -{ - Trie trie; - - if(trie.Delete("abc") != false){ - std::cout << "faile" << std::endl; - } - - trie.Insert("abcd"); - - if(trie.Delete("abcd") != true){ - std::cout << "faile" << std::endl; - } - if(trie.Search("abcd") != false){ - std::cout << "faile" << std::endl; - } - - trie.Insert("abcd"); - - if(trie.Delete("abc") != false){ - std::cout << "faile" << std::endl; - } - - trie.Insert("abc"); - if(trie.Search("abcd") != true){ - std::cout << "faile" << std::endl; - } - - if(trie.Delete("abc") != true){ - std::cout << "faile" << std::endl; - } - if(trie.Search("abc") != false){ - std::cout << "faile" << std::endl; - } - - trie.Insert("abcd"); - - if(trie.Delete("abcd") != true){ - std::cout << "faile" << std::endl; - } -} -void search() -{ - Trie trie; - - if(trie.Search("abcd") != false){ - std::cout << "faile" << std::endl; - } - if(trie.Search("") != false){ - std::cout << "faile" << std::endl; - } - if(trie.Search("c") != false){ - std::cout << "faile" << std::endl; - } - - - trie.Insert("abcd"); - - if(trie.Search("abc") != false){ - std::cout << "faile" << std::endl; - } - - if(trie.Search("abcde") != false){ - std::cout << "faile" << std::endl; - } - - if(trie.Search("vdds") != false){ - std::cout << "faile" << std::endl; - } - - if(trie.Search("abcd") != true){ - std::cout << "faile" << std::endl; - } -} \ No newline at end of file From 9be3d8c658fc8696f97aa98b0c68a03060bf6e91 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Tue, 4 Jul 2023 18:05:52 +0530 Subject: [PATCH 1539/1894] Create Implement_Trie.cpp --- Trees/Implement_Trie.cpp | 115 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 Trees/Implement_Trie.cpp diff --git a/Trees/Implement_Trie.cpp b/Trees/Implement_Trie.cpp new file mode 100644 index 00000000..7aa8ed5e --- /dev/null +++ b/Trees/Implement_Trie.cpp @@ -0,0 +1,115 @@ +/* +Approach: +- We define a Trie node structure that contains an array of child nodes and a flag to indicate the end of a word. +- The Trie class provides methods to insert words into the Trie, search for words, and check if any word starts with a given prefix. +- The insert operation involves traversing the Trie for each character of the word and creating a new node if the path doesn't exist. At the end, we mark the last node as the end of a word. +- The search operation is similar to the insert operation, but it returns true only if the last node is marked as the end of a word. +- The startsWith operation also involves traversing the Trie for each character of the prefix. It returns true regardless of whether the last node is marked as the end of a word or not. + +Time Complexity: +- The time complexity of inserting a word into the Trie is O(m), where m is the length of the word. +- The time complexity of searching for a word or checking for a prefix is O(m), where m is the length of the word or prefix. + +Space Complexity: +- The space complexity of the Trie is O(N * M), where N is the number of words and M is the average length of the words. + +Sample Input / Output: +int main() { + Trie trie; + + trie.insert("apple"); + trie.insert("banana"); + + cout << trie.search("apple") << endl; // Output: 1 (true) + cout << trie.search("banana") << endl; // Output: 1 (true) + cout << trie.search("car") << endl; // Output: 0 (false) + + cout << trie.startsWith("app") << endl; // Output: 1 (true) + cout << trie.startsWith("ban") << endl; // Output: 1 (true) + cout << trie.startsWith("cab") << endl; // Output: 0 (false) + + return 0; +} + +*/ + +//Here's the code for implementing a Trie (Prefix Tree) in C++: + +// Trie node structure +struct TrieNode { + struct TrieNode* children[26]; // Array to store child nodes + bool isEndOfWord; // Flag to indicate end of word + TrieNode() { + isEndOfWord = false; + for (int i = 0; i < 26; i++) + children[i] = nullptr; + } +}; + +// Trie class +class Trie { +private: + TrieNode* root; // Pointer to the root node + +public: + Trie() { + root = new TrieNode(); + } + + // Insert a word into the Trie + void insert(string word) { + TrieNode* current = root; + + for (char ch : word) { + int index = ch - 'a'; + + // Create a new node if the path doesn't exist + if (!current->children[index]) { + current->children[index] = new TrieNode(); + } + + current = current->children[index]; + } + + // Mark the end of a word + current->isEndOfWord = true; + } + + // Search for a word in the Trie + bool search(string word) { + TrieNode* current = root; + + for (char ch : word) { + int index = ch - 'a'; + + // Return false if the path doesn't exist + if (!current->children[index]) { + return false; + } + + current = current->children[index]; + } + + // Return true only if the current node is the end of a word + return current->isEndOfWord; + } + + // Check if any word in the Trie starts with the given prefix + bool startsWith(string prefix) { + TrieNode* current = root; + + for (char ch : prefix) { + int index = ch - 'a'; + + // Return false if the path doesn't exist + if (!current->children[index]) { + return false; + } + + current = current->children[index]; + } + + // Return true regardless of whether the current node is the end of a word or not + return true; + } +}; From 625ab6d4e44c84bf2ca8080ac20a978dce3f8b46 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:28:35 +0530 Subject: [PATCH 1540/1894] add yca in go --- Graphs/youngest_common_ancestor.go | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Graphs/youngest_common_ancestor.go diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go new file mode 100644 index 00000000..6c9ed201 --- /dev/null +++ b/Graphs/youngest_common_ancestor.go @@ -0,0 +1,36 @@ +package main + +type AncestralTree struct { + Name string + Ancestor *AncestralTree +} + +func GetYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo *AncestralTree) *AncestralTree { + depthOne := getDescendantDepth(descendantOne, topAncestor) + depthTwo := getDescendantDepth(descendantTwo, topAncestor) + if depthOne > depthTwo { + return backTrackAncestralTree(descendantOne, descendantTwo, depthOne-depthTwo) + } + return backTrackAncestralTree(descendantTwo, descendantOne, depthTwo-depthOne) +} + +func getDescendantDepth(descendant, topAncestor *AncestralTree) int { + depth := 0 + for descendant != topAncestor { + depth++ + descendant = descendant.Ancestor + } + return depth +} + +func backTrackAncestralTree(lowestDescendant, higherDescendant *AncestralTree, diff int) *AncestralTree { + for diff > 0 { + lowestDescendant = lowestDescendant.Ancestor + diff-- + } + for lowestDescendant != higherDescendant { + lowestDescendant = lowestDescendant.Ancestor + higherDescendant = higherDescendant.Ancestor + } + return lowestDescendant +} \ No newline at end of file From f554300b73a6e9c2560d987152082fdfb6e9b680 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:30:53 +0530 Subject: [PATCH 1541/1894] add explanation --- Graphs/youngest_common_ancestor.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index 6c9ed201..d6647c6d 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -1,3 +1,27 @@ +/* + Explanation: + + This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. + + - `type AncestralTree struct` defines the structure of a node in the ancestral tree, which contains a name and a + reference to its ancestor node. + + - `func GetYoungestCommonAncestor` is the main function that takes three parameters: `topAncestor` (the topmost ancestor + in the tree), `descendantOne` (the first descendant), and `descendantTwo` (the second descendant). It calculates the depths of the two descendants from the top ancestor and then calls the `backTrackAncestralTree` function with the appropriate parameters. + + - `func getDescendantDepth` calculates the depth of a descendant node from the top ancestor. It iteratively increments the + depth and traverses through the ancestors until reaching the top ancestor. + + - `func backTrackAncestralTree` is a helper function that backtracks the ancestral tree starting from the lowest descendant + until the depths of both descendants are equal. It first adjusts the position of the lowest descendant based on the depth difference between the two descendants. Then, it moves both descendants up the tree in tandem until they reach the same ancestor node, which is the youngest common ancestor. + + The code assumes that the `topAncestor` provided is a valid ancestor of both `descendantOne` and `descendantTwo`. + The `GetYoungestCommonAncestor` function returns the youngest common ancestor found in the ancestral tree. + + To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. + You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common + ancestor of two descendants. +*/ package main type AncestralTree struct { From e264373e33cc9ef01d28c5b69c8ac06bc978b4f8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:31:08 +0530 Subject: [PATCH 1542/1894] add comments --- Graphs/youngest_common_ancestor.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index d6647c6d..4a947a72 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -29,15 +29,23 @@ type AncestralTree struct { Ancestor *AncestralTree } +// GetYoungestCommonAncestor finds the youngest common ancestor of two descendants in an ancestral tree. func GetYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo *AncestralTree) *AncestralTree { + // Calculate the depths of the two descendants from the top ancestor depthOne := getDescendantDepth(descendantOne, topAncestor) depthTwo := getDescendantDepth(descendantTwo, topAncestor) + if depthOne > depthTwo { + // If depthOne is greater, backtrack the ancestral tree from descendantOne to align the depths return backTrackAncestralTree(descendantOne, descendantTwo, depthOne-depthTwo) } + + // If depthTwo is greater or both depths are equal, backtrack the ancestral tree from descendantTwo + // to align the depths return backTrackAncestralTree(descendantTwo, descendantOne, depthTwo-depthOne) } +// getDescendantDepth calculates the depth of a descendant node from the top ancestor. func getDescendantDepth(descendant, topAncestor *AncestralTree) int { depth := 0 for descendant != topAncestor { @@ -47,14 +55,19 @@ func getDescendantDepth(descendant, topAncestor *AncestralTree) int { return depth } +// backTrackAncestralTree backtracks the ancestral tree to find the youngest common ancestor. func backTrackAncestralTree(lowestDescendant, higherDescendant *AncestralTree, diff int) *AncestralTree { + // Adjust the position of the lowest descendant based on the depth difference for diff > 0 { lowestDescendant = lowestDescendant.Ancestor diff-- } + + // Move both descendants up the tree until they reach the same ancestor node for lowestDescendant != higherDescendant { lowestDescendant = lowestDescendant.Ancestor higherDescendant = higherDescendant.Ancestor } + return lowestDescendant -} \ No newline at end of file +} From 296068f99ac56379dea5f54afd67b232f75a3baa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:31:31 +0530 Subject: [PATCH 1543/1894] add time and space complexity --- Graphs/youngest_common_ancestor.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index 4a947a72..3b5f7188 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -21,6 +21,8 @@ To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common ancestor of two descendants. + + O(d) time | O(1) space - where d is the depth (height) of the ancestral tree */ package main From f2b4778acfc3f3e2b2efd4d3fa6c428882f57d49 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:32:54 +0530 Subject: [PATCH 1544/1894] add sample io --- Graphs/youngest_common_ancestor.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index 3b5f7188..ee0ab0a0 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -1,4 +1,17 @@ /* + Sample Input: + Top ancestor: node A + descendantOne: node e + descandantTwo: node I + + Output: node B + A + / \ + B C + / \ / \ + D E F G + / \ +H I Explanation: This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. From a8adfa795150cd960b4b1f83a5a77e592b45de1a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:35:05 +0530 Subject: [PATCH 1545/1894] add main func --- Graphs/youngest_common_ancestor.go | 35 ++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index ee0ab0a0..44d128eb 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -1,4 +1,7 @@ /* + + Write a function that returns the youngest common ancestor to the two descendants. + Sample Input: Top ancestor: node A descendantOne: node e @@ -39,6 +42,8 @@ H I */ package main +import "fmt" + type AncestralTree struct { Name string Ancestor *AncestralTree @@ -86,3 +91,33 @@ func backTrackAncestralTree(lowestDescendant, higherDescendant *AncestralTree, d return lowestDescendant } + + +func main() { + // Create the ancestral tree + topAncestor := &AncestralTree{Name: "A"} + B := &AncestralTree{Name: "B", Ancestor: topAncestor} + C := &AncestralTree{Name: "C", Ancestor: topAncestor} + D := &AncestralTree{Name: "D", Ancestor: B} + F := &AncestralTree{Name: "F", Ancestor: C} + I := &AncestralTree{Name: "I", Ancestor: D} + + // Set up the ancestral relationships + + // A + // / \ + // B C + // / \ / \ + // D E F G + // / + // H + // / + // I + + // Find the youngest common ancestor of two descendants + descendantOne := F + descendantTwo := I + yca := GetYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) + + fmt.Printf("The youngest common ancestor of %s and %s is %s.\n", descendantOne.Name, descendantTwo.Name, yca.Name) +} \ No newline at end of file From e73a3d824a35b42e80578a1130a86abe2dc9139c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:35:10 +0530 Subject: [PATCH 1546/1894] add main func --- Graphs/youngest_common_ancestor.go | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/Graphs/youngest_common_ancestor.go b/Graphs/youngest_common_ancestor.go index 44d128eb..4d84149e 100644 --- a/Graphs/youngest_common_ancestor.go +++ b/Graphs/youngest_common_ancestor.go @@ -102,19 +102,6 @@ func main() { F := &AncestralTree{Name: "F", Ancestor: C} I := &AncestralTree{Name: "I", Ancestor: D} - // Set up the ancestral relationships - - // A - // / \ - // B C - // / \ / \ - // D E F G - // / - // H - // / - // I - - // Find the youngest common ancestor of two descendants descendantOne := F descendantTwo := I yca := GetYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) From b79fbab3df3b7fcbad2405896ea9dd3f956adfef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:38:14 +0530 Subject: [PATCH 1547/1894] add yca for c++ --- Graphs/youngest_common_ancestor.cpp | 147 ++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 Graphs/youngest_common_ancestor.cpp diff --git a/Graphs/youngest_common_ancestor.cpp b/Graphs/youngest_common_ancestor.cpp new file mode 100644 index 00000000..c7ffde84 --- /dev/null +++ b/Graphs/youngest_common_ancestor.cpp @@ -0,0 +1,147 @@ +/* + + Write a function that returns the youngest common ancestor to the two descendants. + + Sample Input: + Top ancestor: node A + descendantOne: node e + descandantTwo: node I + + Output: node B + A + / \ + B C + / \ / \ + D E F G + / \ +H I + Explanation: + + This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. + + - `type AncestralTree struct` defines the structure of a node in the ancestral tree, which contains a name and a + reference to its ancestor node. + + - `func GetYoungestCommonAncestor` is the main function that takes three parameters: `topAncestor` (the topmost ancestor + in the tree), `descendantOne` (the first descendant), and `descendantTwo` (the second descendant). It calculates the depths of the two descendants from the top ancestor and then calls the `backTrackAncestralTree` function with the appropriate parameters. + + - `func getDescendantDepth` calculates the depth of a descendant node from the top ancestor. It iteratively increments the + depth and traverses through the ancestors until reaching the top ancestor. + + - `func backTrackAncestralTree` is a helper function that backtracks the ancestral tree starting from the lowest descendant + until the depths of both descendants are equal. It first adjusts the position of the lowest descendant based on the depth difference between the two descendants. Then, it moves both descendants up the tree in tandem until they reach the same ancestor node, which is the youngest common ancestor. + + The code assumes that the `topAncestor` provided is a valid ancestor of both `descendantOne` and `descendantTwo`. + The `GetYoungestCommonAncestor` function returns the youngest common ancestor found in the ancestral tree. + + To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. + You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common + ancestor of two descendants. + + O(d) time | O(1) space - where d is the depth (height) of the ancestral tree +*/ +#include +#include +#include + +using namespace std; + +class AncestralTree { +public: + string name; + AncestralTree* ancestor; + + AncestralTree(string name) { + this->name = name; + this->ancestor = NULL; + } +}; + +// Function to calculate the depth of a descendant from the top ancestor +int getDescendantDepth(AncestralTree* descendant, AncestralTree* topAncestor) { + int depth = 0; + while (descendant != topAncestor) { + depth++; + descendant = descendant->ancestor; + } + return depth; +} + +// Function to backtrack and find the youngest common ancestor +AncestralTree* backTrackAncestralTree(AncestralTree* lowestDescendant, AncestralTree* higherDescendant, int diff) { + while (diff > 0) { + lowestDescendant = lowestDescendant->ancestor; + diff--; + } + while (lowestDescendant != higherDescendant) { + lowestDescendant = lowestDescendant->ancestor; + higherDescendant = higherDescendant->ancestor; + } + return lowestDescendant; +} + +// Function to find the youngest common ancestor of two descendants +AncestralTree* getYoungestCommonAncestor(AncestralTree* topAncestor, AncestralTree* descendantOne, AncestralTree* descendantTwo) { + int depthOne = getDescendantDepth(descendantOne, topAncestor); + int depthTwo = getDescendantDepth(descendantTwo, topAncestor); + + if (depthOne > depthTwo) { + return backTrackAncestralTree(descendantOne, descendantTwo, depthOne - depthTwo); + } + return backTrackAncestralTree(descendantTwo, descendantOne, depthTwo - depthOne); +} + +int main() { + // Create the ancestral tree + AncestralTree* topAncestor = new AncestralTree("A"); + AncestralTree* B = new AncestralTree("B"); + AncestralTree* C = new AncestralTree("C"); + AncestralTree* D = new AncestralTree("D"); + AncestralTree* E = new AncestralTree("E"); + AncestralTree* F = new AncestralTree("F"); + AncestralTree* G = new AncestralTree("G"); + AncestralTree* H = new AncestralTree("H"); + AncestralTree* I = new AncestralTree("I"); + + // Set up the ancestral relationships + + // A + // / \ + // B C + // / \ / \ + // D E F G + // / + // H + // / + // I + + topAncestor->ancestor = NULL; + B->ancestor = topAncestor; + C->ancestor = topAncestor; + D->ancestor = B; + E->ancestor = B; + F->ancestor = C; + G->ancestor = C; + H->ancestor = D; + I->ancestor = H; + + // Find the youngest common ancestor of two descendants + AncestralTree* descendantOne = F; + AncestralTree* descendantTwo = I; + AncestralTree* yca = getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo); + + cout << "The youngest common ancestor of " << descendantOne->name << " and " << descendantTwo->name << " is " << yca->name << "." << endl; + + // Clean up memory + delete topAncestor; + delete B; + delete C; + delete D; + delete E; + delete F; + delete G; + delete H; + delete I; + + return 0; +} From 82a07f5af2ca5dae34325ba66f1822eb67604371 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 4 Jul 2023 23:40:04 +0530 Subject: [PATCH 1548/1894] add yca in python --- Graphs/youngest_common_ancestor.py | 112 +++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 Graphs/youngest_common_ancestor.py diff --git a/Graphs/youngest_common_ancestor.py b/Graphs/youngest_common_ancestor.py new file mode 100644 index 00000000..f48cf6c6 --- /dev/null +++ b/Graphs/youngest_common_ancestor.py @@ -0,0 +1,112 @@ +''' + Write a function that returns the youngest common ancestor to the two descendants. + + Sample Input: + Top ancestor: node A + descendantOne: node e + descandantTwo: node I + + Output: node B + A + / \ + B C + / \ / \ + D E F G + / \ + H I + Explanation: + + This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. + + - `type AncestralTree struct` defines the structure of a node in the ancestral tree, which contains a name and a + reference to its ancestor node. + + - `func GetYoungestCommonAncestor` is the main function that takes three parameters: `topAncestor` (the topmost ancestor + in the tree), `descendantOne` (the first descendant), and `descendantTwo` (the second descendant). It calculates the depths of the two descendants from the top ancestor and then calls the `backTrackAncestralTree` function with the appropriate parameters. + + - `func getDescendantDepth` calculates the depth of a descendant node from the top ancestor. It iteratively increments the + depth and traverses through the ancestors until reaching the top ancestor. + + - `func backTrackAncestralTree` is a helper function that backtracks the ancestral tree starting from the lowest descendant + until the depths of both descendants are equal. It first adjusts the position of the lowest descendant based on the depth difference between the two descendants. Then, it moves both descendants up the tree in tandem until they reach the same ancestor node, which is the youngest common ancestor. + + The code assumes that the `topAncestor` provided is a valid ancestor of both `descendantOne` and `descendantTwo`. + The `GetYoungestCommonAncestor` function returns the youngest common ancestor found in the ancestral tree. + + To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. + You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common + ancestor of two descendants. + + O(d) time | O(1) space - where d is the depth (height) of the ancestral tree +''' +class AncestralTree: + def __init__(self, name): + self.name = name + self.ancestor = None + +# Function to calculate the depth of a descendant from the top ancestor +def get_descendant_depth(descendant, top_ancestor): + depth = 0 + while descendant != top_ancestor: + depth += 1 + descendant = descendant.ancestor + return depth + +# Function to backtrack and find the youngest common ancestor +def back_track_ancestral_tree(lowest_descendant, higher_descendant, diff): + while diff > 0: + lowest_descendant = lowest_descendant.ancestor + diff -= 1 + while lowest_descendant != higher_descendant: + lowest_descendant = lowest_descendant.ancestor + higher_descendant = higher_descendant.ancestor + return lowest_descendant + +# Function to find the youngest common ancestor of two descendants +def get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two): + depth_one = get_descendant_depth(descendant_one, top_ancestor) + depth_two = get_descendant_depth(descendant_two, top_ancestor) + + if depth_one > depth_two: + return back_track_ancestral_tree(descendant_one, descendant_two, depth_one - depth_two) + return back_track_ancestral_tree(descendant_two, descendant_one, depth_two - depth_one) + +# Create the ancestral tree +top_ancestor = AncestralTree("A") +B = AncestralTree("B") +C = AncestralTree("C") +D = AncestralTree("D") +E = AncestralTree("E") +F = AncestralTree("F") +G = AncestralTree("G") +H = AncestralTree("H") +I = AncestralTree("I") + +# Set up the ancestral relationships + +# A +# / \ +# B C +# / \ / \ +# D E F G +# / +# H +# / +# I + +top_ancestor.ancestor = None +B.ancestor = top_ancestor +C.ancestor = top_ancestor +D.ancestor = B +E.ancestor = B +F.ancestor = C +G.ancestor = C +H.ancestor = D +I.ancestor = H + +# Find the youngest common ancestor of two descendants +descendant_one = F +descendant_two = I +yca = get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two) + +print("The youngest common ancestor of", descendant_one.name, "and", descendant_two.name, "is", yca.name) From e1c96c537b237781b99098c8160651f26c34ed08 Mon Sep 17 00:00:00 2001 From: Gilrav Date: Wed, 5 Jul 2023 12:54:23 +0300 Subject: [PATCH 1549/1894] add comments and explanation according to convention --- Trees/trie.cpp | 65 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 6 deletions(-) diff --git a/Trees/trie.cpp b/Trees/trie.cpp index 9c95be52..225b7784 100644 --- a/Trees/trie.cpp +++ b/Trees/trie.cpp @@ -1,5 +1,39 @@ /* - trie for only lowercase English letters. + https://leetcode.com/problems/implement-trie-prefix-tree/ + + Implement Trie (also called 'prefix tree') which supports lowercase letters only, + a search tree with multiple childrens (26 in this case). + methods: Insert - push new string into the tree. + Delete - remove string from the tree. + search - check if a string is already pushed into the tree. + StartWith - check if sum prefix is appear in the tree. + + Example: + + int main(){ + Trie trie; + + trie.Insert("abcd"); + trie.Search("abcd") // return true; + trie.Search("ab") // return false; + trie.startWith("ab") // return true; + + trie.Insert("ab"); + trie.Search("ab") // return true; + + trie.Delete("ab") + trie.Search("ab") // return false; + trie.Search("abcd") // return true; + + return 0; + } + + Time Complexity: + Insert() / Search() / startWith() | Average & Worst-case == O(m) | m == number of chars in string. + + Space Complexity: + Space complexity for a trie: O(k * N) | k == size of the node, N == number of the different nodes. + */ @@ -12,6 +46,7 @@ class TrieNode{ public: TrieNode() : vec(CHARS_IN_ALPHABET, nullptr), end_of_str(false) {}; +// every node has a vector for his childrens and a flag to mark - end of word. std::vector vec; bool end_of_str; }; @@ -20,6 +55,7 @@ class Trie { public: Trie(); ~Trie(); + // non-copyable class Trie(const Trie& other) = delete; Trie& operator= (const Trie& other) = delete; @@ -40,17 +76,18 @@ class Trie { TrieNode* m_root; }; /****************************************************************************/ -Trie::Trie() +Trie::Trie() // Ctor { m_root = new TrieNode(); } /****************************************************************************/ -Trie::~Trie() +Trie::~Trie() // Dtor { Destroy(m_root); delete m_root; } /****************************************************************************/ +// function for push a word(string) inside the trie void Trie::Insert(std::string word) { const char* string_ptr = word.data(); @@ -58,18 +95,22 @@ void Trie::Insert(std::string word) while(*string_ptr) { + // if this node does not have this latter as a child yet. if(!node_runner->vec[*string_ptr - 'a']) { node_runner = CreatNodes(node_runner, string_ptr); break; } - + node_runner = node_runner->vec[*string_ptr - 'a']; ++string_ptr; } + // mark node as end of word. node_runner->end_of_str = true; } /****************************************************************************/ +// function for remove a word from the trie, if the word or part of her suffix +// stand alone, the whole node will be removed. bool Trie::Delete(std::string word) { if(RecDelete(m_root, word.data()) != NOT_FOUND) @@ -79,26 +120,32 @@ bool Trie::Delete(std::string word) return false; } /****************************************************************************/ +// function for check if a string is already pushed into the tree. bool Trie::Search(std::string word) { TrieNode* node = FindLastChar(word.data()); - + // if FindLastChar return nullptr the word isnt in the trie, + // if the word is found but it just a prefix of another word, return false if(node == nullptr || node->end_of_str == false){ return false; } return true; } /****************************************************************************/ +// function for check if sum prefix is appear in the tree. bool Trie::startWith(std::string prefix) { TrieNode* node = FindLastChar(prefix.data()); - + // if FindLastChar return nullptr the word isnt in the trie, if(node == nullptr){ return false; } return true; } /****************************************************************************/ +// Recursive function for delete a word and the whole node if the word or part +// of her suffix stand alone. if the word is prefix of another word, no nodes +// will be removed Trie::RecDeleteStatus Trie::RecDelete(TrieNode* curr_node, const char* string_ptr) { if(curr_node == nullptr) @@ -141,6 +188,7 @@ Trie::RecDeleteStatus Trie::RecDelete(TrieNode* curr_node, const char* string_pt return COMPLITE; } /****************************************************************************/ +// function to check if node does not have childrens bool Trie::IsLeaf(TrieNode* curr_node) { for(auto it : curr_node->vec) @@ -153,6 +201,8 @@ bool Trie::IsLeaf(TrieNode* curr_node) return true; } /****************************************************************************/ +// function for create and push new nodes ,from the input node(node_runner) +// according to the string(string_ptr) that must have a null termination sign. TrieNode* Trie::CreatNodes(TrieNode* node_runner, const char* string_ptr) { while(*string_ptr) @@ -167,6 +217,8 @@ TrieNode* Trie::CreatNodes(TrieNode* node_runner, const char* string_ptr) return node_runner; } /****************************************************************************/ +// function for search and return the node of the last character in a string +// return nullptr if the word is not found. TrieNode* Trie::FindLastChar(const char* string_ptr) { TrieNode* node_runner = m_root; @@ -185,6 +237,7 @@ TrieNode* Trie::FindLastChar(const char* string_ptr) return node_runner; } /****************************************************************************/ +// destroy all nodes inside the trie except the root void Trie::Destroy(TrieNode* node) { if(node == nullptr) From 7afa34bd26db98720b6162d8f1cac5240e56ec7d Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 5 Jul 2023 16:37:44 +0530 Subject: [PATCH 1550/1894] Create trie.go --- Trees/trie.go | 117 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Trees/trie.go diff --git a/Trees/trie.go b/Trees/trie.go new file mode 100644 index 00000000..8f98cd9f --- /dev/null +++ b/Trees/trie.go @@ -0,0 +1,117 @@ +/* +Approach: +In this implementation, we define two struct types: `TrieNode` and `Trie`. `TrieNode` represents a single node in the Trie. It has two fields: `children` (a map of rune to `TrieNode`) to store the child nodes and `isWord` (a boolean) to indicate the end of a word. + +`Trie` represents the Trie data structure and has a single field `root` (a pointer to `TrieNode`), which is initialized with an empty `TrieNode` in the `NewTrie` function. + +The Trie supports three operations: +- `Insert` function is used to add a word to the Trie. It starts from the root node and traverses through each character of the word, creating new nodes as needed. +- `Search` function is used to check if a given word exists in the Trie. It follows a similar approach to the `Insert` function but returns `true` if the final node marks the end of a word. +- `StartsWith` function is used to check if there is any word in the Trie that starts with a given prefix. It works similar to the `Search` function but does not require the final node to mark the end of a word. + +Sample Input: +In the `main` function demonstrates the usage of the Trie data structure. We insert words "apple", "app", "application", "book", and "dog" into the Trie. Then, we search for words "app", "apple", and "banana". Finally, we check if there are any words in the Trie that start with prefixes "ap", "do", and "cat". + +Time complexity of the `Insert`, `Search`, and `StartsWith` operations: O(m), where m is the length of the word or prefix being processed. + +Space complexity: O(n), where n is the total number of characters in all the words inserted in the Trie. +*/ + +//Here's an implementation of the Trie data structure in Go: + +package main + +import "fmt" + +// TrieNode represents a single node in the Trie +type TrieNode struct { + children map[rune]*TrieNode + isWord bool +} + +// Trie represents the Trie data structure +type Trie struct { + root *TrieNode +} + +// NewTrie initializes a new Trie +func NewTrie() *Trie { + return &Trie{ + root: &TrieNode{ + children: make(map[rune]*TrieNode), + isWord: false, + }, + } +} + +// Insert adds a word to the Trie +func (t *Trie) Insert(word string) { + node := t.root + + // Traverse through each character of the word + for _, ch := range word { + if node.children[ch] == nil { + node.children[ch] = &TrieNode{ + children: make(map[rune]*TrieNode), + isWord: false, + } + } + node = node.children[ch] + } + + // Mark the end of the word + node.isWord = true +} + +// Search returns true if the word exists in the Trie, otherwise false +func (t *Trie) Search(word string) bool { + node := t.root + + // Traverse through each character of the word + for _, ch := range word { + if node.children[ch] == nil { + return false + } + node = node.children[ch] + } + + // Check if the node marks the end of a word + return node.isWord +} + +// StartsWith returns true if there is any word in the Trie that starts with the given prefix, otherwise false +func (t *Trie) StartsWith(prefix string) bool { + node := t.root + + // Traverse through each character of the prefix + for _, ch := range prefix { + if node.children[ch] == nil { + return false + } + node = node.children[ch] + } + + return true +} + +func main() { + trie := NewTrie() + + // Inserting words into the Trie + trie.Insert("apple") + trie.Insert("app") + trie.Insert("application") + trie.Insert("book") + trie.Insert("dog") + + // Searching words in the Trie + fmt.Println(trie.Search("app")) // Output: true + fmt.Println(trie.Search("apple")) // Output: true + fmt.Println(trie.Search("banana")) // Output: false + + // Checking prefixes in the Trie + fmt.Println(trie.StartsWith("ap")) // Output: true + fmt.Println(trie.StartsWith("do")) // Output: true + fmt.Println(trie.StartsWith("cat")) // Output: false +} + From 30fc0d0dc33373afc5ae6eb0eccad9e14eb71134 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Jul 2023 22:44:06 +0530 Subject: [PATCH 1551/1894] add yca in js --- Graphs/youngest_common_ancestor.js | 141 +++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 Graphs/youngest_common_ancestor.js diff --git a/Graphs/youngest_common_ancestor.js b/Graphs/youngest_common_ancestor.js new file mode 100644 index 00000000..9ce55c83 --- /dev/null +++ b/Graphs/youngest_common_ancestor.js @@ -0,0 +1,141 @@ +/* + + Write a function that returns the youngest common ancestor to the two descendants. + + Sample Input: + Top ancestor: node A + descendantOne: node e + descandantTwo: node I + + Output: node B + A + / \ + B C + / \ / \ + D E F G + / \ +H I + Explanation: + + This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. + + - `type AncestralTree struct` defines the structure of a node in the ancestral tree, which contains a name and a + reference to its ancestor node. + + - `func GetYoungestCommonAncestor` is the main function that takes three parameters: `topAncestor` (the topmost ancestor + in the tree), `descendantOne` (the first descendant), and `descendantTwo` (the second descendant). It calculates the depths of the two descendants from the top ancestor and then calls the `backTrackAncestralTree` function with the appropriate parameters. + + - `func getDescendantDepth` calculates the depth of a descendant node from the top ancestor. It iteratively increments the + depth and traverses through the ancestors until reaching the top ancestor. + + - `func backTrackAncestralTree` is a helper function that backtracks the ancestral tree starting from the lowest descendant + until the depths of both descendants are equal. It first adjusts the position of the lowest descendant based on the depth difference between the two descendants. Then, it moves both descendants up the tree in tandem until they reach the same ancestor node, which is the youngest common ancestor. + + The code assumes that the `topAncestor` provided is a valid ancestor of both `descendantOne` and `descendantTwo`. + The `GetYoungestCommonAncestor` function returns the youngest common ancestor found in the ancestral tree. + + To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. + You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common + ancestor of two descendants. + + O(d) time | O(1) space - where d is the depth (height) of the ancestral tree +*/ +class AncestralTree { + constructor(name) { + this.name = name; + this.ancestor = null; + } +} + +// Function to calculate the depth of a descendant from the top ancestor +function getDescendantDepth(descendant, topAncestor) { + let depth = 0; + while (descendant !== topAncestor) { + depth += 1; + descendant = descendant.ancestor; + } + return depth; +} + +// Function to backtrack and find the youngest common ancestor +function backTrackAncestralTree(lowestDescendant, higherDescendant, diff) { + while (diff > 0) { + lowestDescendant = lowestDescendant.ancestor; + diff -= 1; + } + while (lowestDescendant !== higherDescendant) { + lowestDescendant = lowestDescendant.ancestor; + higherDescendant = higherDescendant.ancestor; + } + return lowestDescendant; +} + +// Function to find the youngest common ancestor of two descendants +function getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) { + const depthOne = getDescendantDepth(descendantOne, topAncestor); + const depthTwo = getDescendantDepth(descendantTwo, topAncestor); + + if (depthOne > depthTwo) { + return backTrackAncestralTree( + descendantOne, + descendantTwo, + depthOne - depthTwo + ); + } + return backTrackAncestralTree( + descendantTwo, + descendantOne, + depthTwo - depthOne + ); +} + +// Create the ancestral tree +const topAncestor = new AncestralTree("A"); +const B = new AncestralTree("B"); +const C = new AncestralTree("C"); +const D = new AncestralTree("D"); +const E = new AncestralTree("E"); +const F = new AncestralTree("F"); +const G = new AncestralTree("G"); +const H = new AncestralTree("H"); +const I = new AncestralTree("I"); + +// Set up the ancestral relationships + +// A +// / \ +// B C +// / \ / \ +// D E F G +// / +// H +// / +// I + +topAncestor.ancestor = null; +B.ancestor = topAncestor; +C.ancestor = topAncestor; +D.ancestor = B; +E.ancestor = B; +F.ancestor = C; +G.ancestor = C; +H.ancestor = D; +I.ancestor = H; + +// Find the youngest common ancestor of two descendants +const descendantOne = F; +const descendantTwo = I; +const yca = getYoungestCommonAncestor( + topAncestor, + descendantOne, + descendantTwo +); + +console.log( + "The youngest common ancestor of", + descendantOne.name, + "and", + descendantTwo.name, + "is", + yca.name +); From d83d46206226ac480e8c08dfacb913b4d27cfbb4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 5 Jul 2023 22:47:17 +0530 Subject: [PATCH 1552/1894] add yca in java --- Graphs/youngest_common_ancestor.java | 129 +++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 Graphs/youngest_common_ancestor.java diff --git a/Graphs/youngest_common_ancestor.java b/Graphs/youngest_common_ancestor.java new file mode 100644 index 00000000..6326cb9c --- /dev/null +++ b/Graphs/youngest_common_ancestor.java @@ -0,0 +1,129 @@ +/* + + Write a function that returns the youngest common ancestor to the two descendants. + + Sample Input: + Top ancestor: node A + descendantOne: node e + descandantTwo: node I + + Output: node B + A + / \ + B C + / \ / \ + D E F G + / \ +H I + Explanation: + + This code snippet implements a solution for finding the youngest common ancestor of two descendants in an ancestral tree. + + - `type AncestralTree struct` defines the structure of a node in the ancestral tree, which contains a name and a + reference to its ancestor node. + + - `func GetYoungestCommonAncestor` is the main function that takes three parameters: `topAncestor` (the topmost ancestor + in the tree), `descendantOne` (the first descendant), and `descendantTwo` (the second descendant). It calculates the depths of the two descendants from the top ancestor and then calls the `backTrackAncestralTree` function with the appropriate parameters. + + - `func getDescendantDepth` calculates the depth of a descendant node from the top ancestor. It iteratively increments the + depth and traverses through the ancestors until reaching the top ancestor. + + - `func backTrackAncestralTree` is a helper function that backtracks the ancestral tree starting from the lowest descendant + until the depths of both descendants are equal. It first adjusts the position of the lowest descendant based on the depth difference between the two descendants. Then, it moves both descendants up the tree in tandem until they reach the same ancestor node, which is the youngest common ancestor. + + The code assumes that the `topAncestor` provided is a valid ancestor of both `descendantOne` and `descendantTwo`. + The `GetYoungestCommonAncestor` function returns the youngest common ancestor found in the ancestral tree. + + To use this code, you need to create instances of the `AncestralTree` struct representing the ancestral tree and its nodes. + You can then call the `GetYoungestCommonAncestor` function with the appropriate parameters to find the youngest common + ancestor of two descendants. + + O(d) time | O(1) space - where d is the depth (height) of the ancestral tree +*/ +class AncestralTree { + String name; + AncestralTree ancestor; + + public AncestralTree(String name) { + this.name = name; + this.ancestor = null; + } +} + +public class Main { + // Function to calculate the depth of a descendant from the top ancestor + public static int getDescendantDepth(AncestralTree descendant, AncestralTree topAncestor) { + int depth = 0; + while (descendant != topAncestor) { + depth++; + descendant = descendant.ancestor; + } + return depth; + } + + // Function to backtrack and find the youngest common ancestor + public static AncestralTree backTrackAncestralTree(AncestralTree lowestDescendant, AncestralTree higherDescendant, int diff) { + while (diff > 0) { + lowestDescendant = lowestDescendant.ancestor; + diff--; + } + while (lowestDescendant != higherDescendant) { + lowestDescendant = lowestDescendant.ancestor; + higherDescendant = higherDescendant.ancestor; + } + return lowestDescendant; + } + + // Function to find the youngest common ancestor of two descendants + public static AncestralTree getYoungestCommonAncestor(AncestralTree topAncestor, AncestralTree descendantOne, AncestralTree descendantTwo) { + int depthOne = getDescendantDepth(descendantOne, topAncestor); + int depthTwo = getDescendantDepth(descendantTwo, topAncestor); + + if (depthOne > depthTwo) { + return backTrackAncestralTree(descendantOne, descendantTwo, depthOne - depthTwo); + } + return backTrackAncestralTree(descendantTwo, descendantOne, depthTwo - depthOne); + } + + public static void main(String[] args) { + // Create the ancestral tree + AncestralTree topAncestor = new AncestralTree("A"); + AncestralTree B = new AncestralTree("B"); + AncestralTree C = new AncestralTree("C"); + AncestralTree D = new AncestralTree("D"); + AncestralTree E = new AncestralTree("E"); + AncestralTree F = new AncestralTree("F"); + AncestralTree G = new AncestralTree("G"); + AncestralTree H = new AncestralTree("H"); + AncestralTree I = new AncestralTree("I"); + + // Set up the ancestral relationships + + // A + // / \ + // B C + // / \ / \ + // D E F G + // / + // H + // / + // I + + topAncestor.ancestor = null; + B.ancestor = topAncestor; + C.ancestor = topAncestor; + D.ancestor = B; + E.ancestor = B; + F.ancestor = C; + G.ancestor = C; + H.ancestor = D; + I.ancestor = H; + + // Find the youngest common ancestor of two descendants + AncestralTree descendantOne = F; + AncestralTree descendantTwo = I; + AncestralTree yca = getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo); + + System.out.println("The youngest common ancestor of " + descendantOne.name + " and " + descendantTwo.name + " is " + yca.name); + } +} From 649858a5edb292dec3233b1e85ff60ef6faa50fb Mon Sep 17 00:00:00 2001 From: Manik Dingra Date: Wed, 5 Jul 2023 23:46:16 +0530 Subject: [PATCH 1553/1894] Priority queues question added --- PriorityQueues/Code/BuyTheTicket.cpp | 114 ++++++++++++++ PriorityQueues/Code/CheckMaxHeap.cpp | 60 ++++++++ PriorityQueues/Code/InBuilt_PriorityQueue.cpp | 22 +++ PriorityQueues/Code/In_Place_HeapSort.cpp | 109 +++++++++++++ .../Code/Inbuilt_MinPriorityQueue.cpp | 22 +++ PriorityQueues/Code/KLargestElement.cpp | 75 +++++++++ PriorityQueues/Code/KSmallestElement.cpp | 84 ++++++++++ PriorityQueues/Code/KSortedArray.cpp | 39 +++++ PriorityQueues/Code/KthLargestElement.cpp | 81 ++++++++++ PriorityQueues/Code/Max_PriorityQueue.cpp | 144 ++++++++++++++++++ PriorityQueues/Code/MergeKSortedArrays.cpp | 101 ++++++++++++ PriorityQueues/Code/Min_PriorityQueues.cpp | 107 +++++++++++++ PriorityQueues/Code/RunningMedian.cpp | 123 +++++++++++++++ 13 files changed, 1081 insertions(+) create mode 100644 PriorityQueues/Code/BuyTheTicket.cpp create mode 100644 PriorityQueues/Code/CheckMaxHeap.cpp create mode 100644 PriorityQueues/Code/InBuilt_PriorityQueue.cpp create mode 100644 PriorityQueues/Code/In_Place_HeapSort.cpp create mode 100644 PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp create mode 100644 PriorityQueues/Code/KLargestElement.cpp create mode 100644 PriorityQueues/Code/KSmallestElement.cpp create mode 100644 PriorityQueues/Code/KSortedArray.cpp create mode 100644 PriorityQueues/Code/KthLargestElement.cpp create mode 100644 PriorityQueues/Code/Max_PriorityQueue.cpp create mode 100644 PriorityQueues/Code/MergeKSortedArrays.cpp create mode 100644 PriorityQueues/Code/Min_PriorityQueues.cpp create mode 100644 PriorityQueues/Code/RunningMedian.cpp diff --git a/PriorityQueues/Code/BuyTheTicket.cpp b/PriorityQueues/Code/BuyTheTicket.cpp new file mode 100644 index 00000000..f254f246 --- /dev/null +++ b/PriorityQueues/Code/BuyTheTicket.cpp @@ -0,0 +1,114 @@ +/* +You want to buy a ticket for a well-known concert which is happening in your city. But the number of tickets available is limited. Hence the sponsors of the concert decided to sell tickets to customers based on some priority. +A queue is maintained for buying the tickets and every person is attached with a priority (an integer, 1 being the lowest priority). +The tickets are sold in the following manner - + +1. The first person (pi) in the queue requests for the ticket. +2. If there is another person present in the queue who has higher priority than pi, then ask pi to move at end of the queue without giving him the ticket. +3. Otherwise, give him the ticket (and don't make him stand in queue again). + +Giving a ticket to a person takes exactly 1 minute and it takes no time for removing and adding a person to the queue. And you can assume that no new person joins the queue. +Given a list of priorities of N persons standing in the queue and the index of your priority (indexing starts from 0). Find and return the time it will take until you get the ticket. +Input Format: + +The first line of input contains an integer, that denotes the value of total number of people standing in queue or the size of the array of priorities. Let us denote it with the symbol N. +The following line contains N space separated integers, that denote the value of the elements of the array of priorities. +The following contains an integer, that denotes the value of index of your priority. Let us denote it with symbol k. + +Output Format : + +The first and only line of output contains the time required for you to get the ticket. + +Constraints: + +Time Limit: 1 sec + +Sample Input 1 : + +3 +3 9 4 +2 + +Sample Output 1 : + +2 + +Sample Output 1 Explanation : + +Person with priority 3 comes out. But there is a person with higher priority than him. So he goes and then stands in the queue at the end. Queue's status : {9, 4, 3}. Time : 0 secs. +Next, the person with priority 9 comes out. And there is no person with higher priority than him. So he'll get the ticket. Queue's status : {4, 3}. Time : 1 secs. +Next, the person with priority 4 comes out (which is you). And there is no person with higher priority than you. So you'll get the ticket. Time : 2 secs. + +Sample Input 2 : + +5 +2 3 2 2 4 +3 + +Sample Output 2 : + +4 + +*/ +#include +#include +#include +using namespace std; + +int buyTicket(int *arr, int n, int k) +{ + priority_queue pq; + for (int i = 0; i < n; i++) + { + pq.push(arr[i]); + } + queue indices; + for (int i = 0; i < n; i++) + { + indices.push(i); + } + int time = 0; + while (!indices.empty()) + { + if (arr[indices.front()] == pq.top() && indices.front() == k) + { + time++; + pq.pop(); + indices.pop(); + break; + } + if (arr[indices.front()] == pq.top()) + { + time++; + pq.pop(); + indices.pop(); + } + else + { + int temp = indices.front(); + indices.pop(); + indices.push(temp); + } + } + return time; +} + +int main() +{ + int n; + cin >> n; + + int *arr = new int[n]; + + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + int k; + cin >> k; + + cout << buyTicket(arr, n, k); + + delete[] arr; +} \ No newline at end of file diff --git a/PriorityQueues/Code/CheckMaxHeap.cpp b/PriorityQueues/Code/CheckMaxHeap.cpp new file mode 100644 index 00000000..a6ec0854 --- /dev/null +++ b/PriorityQueues/Code/CheckMaxHeap.cpp @@ -0,0 +1,60 @@ +/* +Given an array of integers, check whether it represents max-heap or not. Return true if the given array represents max-heap, else return false. +Input Format: + +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N. +The following line contains N space separated integers, that denote the value of the elements of the array. + +Output Format : + +The first and only line of output contains true if it represents max-heap and false if it is not a max-heap. + +Constraints: + +1 <= N <= 10^5 +1 <= Ai <= 10^5 +Time Limit: 1 sec + +Sample Input 1: + +8 +42 20 18 6 14 11 9 4 + +Sample Output 1: + +true + +*/ +#include +using namespace std; + +bool isMaxHeap(int arr[], int n) +{ + int childIndex = n - 1; + while (childIndex >= 0) + { + int parentIndex = (childIndex - 1) / 2; + if (arr[parentIndex] < arr[childIndex]) + { + return false; + } + childIndex--; + } + return true; +} + +int main() +{ + int n; + cin >> n; + int *arr = new int[n]; + + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + cout << (isMaxHeap(arr, n) ? "true\n" : "false\n"); + + delete[] arr; +} \ No newline at end of file diff --git a/PriorityQueues/Code/InBuilt_PriorityQueue.cpp b/PriorityQueues/Code/InBuilt_PriorityQueue.cpp new file mode 100644 index 00000000..c212b08b --- /dev/null +++ b/PriorityQueues/Code/InBuilt_PriorityQueue.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +int main() +{ + priority_queue pq; + pq.push(10); + pq.push(20); + pq.push(30); + cout << pq.empty() << endl; + cout << pq.size() << endl; + cout << pq.top() << endl; + while (!pq.empty()) + { + cout << pq.top() << endl; + pq.pop(); + } + cout << pq.size() << endl; + cout << pq.empty() << endl; + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/In_Place_HeapSort.cpp b/PriorityQueues/Code/In_Place_HeapSort.cpp new file mode 100644 index 00000000..5083c94d --- /dev/null +++ b/PriorityQueues/Code/In_Place_HeapSort.cpp @@ -0,0 +1,109 @@ +/* +Given an integer array of size N. Sort this array (in decreasing order) using heap sort. +Note: Space complexity should be O(1). +Input Format: + +The first line of input contains an integer, that denotes the value of the size of the array or N. +The following line contains N space separated integers, that denote the value of the elements of the array. + +Output Format : + +The first and only line of output contains array elements after sorting. The elements of the array in the output are separated by single space. + +Constraints : + +1 <= n <= 10^6 +Time Limit: 1 sec + +Sample Input 1: + +6 +2 6 8 5 4 3 + +Sample Output 1: + +8 6 5 4 3 2 +*/ +#include + +using namespace std; + +void heapSort(int arr[], int n) +{ + for (int i = 1; i < n; i++) + { + int childIndex = i; + while (childIndex > 0) + { + int parentIndex = (childIndex - 1) / 2; + if (arr[childIndex] < arr[parentIndex]) + { + int temp = arr[childIndex]; + arr[childIndex] = arr[parentIndex]; + arr[parentIndex] = temp; + } + else + { + break; + } + childIndex = parentIndex; + } + } + int j = n; + while (j > 1) + { + int temp = arr[0]; + arr[0] = arr[j - 1]; + arr[j - 1] = temp; + j--; + int parentIndex = 0; + int rightChildIndex = 2 * parentIndex + 2; + int leftChildIndex = 2 * parentIndex + 1; + while (leftChildIndex < j) + { + int minIndex = parentIndex; + if (arr[leftChildIndex] < arr[minIndex]) + { + minIndex = leftChildIndex; + } + if (rightChildIndex < j && arr[rightChildIndex] < arr[minIndex]) + { + minIndex = rightChildIndex; + } + + int temp = arr[minIndex]; + arr[minIndex] = arr[parentIndex]; + arr[parentIndex] = temp; + + if (parentIndex == minIndex) + { + break; + } + parentIndex = minIndex; + rightChildIndex = 2 * parentIndex + 2; + leftChildIndex = 2 * parentIndex + 1; + } + } +} + +int main() +{ + int size; + cin >> size; + + int *input = new int[size]; + + for (int i = 0; i < size; i++) + { + cin >> input[i]; + } + + heapSort(input, size); + + for (int i = 0; i < size; i++) + { + cout << input[i] << " "; + } + + delete[] input; +} \ No newline at end of file diff --git a/PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp b/PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp new file mode 100644 index 00000000..de686393 --- /dev/null +++ b/PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +int main() +{ + priority_queue, greater> pq; + pq.push(10); + pq.push(20); + pq.push(30); + cout << pq.empty() << endl; + cout << pq.size() << endl; + cout << pq.top() << endl; + while (!pq.empty()) + { + cout << pq.top() << endl; + pq.pop(); + } + cout << pq.size() << endl; + cout << pq.empty() << endl; + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/KLargestElement.cpp b/PriorityQueues/Code/KLargestElement.cpp new file mode 100644 index 00000000..e7f3015f --- /dev/null +++ b/PriorityQueues/Code/KLargestElement.cpp @@ -0,0 +1,75 @@ +/* +You are given with an integer k and an array of integers that contain numbers in random order. Write a program to find k largest numbers from given array. You need to save them in an array and return it. +Time complexity should be O(nlogk) and space complexity should be not more than O(k). +Order of elements in the output is not important. +Input Format : + +Line 1 : Size of array (n) +Line 2 : Array elements (separated by space) +Line 3 : Integer k + +Output Format : + +k largest elements + +Sample Input : + +13 +2 12 9 16 10 5 3 20 25 11 1 8 6 +4 + +Sample Output : + +12 +16 +20 +25 + +*/ +#include +#include +using namespace std; + +vector kLargest(int input[], int n, int k) +{ + priority_queue, greater> pq; + for (int i = 0; i < k; i++) + { + pq.push(input[i]); + } + for (int i = k; i < n; i++) + { + if (input[i] > pq.top()) + { + pq.push(input[i]); + pq.pop(); + } + } + vector ans; + while (!pq.empty()) + { + ans.push_back(pq.top()); + pq.pop(); + } + return ans; +} + +int main() +{ + + int size; + cin >> size; + int *input = new int[1 + size]; + + for (int i = 0; i < size; i++) + cin >> input[i]; + + int k; + cin >> k; + + vector output = kLargest(input, size, k); + for (int i = 0; i < output.size(); i++) + cout << output[i] << endl; + + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/KSmallestElement.cpp b/PriorityQueues/Code/KSmallestElement.cpp new file mode 100644 index 00000000..725de8f5 --- /dev/null +++ b/PriorityQueues/Code/KSmallestElement.cpp @@ -0,0 +1,84 @@ +/* +You are given with an integer k and an array of integers that contain numbers in random order. Write a program to find k smallest numbers from given array. You need to save them in an array and return it. +Time complexity should be O(n * logk) and space complexity should not be more than O(k). +Note: Order of elements in the output is not important. +Input Format : + +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N. +The following line contains N space separated integers, that denote the value of the elements of the array. +The following line contains an integer, that denotes the value of k. + +Output Format : + +The first and only line of output print k smallest elements. The elements in the output are separated by a single space. + +Constraints: + +Time Limit: 1 sec + +Sample Input 1 : + +13 +2 12 9 16 10 5 3 20 25 11 1 8 6 +4 + +Sample Output 1 : + +1 2 3 5 + +*/ +#include +#include +#include +#include +using namespace std; + +vector kSmallest(int arr[], int n, int k) +{ + priority_queue pq; + for (int i = 0; i < k; i++) + { + pq.push(arr[i]); + } + for (int i = k; i < n; i++) + { + if (arr[i] < pq.top()) + { + pq.push(arr[i]); + pq.pop(); + } + } + vector vec; + while (!pq.empty()) + { + vec.push_back(pq.top()); + pq.pop(); + } + return vec; +} + +int main() +{ + int size; + cin >> size; + + int *input = new int[size]; + + for (int i = 0; i < size; i++) + { + cin >> input[i]; + } + + int k; + cin >> k; + + vector output = kSmallest(input, size, k); + sort(output.begin(), output.end()); + + for (int i = 0; i < output.size(); i++) + { + cout << output[i] << " "; + } + + delete[] input; +} \ No newline at end of file diff --git a/PriorityQueues/Code/KSortedArray.cpp b/PriorityQueues/Code/KSortedArray.cpp new file mode 100644 index 00000000..49b98b71 --- /dev/null +++ b/PriorityQueues/Code/KSortedArray.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; + +void kSortedArray(int arr[], int n, int k) +{ + priority_queue pq; + for (int i = 0; i < k; i++) + { + pq.push(arr[i]); + } + int j = 0; + for (int i = k; i < n; i++) + { + arr[j] = pq.top(); + pq.pop(); + pq.push(arr[i]); + j++; + } + while (!pq.empty()) + { + arr[j] = pq.top(); + pq.pop(); + j++; + } +} + +int main() +{ + int arr[] = {12, 15, 6, 7, 9}; + int k = 3; + kSortedArray(arr, 5, k); + for (int i = 0; i < 5; i++) + { + cout << arr[i] << " "; + } + cout << endl; + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/KthLargestElement.cpp b/PriorityQueues/Code/KthLargestElement.cpp new file mode 100644 index 00000000..b924699c --- /dev/null +++ b/PriorityQueues/Code/KthLargestElement.cpp @@ -0,0 +1,81 @@ +/* +Given an array A of random integers and an integer k, find and return the kth largest element in the array. +Note: Try to do this question in less than O(N * logN) time. +Input Format : + +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N. +The following line contains N space separated integers, that denote the value of the elements of the array. +The following contains an integer, that denotes the value of k. + +Output Format : + +The first and only line of output contains the kth largest element + +Constraints : + +1 <= N, Ai, k <= 10^5 +Time Limit: 1 sec + +Sample Input 1 : + +6 +9 4 8 7 11 3 +2 + +Sample Output 1 : + +9 + +Sample Input 2 : + +8 +2 6 10 11 13 4 1 20 +4 + +Sample Output 2 : + +10 + +*/ +#include +#include +#include +using namespace std; + +int kthLargest(int *arr, int n, int k) +{ + priority_queue, greater> pq; + for (int i = 0; i < k; i++) + { + pq.push(arr[i]); + } + for (int i = k; i < n; i++) + { + if (arr[i] > pq.top()) + { + pq.push(arr[i]); + pq.pop(); + } + } + return pq.top(); +} + +int main() +{ + int n; + cin >> n; + + int *arr = new int[n]; + + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + int k; + cin >> k; + + cout << kthLargest(arr, n, k); + + delete[] arr; +} \ No newline at end of file diff --git a/PriorityQueues/Code/Max_PriorityQueue.cpp b/PriorityQueues/Code/Max_PriorityQueue.cpp new file mode 100644 index 00000000..a776ab05 --- /dev/null +++ b/PriorityQueues/Code/Max_PriorityQueue.cpp @@ -0,0 +1,144 @@ +/* +Implement the class for Max Priority Queue which includes following functions - +1. getSize - +Return the size of priority queue i.e. number of elements present in the priority queue. +2. isEmpty - +Check if priority queue is empty or not. Return true or false accordingly. +3. insert - +Given an element, insert that element in the priority queue at the correct position. +4. getMax - +Return the maximum element present in the priority queue without deleting. Return -Infinity if priority queue is empty. +5. removeMax - +Delete and return the maximum element present in the priority queue. Return -Infinity if priority queue is empty. +Note : main function is given for your reference which we are using internally to test the class. +*/ +#include +#include +#include +using namespace std; + +class PriorityQueue +{ + vector pq; + +public: + PriorityQueue() + { + // Implement the constructor here + } + + /**************** Implement all the public functions here ***************/ + + void insert(int element) + { + pq.push_back(element); + int childIndex = pq.size() - 1; + + while (childIndex > 0) + { + int parentIndex = (childIndex - 1) / 2; + if (pq[parentIndex] < pq[childIndex]) + { + int temp = pq[childIndex]; + pq[childIndex] = pq[parentIndex]; + pq[parentIndex] = temp; + } + else + { + break; + } + childIndex = parentIndex; + } + } + + int getMax() + { + if (isEmpty()) + { + return INT_MIN; + } + return pq[0]; + } + + int removeMax() + { + if (pq.size() == 0) + { + return INT_MIN; + } + int ans = pq[0]; + pq[0] = pq[pq.size() - 1]; + pq.pop_back(); + int parentIndex = 0; + int leftChildIndex = 2 * parentIndex + 1; + int rightChildIndex = 2 * parentIndex + 2; + while (leftChildIndex < pq.size()) + { + int maxIndex = parentIndex; + if (pq[leftChildIndex] > pq[parentIndex]) + { + maxIndex = leftChildIndex; + } + if (rightChildIndex < pq.size() && pq[rightChildIndex] > pq[maxIndex]) + { + maxIndex = rightChildIndex; + } + int temp = pq[parentIndex]; + pq[parentIndex] = pq[maxIndex]; + pq[maxIndex] = temp; + + if (parentIndex == maxIndex) + { + break; + } + parentIndex = maxIndex; + leftChildIndex = 2 * parentIndex + 1; + rightChildIndex = 2 * parentIndex + 2; + } + return ans; + } + + int getSize() + { + return pq.size(); + } + + bool isEmpty() + { + return pq.size() == 0; + } +}; + +int main() +{ + PriorityQueue pq; + int choice; + cin >> choice; + + while (choice != -1) + { + switch (choice) + { + case 1: // insert + int element; + cin >> element; + pq.insert(element); + break; + case 2: // getMax + cout << pq.getMax() << "\n"; + break; + case 3: // removeMax + cout << pq.removeMax() << "\n"; + break; + case 4: // size + cout << pq.getSize() << "\n"; + break; + case 5: // isEmpty + cout << (pq.isEmpty() ? "true\n" : "false\n"); + default: + return 0; + } + + cin >> choice; + } +} \ No newline at end of file diff --git a/PriorityQueues/Code/MergeKSortedArrays.cpp b/PriorityQueues/Code/MergeKSortedArrays.cpp new file mode 100644 index 00000000..312300ec --- /dev/null +++ b/PriorityQueues/Code/MergeKSortedArrays.cpp @@ -0,0 +1,101 @@ +/* +Given k different arrays, which are sorted individually (in ascending order). You need to merge all the given arrays such that output array should be sorted (in ascending order). +Hint : Use Heaps. +Input Format: + +The first line of input contains an integer, that denotes value of k. +The following lines of input represent k sorted arrays. Each sorted array uses two lines of input. The first line contains an integer, that denotes the size of the array. The following line contains elements of the array. + +Output Format: + +The first and only line of output contains space separated elements of the merged and sorted array, as described in the task. + +Constraints: + +0 <= k <= 1000 +0 <= n1, n2 <= 10000 +Time Limit: 1 second + +Sample Input 1: + +4 +3 +1 5 9 +2 +45 90 +5 +2 6 78 100 234 +1 +0 + +Sample Output 1: + +0 1 2 5 6 9 45 78 90 100 234 + +*/ +#include +#include +#include +using namespace std; + +vector mergeKSortedArrays(vector *> input) +{ + priority_queue>, vector>>, greater>>> pq; + for (int i = 0; i < input.size(); i++) + { + pair> p; + p.first = input[i]->at(0); + p.second.first = i; + p.second.second = 0; + pq.push(p); + } + vector ans; + while (!pq.empty()) + { + pair> p = pq.top(); + pq.pop(); + ans.push_back(p.first); + int arrNo = p.second.first; + int index = p.second.second + 1; + if (index < input[arrNo]->size()) + { + p.first = input[arrNo]->at(index); + p.second.second = index; + pq.push(p); + } + } + return ans; +} + +int main() +{ + int k; + cin >> k; + + vector *> input; + + for (int j = 1; j <= k; j++) + { + int size; + cin >> size; + vector *current = new vector; + + for (int i = 0; i < size; i++) + { + int a; + cin >> a; + current->push_back(a); + } + + input.push_back(current); + } + + vector output = mergeKSortedArrays(input); + + for (int i = 0; i < output.size(); i++) + { + cout << output[i] << " "; + } + + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/Min_PriorityQueues.cpp b/PriorityQueues/Code/Min_PriorityQueues.cpp new file mode 100644 index 00000000..57781231 --- /dev/null +++ b/PriorityQueues/Code/Min_PriorityQueues.cpp @@ -0,0 +1,107 @@ +#include +#include +#include + +using namespace std; + +class priorityQueue +{ + vector pq; + +public: + priorityQueue() + { + } + bool isEmpty() + { + return pq.size() == 0; + } + int getSize() + { + return pq.size(); + } + int getMin() + { + if (isEmpty()) + { + return -1; + } + return pq[0]; + } + + void insert(int data) + { + pq.push_back(data); + int childIndex = pq.size() - 1; + while (childIndex > 0) + { + int parentIndex = (childIndex - 1) / 2; + if (pq[childIndex] < pq[parentIndex]) + { + int temp = pq[childIndex]; + pq[childIndex] = pq[parentIndex]; + pq[parentIndex] = temp; + } + else + { + break; + } + childIndex = parentIndex; + } + } + + int removeMin() + { + if (pq.size() == 0) + { + return -1; + } + int ans = getMin(); + int temp = pq[0]; + pq[0] = pq[pq.size() - 1]; + pq[pq.size() - 1] = temp; + pq.pop_back(); + int parentIndex = 0; + int childIndex1 = 2 * parentIndex + 1; + int childIndex2 = 2 * parentIndex + 2; + while (childIndex1 < pq.size()) + { + int minIndex = parentIndex; + if (pq[minIndex] > pq[childIndex1]) + { + minIndex = childIndex1; + } + if (childIndex2 < pq.size() && pq[minIndex] > pq[childIndex2]) + { + minIndex = childIndex2; + } + swap(pq[parentIndex], pq[minIndex]); + if (minIndex == parentIndex) + { + break; + } + parentIndex = minIndex; + childIndex1 = 2 * parentIndex + 1; + childIndex2 = 2 * parentIndex + 2; + } + return ans; + } +}; + +int main() +{ + priorityQueue p; + p.insert(100); + p.insert(10); + p.insert(15); + p.insert(4); + p.insert(17); + p.insert(21); + p.insert(67); + + cout << p.getSize() << endl; + cout << p.getMin() << endl; + while (!p.isEmpty()) + cout << p.removeMin() << " "; + return 0; +} \ No newline at end of file diff --git a/PriorityQueues/Code/RunningMedian.cpp b/PriorityQueues/Code/RunningMedian.cpp new file mode 100644 index 00000000..4942d9f6 --- /dev/null +++ b/PriorityQueues/Code/RunningMedian.cpp @@ -0,0 +1,123 @@ +/* +You are given a stream of 'N' integers. For every 'i-th' integer added to the running list of integers, print the resulting median. +Print only the integer part of the median. +Input Format : + +The first line of input contains an integer 'N', denoting the number of integers in the stream. + +The second line of input contains 'N' integers separated by a single space. + +Output Format : + +Print the running median for every integer added to the running list in one line (space-separated). + +Input Constraints + +0 <= N <= 10 ^ 5 +1 <= ARR[i] <= 10 ^ 5 + +Time Limit: 1 sec + +Sample Input 1 : + +6 +6 2 1 3 7 5 + +Sample Output 1 : + +6 4 2 2 3 4 + +Explanation of Sample Output 1 : + +S = {6}, median = 6 +S = {6, 2} -> {2, 6}, median = 4 +S = {6, 2, 1} -> {1, 2, 6}, median = 2 +S = {6, 2, 1, 3} -> {1, 2, 3, 6}, median = 2 +S = {6, 2, 1, 3, 7} -> {1, 2, 3, 6, 7}, median = 3 +S = {6, 2, 1, 3, 7, 5} -> {1, 2, 3, 5, 6, 7}, median = 4 + +Sample Input 2 : + +5 +5 4 3 2 1 + +Sample Output 2 : + +5 4 4 3 3 + +*/ + +#include +#include +using namespace std; + +void findMedian(int *arr, int n) +{ + priority_queue, greater> min; + priority_queue max; + for (int i = 0; i < n; i++) + { + if (i == 0) + { + max.push(arr[i]); + } + else + { + if (max.top() > arr[i]) + { + max.push(arr[i]); + } + else + { + min.push(arr[i]); + } + } + + if (int(min.size() - max.size()) > 1) + { + int temp = min.top(); + min.pop(); + max.push(temp); + } + else if (int(max.size() - min.size()) > 1) + { + int temp = max.top(); + max.pop(); + min.push(temp); + } + int c = max.size() + min.size(); + if (c % 2 == 0) + { + cout << (min.top() + max.top()) / 2 << " "; + } + else + { + if (min.size() > max.size()) + { + cout << min.top() << " "; + } + else + { + cout << max.top() << " "; + } + } + } + cout << endl; +} + +int main() +{ + int n; + cin >> n; + + int *arr = new int[n]; + + for (int i = 0; i < n; ++i) + { + cin >> arr[i]; + } + + findMedian(arr, n); + + delete[] arr; +} From f0765c4b89c01de2f301f319da79de254afab6be Mon Sep 17 00:00:00 2001 From: Anand Date: Thu, 6 Jul 2023 14:37:57 +0530 Subject: [PATCH 1554/1894] Modify TimeComplexity Cyclic_Sort Corrected TimeComplexity of java Cyclic_Sort O(n) instead of O(n^2) Algorithm supports for 1-n elements. --- sorting/Cyclic_Sort.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sorting/Cyclic_Sort.java b/sorting/Cyclic_Sort.java index c42f2e1b..53cd5dd7 100644 --- a/sorting/Cyclic_Sort.java +++ b/sorting/Cyclic_Sort.java @@ -3,9 +3,11 @@ The basic idea behind cycle sort is to divide the input array into cycles, where each cycle consists of elements that belong to the same position in the sorted output array. The algorithm then performs a series of swaps to place each element in its correct position within its cycle, until all cycles are complete and the array is sorted. It is usually used where elements are in the range of (1,n) +Note : This Algorithm solution is for elements from 1-N , where N is the number of elements in the array. Time Complexity Analysis: - Worst Case: O(n2) - Best Case: O(n2) + Worst Case: O(n) + Average Case: O(n) + Best Case: O(n) Auxiliary Space: O(1) */ From 7e83b2692c24f9709a09647100d5dbe4817a85e2 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Thu, 6 Jul 2023 18:21:43 +0530 Subject: [PATCH 1555/1894] Create NumericalPattern.java --- Patterns/NumericalPattern.java | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Patterns/NumericalPattern.java diff --git a/Patterns/NumericalPattern.java b/Patterns/NumericalPattern.java new file mode 100644 index 00000000..bcde260c --- /dev/null +++ b/Patterns/NumericalPattern.java @@ -0,0 +1,49 @@ +/* +Problem: +This program prints a pattern of numbers in an organized way. +The numbers start from 1 and increase in a triangular pattern. +Each row in the pattern contains the numbers from 1 to the row number. +The row numbers increase from 1 to the given input number. + +Approach: +- Use nested loops to iterate through each row and each number within the row. +- The outer loop controls the row number and runs from 1 to the input number. +- The inner loop prints the numbers for each row and runs from 1 to the row number. +- Print each number followed by a space. +- After each row is printed, insert a new line. + +Time Complexity: O(n^2), where n is the given input number. This is because we have nested loops that iterate n times. +Space Complexity: O(1) as no extra space is required other than the given input. + +Sample Input 1: +5 +Sample Output 1: +1 +1 2 +1 2 3 +1 2 3 4 +1 2 3 4 5 + +Sample Input 2: +3 +Sample Output 2: +1 +1 2 +1 2 3 +*/ + +public class NumericalPattern { + public static void printPattern(int n) { + for (int i = 1; i <= n; i++) { // iterate through each row + for (int j = 1; j <= i; j++) { // iterate through each number within the row + System.out.print(j + " "); // print the number followed by a space + } + System.out.println(); // insert a new line after each row + } + } + + public static void main(String[] args) { + int n = 5; // sample input + printPattern(n); + } +} From 3c7029d715cc93ae0ab4f0a2ec8ade0d427f53f0 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Thu, 6 Jul 2023 18:25:28 +0530 Subject: [PATCH 1556/1894] Create triangular_pattern.py --- Patterns/triangular_pattern.py | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Patterns/triangular_pattern.py diff --git a/Patterns/triangular_pattern.py b/Patterns/triangular_pattern.py new file mode 100644 index 00000000..85b788e1 --- /dev/null +++ b/Patterns/triangular_pattern.py @@ -0,0 +1,42 @@ +''' +Explanation: +1. The code defines a function `print_triangular_pattern()` that takes a parameter `n`. This parameter determines the number of rows in the triangular pattern. +2. Inside the function, `num` is initialized to 1, which is the starting number of the pattern. +3. The code then uses nested loops. The outer loop runs from 1 to `n`, which represents the number of rows. +4. The inner loop runs from 1 to the current row number (i). It prints the numbers in each row in increasing order. +5. After printing all the numbers in a row, the code moves to the next line using `print()` to create a new row. +6. Ultimately, the pattern is printed as a set of rows, forming a triangular shape. + +Time Complexity: The time complexity of this code is O(n^2), where n is the number of rows. This is because we have two nested loops, one iterating n times and the other iterating up to the current row number. + +Space Complexity: The space complexity of this code is O(1), as we are not using any additional data structures that depend on the input size. + +Sample Input: +n = 5 + +Sample Output: +1 +2 3 +4 5 6 +7 8 9 10 +11 12 13 14 15 + +''' + +#code in Python that prints a number pattern in a triangular pattern starting from 1: + +def print_triangular_pattern(n): + num = 1 # Initialize the starting number + + for i in range(1, n + 1): # Iterate through each row + for j in range(1, i + 1): # Print numbers in each row + print(num, end=" ") + num += 1 # Increment the number for the next iteration + print() # Move to the next line after each row + + +# Example usage +n = 5 +print_triangular_pattern(n) + + From 82a25c9cbe7f828e64814ee5cc39fc3eab153226 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Thu, 6 Jul 2023 18:28:48 +0530 Subject: [PATCH 1557/1894] Create triangular_pattern.java --- Patterns/triangular_pattern.java | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Patterns/triangular_pattern.java diff --git a/Patterns/triangular_pattern.java b/Patterns/triangular_pattern.java new file mode 100644 index 00000000..ca32f798 --- /dev/null +++ b/Patterns/triangular_pattern.java @@ -0,0 +1,43 @@ +/* +Approach: +- Initialize the `rows` variable to determine the number of rows in the pattern. +- Initialize the `count` variable to keep track of the current number. +- Use nested `for` loops to iterate through the rows and columns. +- Print the current `count` value and increment it after printing. +- Move to the next line after each row by using `System.out.println()`. + +Time Complexity: The nested loops iterate through the rows and columns of the pattern, resulting in a time complexity of O(rows^2). + +Space Complexity: The space complexity is O(1) as we only require a few variables to store the number of rows, current count, and loop indices. + +Sample Input (rows = 5): +5 + +Sample Output: +1 +2 3 +4 5 6 +7 8 9 10 +11 12 13 14 15 +*/ + +//Java code for generating a number pattern in a triangular pattern, starting from 1: + +public class triangular_pattern { + public static void main(String[] args) { + int rows = 5; // number of rows in the pattern + + int count = 1; // variable to keep track of the current number + + // loop through the rows + for (int i = 1; i <= rows; i++) { + // loop through the columns + for (int j = 1; j <= i; j++) { + System.out.print(count + " "); + count++; + } + System.out.println(); // move to the next line after each row + } + } +} + From 6823f4a2a7c18beec0f33cd1e96951501958a83b Mon Sep 17 00:00:00 2001 From: Arsh Date: Thu, 6 Jul 2023 21:59:56 +0530 Subject: [PATCH 1558/1894] Add Implementation of Trie in js --- Trees/Binary Trees/Trie.js | 93 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Trees/Binary Trees/Trie.js diff --git a/Trees/Binary Trees/Trie.js b/Trees/Binary Trees/Trie.js new file mode 100644 index 00000000..b4f6522c --- /dev/null +++ b/Trees/Binary Trees/Trie.js @@ -0,0 +1,93 @@ +/* +Description +A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + +Implement the Trie class: + +Trie() Initializes the trie object. +void insert(String word) Inserts the string word into the trie. +boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. +boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. + +Input +["Trie", "insert", "search", "search", "startsWith", "insert", "search"] +[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] +Output +[null, null, true, false, true, null, true] + +Explanation +Trie trie = new Trie(); +trie.insert("apple"); +trie.search("apple"); // return True +trie.search("app"); // return False +trie.startsWith("app"); // return True +trie.insert("app"); +trie.search("app"); // return True + +Time Complexity for each operation is O(n) +Space Complexity O(n*m) where n is the number of words inserted and m is the average length of the words. + +Explanation: +insert() -> traverse through each character of the input word and initializes it if necessary. If the end of the word is reached set isEnd to true. +search() -> Search In each child node until the end of the word is reached, then if end of the node is also reached return true else false. +startsWith() -> Similar to search method but we only check if end of the prefix is reached and we don't need to check if it is the end of the node. + +*/ + + +class Trie { + constructor() { + this.root = new Node(); + } + + insert(word) { + this.root.insert(word, 0); + } + + search(word) { + return this.root.search(word, 0); + } + + startsWith(prefix) { + return this.root.startsWith(prefix, 0); + } +} + +class Node { + constructor() { + this.nodes = new Array(26); + this.isEnd = false; + } + + // Function to insert the word in the tree + insert(word, idx) { + if (idx >= word.length) return; // handle edge case + const i = word.charCodeAt(idx) - 'a'.charCodeAt(0); + if (!this.nodes[i]) { + this.nodes[i] = new Node(); // initialize the node[i] if the letter was not found before + } + + if (idx === word.length - 1) this.nodes[i].isEnd = true; // signifies that this is the end of the word + this.nodes[i].insert(word, idx + 1); // recursive call to populate the child node + } + + // Function to search the word in the tree + search(word, idx) { + if (idx >= word.length) return false; + const node = this.nodes[word.charCodeAt(idx) - 'a'.charCodeAt(0)]; + if (!node) return false; // if the node is null it means that it was not initialised hence the character was never found. + if (idx === word.length - 1 && node.isEnd) return true; //if it is the last character and the end of the node then return true + + return node.search(word, idx + 1); // recursive call search in the child node + } + + //Function to search the prefix in tree + startsWith(prefix, idx) { + if (idx >= prefix.length) return false; + const node = this.nodes[prefix.charCodeAt(idx) - 'a'.charCodeAt(0)]; + if (!node) return false; + if (idx === prefix.length - 1) return true; // Very similar to above method but here we don't need to check if it is the end of the node. + + return node.startsWith(prefix, idx + 1); + } +} From c78829de6d47c87e11773b3bf482de8650f36e9f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Jul 2023 23:28:19 +0530 Subject: [PATCH 1559/1894] add search in sorted matrix in go --- .../search_in_sorted_rotated_array.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Binary Search/search_in_sorted_rotated_array.go diff --git a/Binary Search/search_in_sorted_rotated_array.go b/Binary Search/search_in_sorted_rotated_array.go new file mode 100644 index 00000000..82dec63f --- /dev/null +++ b/Binary Search/search_in_sorted_rotated_array.go @@ -0,0 +1,25 @@ + +package main + +func SearchInSortedMatrix(matrix [][]int, target int) []int { + // Initialize the starting position at the top-right corner of the matrix + row, col := 0, len(matrix[0])-1 + + // Continue the loop as long as the current position is within the matrix bounds + for row < len(matrix) && col >= 0 { + // Compare the value at the current position with the target value + if matrix[row][col] > target { + // If the value is greater than the target, move to the left column + col-- + } else if matrix[row][col] < target { + // If the value is less than the target, move to the next row + row++ + } else { + // If the value is equal to the target, return the position [row, col] + return []int{row, col} + } + } + + // If the loop completes without finding the target, return [-1, -1] + return []int{-1, -1} +} From 75ee50051d87c55975bf7ca31b67c3e199074570 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Jul 2023 23:28:49 +0530 Subject: [PATCH 1560/1894] add main func --- .../search_in_sorted_rotated_array.go | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Binary Search/search_in_sorted_rotated_array.go b/Binary Search/search_in_sorted_rotated_array.go index 82dec63f..746b76d8 100644 --- a/Binary Search/search_in_sorted_rotated_array.go +++ b/Binary Search/search_in_sorted_rotated_array.go @@ -1,6 +1,32 @@ +/* + The code snippet represents a function `SearchInSortedMatrix` that searches for a target value in a sorted matrix and returns the position (row and column) of the target if found, or [-1, -1] if not found. + Here's how the code works: + + 1. Initialize the starting position at the top-right corner of the matrix, i.e., `row = 0` and `col = len(matrix[0]) - 1`. + + 2. Enter a loop that continues as long as the current position is within the matrix bounds, i.e., `row < len(matrix)` and `col >= 0`. + + 3. Inside the loop, compare the value at the current position (`matrix[row][col]`) with the target value: + - If the value is greater than the target, it means the target value must be in a lower column, so decrement the column + index (`col--`). + - If the value is less than the target, it means the target value must be in a higher row, so increment the row index + (`row++`). + - If the value is equal to the target, it means the target value is found. Return the position as [row, col]. + + 4. If the loop completes without finding the target value, it means the target is not present in the matrix. Return [-1, -1] + to indicate that the target was not found. + + The code takes advantage of the sorted nature of the matrix to perform an efficient search. By starting at the top-right + corner and comparing the current value with the target, it eliminates rows and columns in each iteration, narrowing down the search space until the target is found or the entire matrix is traversed. + + Overall, the code has a time complexity of O(N + M), where N is the number of rows in the matrix and M is the number of + columns, as it performs a linear search through the matrix. +*/ package main +import "fmt" + func SearchInSortedMatrix(matrix [][]int, target int) []int { // Initialize the starting position at the top-right corner of the matrix row, col := 0, len(matrix[0])-1 @@ -23,3 +49,23 @@ func SearchInSortedMatrix(matrix [][]int, target int) []int { // If the loop completes without finding the target, return [-1, -1] return []int{-1, -1} } + + +func main() { + matrix := [][]int{ + {1, 4, 7, 12, 15, 1000}, + {2, 5, 19, 31, 32, 1001}, + {3, 8, 24, 33, 35, 1002}, + {40, 41, 42, 44, 45, 1003}, + {99, 100, 103, 106, 128, 1004}, + } + + target := 33 + + result := SearchInSortedMatrix(matrix, target) + if result[0] == -1 && result[1] == -1 { + fmt.Println("Target not found in the matrix") + } else { + fmt.Println("Target found at position:", result) + } +} \ No newline at end of file From 263b6548669c2e6d92aaa5cb2bf2b08e37b8d313 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 6 Jul 2023 23:29:36 +0530 Subject: [PATCH 1561/1894] add time and space --- Binary Search/search_in_sorted_rotated_array.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Binary Search/search_in_sorted_rotated_array.go b/Binary Search/search_in_sorted_rotated_array.go index 746b76d8..09fedaf0 100644 --- a/Binary Search/search_in_sorted_rotated_array.go +++ b/Binary Search/search_in_sorted_rotated_array.go @@ -22,6 +22,9 @@ Overall, the code has a time complexity of O(N + M), where N is the number of rows in the matrix and M is the number of columns, as it performs a linear search through the matrix. + + Time complexity: O(n + m) time where n is the length of the matrix's rows and m is the length of the matrix's columns + Space complexity: O(1) */ package main From 4d640724690b94eba8546b70ab3a3b6566dad25c Mon Sep 17 00:00:00 2001 From: Manik Dingra Date: Fri, 7 Jul 2023 02:30:52 +0530 Subject: [PATCH 1562/1894] Code explaination and comments added --- PriorityQueues/Code/BuyTheTicket.cpp | 31 ++++++++++-- PriorityQueues/Code/CheckMaxHeap.cpp | 28 ++++++++++- PriorityQueues/Code/In_Place_HeapSort.cpp | 32 +++++++++++- PriorityQueues/Code/KLargestElement.cpp | 31 +++++++++++- PriorityQueues/Code/KSmallestElement.cpp | 36 +++++++++++++- PriorityQueues/Code/KthLargestElement.cpp | 21 +++++++- PriorityQueues/Code/Max_PriorityQueue.cpp | 11 ++--- PriorityQueues/Code/MergeKSortedArrays.cpp | 57 +++++++++++++++++----- PriorityQueues/Code/Min_PriorityQueues.cpp | 4 ++ PriorityQueues/Code/RunningMedian.cpp | 57 +++++++++++++++------- PriorityQueues/Code/tempCodeRunnerFile.cpp | 2 + 11 files changed, 264 insertions(+), 46 deletions(-) create mode 100644 PriorityQueues/Code/tempCodeRunnerFile.cpp diff --git a/PriorityQueues/Code/BuyTheTicket.cpp b/PriorityQueues/Code/BuyTheTicket.cpp index f254f246..ab35aefa 100644 --- a/PriorityQueues/Code/BuyTheTicket.cpp +++ b/PriorityQueues/Code/BuyTheTicket.cpp @@ -49,7 +49,19 @@ Sample Output 2 : 4 +Explaination : + The code first defines two data structures: a priority queue and a queue. The priority queue is used to store the priorities of all the people in the queue, and the queue is used to store the indices of the people in the queue. + + The function buyTicket() takes three parameters: an array of priorities, the number of people in the queue, and the index of the person who is buying the ticket. The function first pushes all the priorities into the priority queue. Then, it pushes all the indices into the queue. + + The function then enters a loop. In each iteration of the loop, the function checks if the priority of the person at the front of the queue is equal to the priority of the person who is buying the ticket. If it is, the function increments the time by 1, pops the person at the front of the queue, and pops the person at the front of the queue. If it is not, the function pops the person at the front of the queue and pushes them back into the queue. + + The function continues looping until the person who is buying the ticket is at the front of the queue. The function then returns the time it took for the person to buy the ticket. + + The main function of the code first prompts the user to enter the number of people in the queue. Then, it creates an array of priorities and prompts the user to enter the priorities of all the people in the queue. Finally, it prompts the user to enter the index of the person who is buying the ticket, and it prints the time it took for the person to buy the ticket. + */ + #include #include #include @@ -57,19 +69,26 @@ using namespace std; int buyTicket(int *arr, int n, int k) { + // Initialize a priority queue to store the priorities of all the people in the queue. priority_queue pq; + // Initialize a queue to store the indices of all the people in the queue. + queue indices; + // Push all the priorities into the priority queue. for (int i = 0; i < n; i++) { pq.push(arr[i]); } - queue indices; + // Push all the indices into the queue. for (int i = 0; i < n; i++) { indices.push(i); } + // Initialize the time it took for the person to buy the ticket. int time = 0; + // Loop until the person who is buying the ticket is at the front of the queue. while (!indices.empty()) { + // Check if the priority of the person at the front of the queue is equal to the priority of the person who is buying the ticket. if (arr[indices.front()] == pq.top() && indices.front() == k) { time++; @@ -77,12 +96,14 @@ int buyTicket(int *arr, int n, int k) indices.pop(); break; } + // If the priorities match, increment the time by 1 and break out of the loop. if (arr[indices.front()] == pq.top()) { time++; pq.pop(); indices.pop(); } + // If the priorities do not match, pop the person at the front of the queue and push them back into the queue. else { int temp = indices.front(); @@ -90,25 +111,29 @@ int buyTicket(int *arr, int n, int k) indices.push(temp); } } + // Return the time it took for the person to buy the ticket. return time; } int main() { + // Prompt the user to enter the number of people in the queue. int n; cin >> n; - + // Create an array of priorities and prompt the user to enter the priorities of all the people in the queue. int *arr = new int[n]; - for (int i = 0; i < n; i++) { cin >> arr[i]; } + // Prompt the user to enter the index of the person who is buying the ticket. int k; cin >> k; + // Print the time it took for the person to buy the ticket. cout << buyTicket(arr, n, k); + // Delete the array of priorities. delete[] arr; } \ No newline at end of file diff --git a/PriorityQueues/Code/CheckMaxHeap.cpp b/PriorityQueues/Code/CheckMaxHeap.cpp index a6ec0854..7bbdc45d 100644 --- a/PriorityQueues/Code/CheckMaxHeap.cpp +++ b/PriorityQueues/Code/CheckMaxHeap.cpp @@ -24,37 +24,61 @@ Sample Output 1: true +Explaination : + The code first defines a function called isMaxHeap(). This function takes two parameters: an array of integers and the size of the array. The function recursively checks if the array is a max heap. A max heap is a binary tree where the value of each parent node is greater than or equal to the value of each of its child nodes. + + The function starts by checking the last element of the array. If the parent of the last element is smaller than the last element, the function returns false. Otherwise, the function recursively checks the parent of the last element. This process continues until the function reaches the root of the tree. + + If the function reaches the root of the tree and all of the parent nodes are greater than or equal to their child nodes, the function returns true. Otherwise, the function returns false. + + The main function of the code prompts the user to enter the size of the array and then prompts the user to enter the elements of the array. The main function then calls the isMaxHeap() function and prints the result. + */ + #include using namespace std; bool isMaxHeap(int arr[], int n) { + + // This function recursively checks if the array is a max heap. + // The function starts at the last element of the array and checks if the parent is smaller than the child. + // If the parent is smaller than the child, the function returns false. + // Otherwise, the function recursively checks the parent of the child. + int childIndex = n - 1; while (childIndex >= 0) { int parentIndex = (childIndex - 1) / 2; + // Check if the parent is smaller than the child. if (arr[parentIndex] < arr[childIndex]) { return false; } + // Recursively check the parent of the child. childIndex--; } + // The array is a max heap. return true; } int main() { + + // Prompt the user to enter the size of the array. int n; cin >> n; - int *arr = new int[n]; + // Create an array and prompt the user to enter the elements of the array. + int *arr = new int[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } + // Check if the array is a max heap. cout << (isMaxHeap(arr, n) ? "true\n" : "false\n"); + // Delete the array. delete[] arr; -} \ No newline at end of file +} diff --git a/PriorityQueues/Code/In_Place_HeapSort.cpp b/PriorityQueues/Code/In_Place_HeapSort.cpp index 5083c94d..dbd62754 100644 --- a/PriorityQueues/Code/In_Place_HeapSort.cpp +++ b/PriorityQueues/Code/In_Place_HeapSort.cpp @@ -23,6 +23,19 @@ Sample Input 1: Sample Output 1: 8 6 5 4 3 2 + +Explaination : + The code implements the heap sort algorithm, which is a sorting algorithm that works by first building a max heap. A max heap is a binary tree where the value of each parent node is greater than or equal to the value of each of its child nodes. + + The heap sort algorithm works by repeatedly swapping the root element of the heap with the last element of the array and then rebuilding the heap without the root element. This process is repeated until the array is sorted. + + The code first defines a function called heapSort(). This function takes two parameters: an array of integers and the size of the array. The function builds a max heap from the bottom up and then sorts the array by repeatedly swapping the root element with the last element and rebuilding the heap. + + The main function of the code prompts the user to enter the size of the array and then prompts the user to enter the elements of the array. The main function then calls the heapSort() function and prints the sorted array. + + The intuition behind the heap sort algorithm is that it takes advantage of the fact that a max heap is already partially sorted. By repeatedly swapping the root element with the last element of the array and rebuilding the heap, the algorithm is able to sort the array in a relatively efficient way. + + The heap sort algorithm is a divide-and-conquer algorithm, which means that it breaks the problem of sorting an array into smaller and smaller subproblems until they are trivial to solve. This makes the algorithm very efficient for sorting large arrays. */ #include @@ -30,37 +43,52 @@ using namespace std; void heapSort(int arr[], int n) { + // This function sorts an array using the heap sort algorithm. + // The algorithm works by first building a max heap. + // Then, the root of the heap is swapped with the last element of the array. + // The heap is then rebuilt without the root element. + // This process is repeated until the array is sorted. + for (int i = 1; i < n; i++) { + // Recursively build a max heap from the bottom up. int childIndex = i; while (childIndex > 0) { int parentIndex = (childIndex - 1) / 2; if (arr[childIndex] < arr[parentIndex]) { + // Swap the child and parent. int temp = arr[childIndex]; arr[childIndex] = arr[parentIndex]; arr[parentIndex] = temp; } else { + // The heap is already a max heap. break; } childIndex = parentIndex; } } + + // Sort the array by repeatedly swapping the root element with the last element and rebuilding the heap. int j = n; while (j > 1) { + // Swap the root element with the last element. int temp = arr[0]; arr[0] = arr[j - 1]; arr[j - 1] = temp; j--; + + // Rebuild the heap without the root element. int parentIndex = 0; int rightChildIndex = 2 * parentIndex + 2; int leftChildIndex = 2 * parentIndex + 1; while (leftChildIndex < j) { + // Find the minimum child. int minIndex = parentIndex; if (arr[leftChildIndex] < arr[minIndex]) { @@ -71,12 +99,14 @@ void heapSort(int arr[], int n) minIndex = rightChildIndex; } + // Swap the minimum child with the parent. int temp = arr[minIndex]; arr[minIndex] = arr[parentIndex]; arr[parentIndex] = temp; if (parentIndex == minIndex) { + // The heap is already a max heap. break; } parentIndex = minIndex; @@ -106,4 +136,4 @@ int main() } delete[] input; -} \ No newline at end of file +} diff --git a/PriorityQueues/Code/KLargestElement.cpp b/PriorityQueues/Code/KLargestElement.cpp index e7f3015f..a9630033 100644 --- a/PriorityQueues/Code/KLargestElement.cpp +++ b/PriorityQueues/Code/KLargestElement.cpp @@ -25,18 +25,37 @@ Sample Output : 20 25 +Explaination : + The code first defines a function called kLargest(). This function takes three parameters: an array of integers, the size of the array, and the number of largest elements to find. The function uses a priority queue to find the k largest elements in the array. + + The code then defines a main function. The main function prompts the user to enter the size of the array and the number of largest elements to find. The main function then creates an array of integers and prompts the user to enter the elements of the array. The main function then calls the kLargest() function and prints the k largest elements in the array. + + The kLargest() function works as follows: + + The function first creates a priority queue and pushes the first k elements of the array onto the priority queue. + The function then iterates through the remaining elements of the array. If the current element is greater than the top element of the priority queue, the function pushes the current element onto the priority queue and pops the top element of the priority queue. + The function then returns a vector of the elements in the priority queue. + + */ #include #include using namespace std; +// This function finds the k largest elements in an array. vector kLargest(int input[], int n, int k) { + + // Create a priority queue and push the first k elements of the array onto the priority queue. priority_queue, greater> pq; for (int i = 0; i < k; i++) { pq.push(input[i]); } + + // Iterate through the remaining elements of the array. + // If the current element is greater than the top element of the priority queue, + // push the current element onto the priority queue and pop the top element of the priority queue. for (int i = k; i < n; i++) { if (input[i] > pq.top()) @@ -45,6 +64,8 @@ vector kLargest(int input[], int n, int k) pq.pop(); } } + + // Return a vector of the elements in the priority queue. vector ans; while (!pq.empty()) { @@ -57,19 +78,27 @@ vector kLargest(int input[], int n, int k) int main() { + // Prompt the user to enter the size of the array and the number of largest elements to find. int size; cin >> size; int *input = new int[1 + size]; + // Prompt the user to enter the elements of the array. for (int i = 0; i < size; i++) + { cin >> input[i]; + } + // Prompt the user to enter the number of largest elements to find. int k; cin >> k; + // Call the `kLargest()` function and print the k largest elements in the array. vector output = kLargest(input, size, k); for (int i = 0; i < output.size(); i++) + { cout << output[i] << endl; + } return 0; -} \ No newline at end of file +} diff --git a/PriorityQueues/Code/KSmallestElement.cpp b/PriorityQueues/Code/KSmallestElement.cpp index 725de8f5..3cb84fc5 100644 --- a/PriorityQueues/Code/KSmallestElement.cpp +++ b/PriorityQueues/Code/KSmallestElement.cpp @@ -26,6 +26,19 @@ Sample Output 1 : 1 2 3 5 +Explaination : + + The code first defines a function called kSmallest(). This function takes three parameters: an array of integers, the size of the array, and the number of smallest elements to find. The function uses a priority queue to find the k smallest elements in the array. + + The code then defines a main function. The main function prompts the user to enter the size of the array and the number of smallest elements to find. The main function then creates an array of integers and prompts the user to enter the elements of the array. The main function then calls the kSmallest() function and prints the k smallest elements in the array. + + The kSmallest() function works as follows: + + The function first creates a priority queue and pushes the first k elements of the array onto the priority queue. + The function then iterates through the remaining elements of the array. If the current element is less than the top element of the priority queue, the function pushes the current element onto the priority queue and pops the top element of the priority queue. + The function then returns a vector of the elements in the priority queue. + + */ #include #include @@ -33,13 +46,20 @@ Sample Output 1 : #include using namespace std; +// This function finds the k smallest elements in an array. vector kSmallest(int arr[], int n, int k) { + + // Create a priority queue and push the first k elements of the array onto the priority queue. priority_queue pq; for (int i = 0; i < k; i++) { pq.push(arr[i]); } + + // Iterate through the remaining elements of the array. + // If the current element is less than the top element of the priority queue, + // push the current element onto the priority queue and pop the top element of the priority queue. for (int i = k; i < n; i++) { if (arr[i] < pq.top()) @@ -48,6 +68,8 @@ vector kSmallest(int arr[], int n, int k) pq.pop(); } } + + // Return a vector of the elements in the priority queue. vector vec; while (!pq.empty()) { @@ -57,28 +79,40 @@ vector kSmallest(int arr[], int n, int k) return vec; } +// This is the main function. int main() { + + // Prompt the user to enter the size of the array and the number of smallest elements to find. int size; cin >> size; + // Create an array of integers. int *input = new int[size]; + // Prompt the user to enter the elements of the array. for (int i = 0; i < size; i++) { cin >> input[i]; } + // Prompt the user to enter the number of smallest elements to find. int k; cin >> k; + // Call the `kSmallest()` function and print the k smallest elements in the array. vector output = kSmallest(input, size, k); + + // Sort the output vector in ascending order. sort(output.begin(), output.end()); + // Print the output vector. for (int i = 0; i < output.size(); i++) { cout << output[i] << " "; } + // Delete the array. delete[] input; -} \ No newline at end of file + return 0; +} diff --git a/PriorityQueues/Code/KthLargestElement.cpp b/PriorityQueues/Code/KthLargestElement.cpp index b924699c..e8ddac1b 100644 --- a/PriorityQueues/Code/KthLargestElement.cpp +++ b/PriorityQueues/Code/KthLargestElement.cpp @@ -36,27 +36,42 @@ Sample Output 2 : 10 +Explaination : + The code uses a min-heap priority queue (pq) to find the kth largest element in the given array. It initializes the priority queue with the first k elements of the array. Then, it iterates over the remaining elements of the array and compares each element with the smallest element (top) of the priority queue. If the current element is larger, it replaces the smallest element in the priority queue. Finally, it returns the top element of the priority queue, which will be the kth largest element. + + Note: The code dynamically allocates memory for the array using new and deallocates it using delete[] to ensure proper memory management. + */ #include #include #include using namespace std; +// Function to find the kth largest element in an array int kthLargest(int *arr, int n, int k) { + // Create a min-heap priority queue priority_queue, greater> pq; + + // Insert the first k elements into the priority queue for (int i = 0; i < k; i++) { pq.push(arr[i]); } + + // Iterate over the remaining elements in the array for (int i = k; i < n; i++) { + // If the current element is greater than the smallest element in the priority queue (top), + // replace the smallest element with the current element if (arr[i] > pq.top()) { pq.push(arr[i]); pq.pop(); } } + + // The top element of the priority queue will be the kth largest element return pq.top(); } @@ -65,8 +80,10 @@ int main() int n; cin >> n; + // Dynamically allocate memory for the array int *arr = new int[n]; + // Read the elements of the array from the user for (int i = 0; i < n; i++) { cin >> arr[i]; @@ -75,7 +92,9 @@ int main() int k; cin >> k; + // Call the kthLargest function to find the kth largest element cout << kthLargest(arr, n, k); + // Deallocate the memory for the array delete[] arr; -} \ No newline at end of file +} diff --git a/PriorityQueues/Code/Max_PriorityQueue.cpp b/PriorityQueues/Code/Max_PriorityQueue.cpp index a776ab05..f907f72d 100644 --- a/PriorityQueues/Code/Max_PriorityQueue.cpp +++ b/PriorityQueues/Code/Max_PriorityQueue.cpp @@ -11,7 +11,11 @@ Return the maximum element present in the priority queue without deleting. Retur 5. removeMax - Delete and return the maximum element present in the priority queue. Return -Infinity if priority queue is empty. Note : main function is given for your reference which we are using internally to test the class. + +Explaination : + This code implements a priority queue using a max-heap data structure. Let's go through the code and add comments to explain each section: */ + #include #include #include @@ -22,13 +26,6 @@ class PriorityQueue vector pq; public: - PriorityQueue() - { - // Implement the constructor here - } - - /**************** Implement all the public functions here ***************/ - void insert(int element) { pq.push_back(element); diff --git a/PriorityQueues/Code/MergeKSortedArrays.cpp b/PriorityQueues/Code/MergeKSortedArrays.cpp index 312300ec..36174e52 100644 --- a/PriorityQueues/Code/MergeKSortedArrays.cpp +++ b/PriorityQueues/Code/MergeKSortedArrays.cpp @@ -32,6 +32,16 @@ Sample Output 1: 0 1 2 5 6 9 45 78 90 100 234 +Explaination : + The intuition behind the code is to use a min-heap (priority queue) to merge K sorted arrays efficiently. + + By taking the first element from each array and inserting it into the priority queue, the smallest element is always at the top. This ensures that when elements are extracted from the priority queue, they are in sorted order. + + The code iteratively extracts the smallest element from the priority queue, adds it to the merged sorted array, and checks if there are remaining elements in the array from which the extracted element came. If so, the next element from that array is inserted into the priority queue. + + This process continues until all elements from all arrays are processed and added to the merged sorted array. + + By utilizing the min-heap property of the priority queue, the code efficiently merges the sorted arrays in a way that the overall time complexity is optimized. The priority queue allows for easy retrieval of the smallest element, resulting in an overall time complexity of O(N log K), where N is the total number of elements across all arrays and K is the number of arrays. */ #include #include @@ -40,62 +50,83 @@ using namespace std; vector mergeKSortedArrays(vector *> input) { + // Create a min-heap priority queue to store elements from different arrays priority_queue>, vector>>, greater>>> pq; + + // Insert the first element from each array into the priority queue for (int i = 0; i < input.size(); i++) { pair> p; - p.first = input[i]->at(0); - p.second.first = i; - p.second.second = 0; + p.first = input[i]->at(0); // value of the element + p.second.first = i; // array number + p.second.second = 0; // index of the element pq.push(p); } + + // Initialize a vector to store the merged sorted array vector ans; + + // Process the priority queue until it becomes empty while (!pq.empty()) { pair> p = pq.top(); pq.pop(); + + // Add the minimum element to the result vector ans.push_back(p.first); - int arrNo = p.second.first; - int index = p.second.second + 1; + + int arrNo = p.second.first; // array number + int index = p.second.second + 1; // index of the next element in the array + + // If there are still elements remaining in the array, add the next element to the priority queue if (index < input[arrNo]->size()) { - p.first = input[arrNo]->at(index); - p.second.second = index; + p.first = input[arrNo]->at(index); // value of the element + p.second.second = index; // update the index pq.push(p); } } + + // Return the merged sorted array return ans; } int main() { int k; - cin >> k; + cin >> k; // Number of sorted arrays - vector *> input; + vector *> input; // Vector to store the arrays + // Read the size and elements of each array for (int j = 1; j <= k; j++) { int size; - cin >> size; + cin >> size; // Size of the array + + // Create a dynamically allocated vector for the current array vector *current = new vector; + // Read the elements of the array for (int i = 0; i < size; i++) { int a; - cin >> a; - current->push_back(a); + cin >> a; // Element of the array + current->push_back(a); // Add the element to the current array } + // Add the current array to the vector of arrays input.push_back(current); } + // Merge the sorted arrays using the mergeKSortedArrays function vector output = mergeKSortedArrays(input); + // Print the merged sorted array for (int i = 0; i < output.size(); i++) { cout << output[i] << " "; } return 0; -} \ No newline at end of file +} diff --git a/PriorityQueues/Code/Min_PriorityQueues.cpp b/PriorityQueues/Code/Min_PriorityQueues.cpp index 57781231..74168b41 100644 --- a/PriorityQueues/Code/Min_PriorityQueues.cpp +++ b/PriorityQueues/Code/Min_PriorityQueues.cpp @@ -1,3 +1,7 @@ +/* +Explaination : + Implementation of min priority queue +*/ #include #include #include diff --git a/PriorityQueues/Code/RunningMedian.cpp b/PriorityQueues/Code/RunningMedian.cpp index 4942d9f6..628ae5c7 100644 --- a/PriorityQueues/Code/RunningMedian.cpp +++ b/PriorityQueues/Code/RunningMedian.cpp @@ -45,31 +45,49 @@ Sample Output 2 : 5 4 4 3 3 -*/ +Explaination : + + The code aims to efficiently find and print the median of a stream of integers as they are read one by one. It achieves this by using two priority queues: `min` and `max`. These priority queues divide the elements encountered so far into the lower and higher halves, allowing for the calculation of the median. + + When reading the integers one by one, the code follows these steps: + + 1. For the first element, it is pushed into the `max` priority queue. At this point, the median is simply the first element. + + 2. For subsequent elements, the code compares each element with the current median (which is the top element of the `max` priority queue). If the new element is smaller, it is pushed into the `max` priority queue. This ensures that the lower half of the elements is stored in `max`, with the maximum element of the lower half at the top. + + 3. If the new element is larger than the current median, it is pushed into the `min` priority queue. This ensures that the higher half of the elements is stored in `min`, with the minimum element of the higher half at the top. + + 4. After each insertion, the code checks the size difference between the `min` and `max` priority queues. If the difference exceeds 1, it rebalances the queues by transferring the top element from the larger queue to the smaller one. This ensures that the size difference between the two halves remains at most 1, allowing for accurate median calculations. + + 5. To calculate and print the median, the code checks the total number of elements (c) in both priority queues. If c is even, the median is the average of the top elements of `min` and `max`. If c is odd, the median is the top element of the priority queue with more elements. + By using two priority queues to maintain the lower and higher halves of the elements encountered so far, the code efficiently updates and calculates the median of the stream of integers in a scalable manner. The rebalancing step ensures that the size difference between the two halves remains at most 1, allowing for accurate median calculations even as new elements are added to the stream. + +*/ #include #include using namespace std; void findMedian(int *arr, int n) { - priority_queue, greater> min; - priority_queue max; + priority_queue, greater> min; // Min-heap to store the higher half of the elements encountered + priority_queue max; // Max-heap to store the lower half of the elements encountered + for (int i = 0; i < n; i++) { if (i == 0) { - max.push(arr[i]); + max.push(arr[i]); // For the first element, push it into the max heap } else { if (max.top() > arr[i]) { - max.push(arr[i]); + max.push(arr[i]); // If the new element is smaller than the current median, push it into the max heap } else { - min.push(arr[i]); + min.push(arr[i]); // If the new element is larger than the current median, push it into the min heap } } @@ -77,47 +95,52 @@ void findMedian(int *arr, int n) { int temp = min.top(); min.pop(); - max.push(temp); + max.push(temp); // Rebalance the heaps by transferring the top element from min heap to max heap } else if (int(max.size() - min.size()) > 1) { int temp = max.top(); max.pop(); - min.push(temp); + min.push(temp); // Rebalance the heaps by transferring the top element from max heap to min heap } - int c = max.size() + min.size(); + + int c = max.size() + min.size(); // Total count of elements + if (c % 2 == 0) { - cout << (min.top() + max.top()) / 2 << " "; + cout << (min.top() + max.top()) / 2 << " "; // If total count is even, median is the average of the top elements of both heaps } else { if (min.size() > max.size()) { - cout << min.top() << " "; + cout << min.top() << " "; // If total count is odd and min heap has more elements, median is the top element of min heap } else { - cout << max.top() << " "; + cout << max.top() << " "; // If total count is odd and max heap has more elements, median is the top element of max heap } } } + cout << endl; } int main() { int n; - cin >> n; + cin >> n; // Number of elements - int *arr = new int[n]; + int *arr = new int[n]; // Dynamically allocate memory for the array for (int i = 0; i < n; ++i) { - cin >> arr[i]; + cin >> arr[i]; // Read the elements of the array } - findMedian(arr, n); + findMedian(arr, n); // Find and print the median of the stream + + delete[] arr; // Deallocate the memory - delete[] arr; + return 0; } diff --git a/PriorityQueues/Code/tempCodeRunnerFile.cpp b/PriorityQueues/Code/tempCodeRunnerFile.cpp new file mode 100644 index 00000000..ac7d3036 --- /dev/null +++ b/PriorityQueues/Code/tempCodeRunnerFile.cpp @@ -0,0 +1,2 @@ +6 +6 2 1 3 7 5 \ No newline at end of file From e451dbd476c8dea9412acf32e2d5d10762462a48 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 22:51:40 +0530 Subject: [PATCH 1563/1894] remove code folder --- {PriorityQueues/Code => Priority Queues}/BuyTheTicket.cpp | 0 {PriorityQueues/Code => Priority Queues}/CheckMaxHeap.cpp | 0 .../Code => Priority Queues}/InBuilt_PriorityQueue.cpp | 0 {PriorityQueues/Code => Priority Queues}/In_Place_HeapSort.cpp | 0 .../Code => Priority Queues}/Inbuilt_MinPriorityQueue.cpp | 0 {PriorityQueues/Code => Priority Queues}/KLargestElement.cpp | 0 {PriorityQueues/Code => Priority Queues}/KSmallestElement.cpp | 0 {PriorityQueues/Code => Priority Queues}/KSortedArray.cpp | 0 {PriorityQueues/Code => Priority Queues}/KthLargestElement.cpp | 0 {PriorityQueues/Code => Priority Queues}/Max_PriorityQueue.cpp | 0 {PriorityQueues/Code => Priority Queues}/MergeKSortedArrays.cpp | 0 {PriorityQueues/Code => Priority Queues}/Min_PriorityQueues.cpp | 0 {PriorityQueues/Code => Priority Queues}/RunningMedian.cpp | 0 {PriorityQueues/Code => Priority Queues}/tempCodeRunnerFile.cpp | 0 14 files changed, 0 insertions(+), 0 deletions(-) rename {PriorityQueues/Code => Priority Queues}/BuyTheTicket.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/CheckMaxHeap.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/InBuilt_PriorityQueue.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/In_Place_HeapSort.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/Inbuilt_MinPriorityQueue.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/KLargestElement.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/KSmallestElement.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/KSortedArray.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/KthLargestElement.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/Max_PriorityQueue.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/MergeKSortedArrays.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/Min_PriorityQueues.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/RunningMedian.cpp (100%) rename {PriorityQueues/Code => Priority Queues}/tempCodeRunnerFile.cpp (100%) diff --git a/PriorityQueues/Code/BuyTheTicket.cpp b/Priority Queues/BuyTheTicket.cpp similarity index 100% rename from PriorityQueues/Code/BuyTheTicket.cpp rename to Priority Queues/BuyTheTicket.cpp diff --git a/PriorityQueues/Code/CheckMaxHeap.cpp b/Priority Queues/CheckMaxHeap.cpp similarity index 100% rename from PriorityQueues/Code/CheckMaxHeap.cpp rename to Priority Queues/CheckMaxHeap.cpp diff --git a/PriorityQueues/Code/InBuilt_PriorityQueue.cpp b/Priority Queues/InBuilt_PriorityQueue.cpp similarity index 100% rename from PriorityQueues/Code/InBuilt_PriorityQueue.cpp rename to Priority Queues/InBuilt_PriorityQueue.cpp diff --git a/PriorityQueues/Code/In_Place_HeapSort.cpp b/Priority Queues/In_Place_HeapSort.cpp similarity index 100% rename from PriorityQueues/Code/In_Place_HeapSort.cpp rename to Priority Queues/In_Place_HeapSort.cpp diff --git a/PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp b/Priority Queues/Inbuilt_MinPriorityQueue.cpp similarity index 100% rename from PriorityQueues/Code/Inbuilt_MinPriorityQueue.cpp rename to Priority Queues/Inbuilt_MinPriorityQueue.cpp diff --git a/PriorityQueues/Code/KLargestElement.cpp b/Priority Queues/KLargestElement.cpp similarity index 100% rename from PriorityQueues/Code/KLargestElement.cpp rename to Priority Queues/KLargestElement.cpp diff --git a/PriorityQueues/Code/KSmallestElement.cpp b/Priority Queues/KSmallestElement.cpp similarity index 100% rename from PriorityQueues/Code/KSmallestElement.cpp rename to Priority Queues/KSmallestElement.cpp diff --git a/PriorityQueues/Code/KSortedArray.cpp b/Priority Queues/KSortedArray.cpp similarity index 100% rename from PriorityQueues/Code/KSortedArray.cpp rename to Priority Queues/KSortedArray.cpp diff --git a/PriorityQueues/Code/KthLargestElement.cpp b/Priority Queues/KthLargestElement.cpp similarity index 100% rename from PriorityQueues/Code/KthLargestElement.cpp rename to Priority Queues/KthLargestElement.cpp diff --git a/PriorityQueues/Code/Max_PriorityQueue.cpp b/Priority Queues/Max_PriorityQueue.cpp similarity index 100% rename from PriorityQueues/Code/Max_PriorityQueue.cpp rename to Priority Queues/Max_PriorityQueue.cpp diff --git a/PriorityQueues/Code/MergeKSortedArrays.cpp b/Priority Queues/MergeKSortedArrays.cpp similarity index 100% rename from PriorityQueues/Code/MergeKSortedArrays.cpp rename to Priority Queues/MergeKSortedArrays.cpp diff --git a/PriorityQueues/Code/Min_PriorityQueues.cpp b/Priority Queues/Min_PriorityQueues.cpp similarity index 100% rename from PriorityQueues/Code/Min_PriorityQueues.cpp rename to Priority Queues/Min_PriorityQueues.cpp diff --git a/PriorityQueues/Code/RunningMedian.cpp b/Priority Queues/RunningMedian.cpp similarity index 100% rename from PriorityQueues/Code/RunningMedian.cpp rename to Priority Queues/RunningMedian.cpp diff --git a/PriorityQueues/Code/tempCodeRunnerFile.cpp b/Priority Queues/tempCodeRunnerFile.cpp similarity index 100% rename from PriorityQueues/Code/tempCodeRunnerFile.cpp rename to Priority Queues/tempCodeRunnerFile.cpp From ee7b0b34aafabf481b62b88f21fb2c90457ee77b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 22:53:12 +0530 Subject: [PATCH 1564/1894] remove program with no explanation --- Priority Queues/InBuilt_PriorityQueue.cpp | 22 -------------------- Priority Queues/Inbuilt_MinPriorityQueue.cpp | 22 -------------------- 2 files changed, 44 deletions(-) delete mode 100644 Priority Queues/InBuilt_PriorityQueue.cpp delete mode 100644 Priority Queues/Inbuilt_MinPriorityQueue.cpp diff --git a/Priority Queues/InBuilt_PriorityQueue.cpp b/Priority Queues/InBuilt_PriorityQueue.cpp deleted file mode 100644 index c212b08b..00000000 --- a/Priority Queues/InBuilt_PriorityQueue.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -using namespace std; - -int main() -{ - priority_queue pq; - pq.push(10); - pq.push(20); - pq.push(30); - cout << pq.empty() << endl; - cout << pq.size() << endl; - cout << pq.top() << endl; - while (!pq.empty()) - { - cout << pq.top() << endl; - pq.pop(); - } - cout << pq.size() << endl; - cout << pq.empty() << endl; - return 0; -} \ No newline at end of file diff --git a/Priority Queues/Inbuilt_MinPriorityQueue.cpp b/Priority Queues/Inbuilt_MinPriorityQueue.cpp deleted file mode 100644 index de686393..00000000 --- a/Priority Queues/Inbuilt_MinPriorityQueue.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include -#include -using namespace std; - -int main() -{ - priority_queue, greater> pq; - pq.push(10); - pq.push(20); - pq.push(30); - cout << pq.empty() << endl; - cout << pq.size() << endl; - cout << pq.top() << endl; - while (!pq.empty()) - { - cout << pq.top() << endl; - pq.pop(); - } - cout << pq.size() << endl; - cout << pq.empty() << endl; - return 0; -} \ No newline at end of file From 73bd111c8ca9da50333f4ac23381f2f79857ba7a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 22:57:06 +0530 Subject: [PATCH 1565/1894] make file name consistent and remove programs with no explanation --- Priority Queues/KLargestElement.cpp | 104 ------------- Priority Queues/KSortedArray.cpp | 39 ----- Priority Queues/Max_PriorityQueue.cpp | 141 ------------------ Priority Queues/Min_PriorityQueues.cpp | 111 -------------- .../{BuyTheTicket.cpp => buy_the_ticket.cpp} | 0 .../{CheckMaxHeap.cpp => check_max_heap.cpp} | 0 ...estElement.cpp => kth_largest_element.cpp} | 0 ...stElement.cpp => kth_smallest_element.cpp} | 0 ...edArrays.cpp => merge_k_sorted_arrays.cpp} | 0 .../{RunningMedian.cpp => running_median.cpp} | 0 Priority Queues/tempCodeRunnerFile.cpp | 2 - 11 files changed, 397 deletions(-) delete mode 100644 Priority Queues/KLargestElement.cpp delete mode 100644 Priority Queues/KSortedArray.cpp delete mode 100644 Priority Queues/Max_PriorityQueue.cpp delete mode 100644 Priority Queues/Min_PriorityQueues.cpp rename Priority Queues/{BuyTheTicket.cpp => buy_the_ticket.cpp} (100%) rename Priority Queues/{CheckMaxHeap.cpp => check_max_heap.cpp} (100%) rename Priority Queues/{KthLargestElement.cpp => kth_largest_element.cpp} (100%) rename Priority Queues/{KSmallestElement.cpp => kth_smallest_element.cpp} (100%) rename Priority Queues/{MergeKSortedArrays.cpp => merge_k_sorted_arrays.cpp} (100%) rename Priority Queues/{RunningMedian.cpp => running_median.cpp} (100%) delete mode 100644 Priority Queues/tempCodeRunnerFile.cpp diff --git a/Priority Queues/KLargestElement.cpp b/Priority Queues/KLargestElement.cpp deleted file mode 100644 index a9630033..00000000 --- a/Priority Queues/KLargestElement.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* -You are given with an integer k and an array of integers that contain numbers in random order. Write a program to find k largest numbers from given array. You need to save them in an array and return it. -Time complexity should be O(nlogk) and space complexity should be not more than O(k). -Order of elements in the output is not important. -Input Format : - -Line 1 : Size of array (n) -Line 2 : Array elements (separated by space) -Line 3 : Integer k - -Output Format : - -k largest elements - -Sample Input : - -13 -2 12 9 16 10 5 3 20 25 11 1 8 6 -4 - -Sample Output : - -12 -16 -20 -25 - -Explaination : - The code first defines a function called kLargest(). This function takes three parameters: an array of integers, the size of the array, and the number of largest elements to find. The function uses a priority queue to find the k largest elements in the array. - - The code then defines a main function. The main function prompts the user to enter the size of the array and the number of largest elements to find. The main function then creates an array of integers and prompts the user to enter the elements of the array. The main function then calls the kLargest() function and prints the k largest elements in the array. - - The kLargest() function works as follows: - - The function first creates a priority queue and pushes the first k elements of the array onto the priority queue. - The function then iterates through the remaining elements of the array. If the current element is greater than the top element of the priority queue, the function pushes the current element onto the priority queue and pops the top element of the priority queue. - The function then returns a vector of the elements in the priority queue. - - -*/ -#include -#include -using namespace std; - -// This function finds the k largest elements in an array. -vector kLargest(int input[], int n, int k) -{ - - // Create a priority queue and push the first k elements of the array onto the priority queue. - priority_queue, greater> pq; - for (int i = 0; i < k; i++) - { - pq.push(input[i]); - } - - // Iterate through the remaining elements of the array. - // If the current element is greater than the top element of the priority queue, - // push the current element onto the priority queue and pop the top element of the priority queue. - for (int i = k; i < n; i++) - { - if (input[i] > pq.top()) - { - pq.push(input[i]); - pq.pop(); - } - } - - // Return a vector of the elements in the priority queue. - vector ans; - while (!pq.empty()) - { - ans.push_back(pq.top()); - pq.pop(); - } - return ans; -} - -int main() -{ - - // Prompt the user to enter the size of the array and the number of largest elements to find. - int size; - cin >> size; - int *input = new int[1 + size]; - - // Prompt the user to enter the elements of the array. - for (int i = 0; i < size; i++) - { - cin >> input[i]; - } - - // Prompt the user to enter the number of largest elements to find. - int k; - cin >> k; - - // Call the `kLargest()` function and print the k largest elements in the array. - vector output = kLargest(input, size, k); - for (int i = 0; i < output.size(); i++) - { - cout << output[i] << endl; - } - - return 0; -} diff --git a/Priority Queues/KSortedArray.cpp b/Priority Queues/KSortedArray.cpp deleted file mode 100644 index 49b98b71..00000000 --- a/Priority Queues/KSortedArray.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -using namespace std; - -void kSortedArray(int arr[], int n, int k) -{ - priority_queue pq; - for (int i = 0; i < k; i++) - { - pq.push(arr[i]); - } - int j = 0; - for (int i = k; i < n; i++) - { - arr[j] = pq.top(); - pq.pop(); - pq.push(arr[i]); - j++; - } - while (!pq.empty()) - { - arr[j] = pq.top(); - pq.pop(); - j++; - } -} - -int main() -{ - int arr[] = {12, 15, 6, 7, 9}; - int k = 3; - kSortedArray(arr, 5, k); - for (int i = 0; i < 5; i++) - { - cout << arr[i] << " "; - } - cout << endl; - return 0; -} \ No newline at end of file diff --git a/Priority Queues/Max_PriorityQueue.cpp b/Priority Queues/Max_PriorityQueue.cpp deleted file mode 100644 index f907f72d..00000000 --- a/Priority Queues/Max_PriorityQueue.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -Implement the class for Max Priority Queue which includes following functions - -1. getSize - -Return the size of priority queue i.e. number of elements present in the priority queue. -2. isEmpty - -Check if priority queue is empty or not. Return true or false accordingly. -3. insert - -Given an element, insert that element in the priority queue at the correct position. -4. getMax - -Return the maximum element present in the priority queue without deleting. Return -Infinity if priority queue is empty. -5. removeMax - -Delete and return the maximum element present in the priority queue. Return -Infinity if priority queue is empty. -Note : main function is given for your reference which we are using internally to test the class. - -Explaination : - This code implements a priority queue using a max-heap data structure. Let's go through the code and add comments to explain each section: -*/ - -#include -#include -#include -using namespace std; - -class PriorityQueue -{ - vector pq; - -public: - void insert(int element) - { - pq.push_back(element); - int childIndex = pq.size() - 1; - - while (childIndex > 0) - { - int parentIndex = (childIndex - 1) / 2; - if (pq[parentIndex] < pq[childIndex]) - { - int temp = pq[childIndex]; - pq[childIndex] = pq[parentIndex]; - pq[parentIndex] = temp; - } - else - { - break; - } - childIndex = parentIndex; - } - } - - int getMax() - { - if (isEmpty()) - { - return INT_MIN; - } - return pq[0]; - } - - int removeMax() - { - if (pq.size() == 0) - { - return INT_MIN; - } - int ans = pq[0]; - pq[0] = pq[pq.size() - 1]; - pq.pop_back(); - int parentIndex = 0; - int leftChildIndex = 2 * parentIndex + 1; - int rightChildIndex = 2 * parentIndex + 2; - while (leftChildIndex < pq.size()) - { - int maxIndex = parentIndex; - if (pq[leftChildIndex] > pq[parentIndex]) - { - maxIndex = leftChildIndex; - } - if (rightChildIndex < pq.size() && pq[rightChildIndex] > pq[maxIndex]) - { - maxIndex = rightChildIndex; - } - int temp = pq[parentIndex]; - pq[parentIndex] = pq[maxIndex]; - pq[maxIndex] = temp; - - if (parentIndex == maxIndex) - { - break; - } - parentIndex = maxIndex; - leftChildIndex = 2 * parentIndex + 1; - rightChildIndex = 2 * parentIndex + 2; - } - return ans; - } - - int getSize() - { - return pq.size(); - } - - bool isEmpty() - { - return pq.size() == 0; - } -}; - -int main() -{ - PriorityQueue pq; - int choice; - cin >> choice; - - while (choice != -1) - { - switch (choice) - { - case 1: // insert - int element; - cin >> element; - pq.insert(element); - break; - case 2: // getMax - cout << pq.getMax() << "\n"; - break; - case 3: // removeMax - cout << pq.removeMax() << "\n"; - break; - case 4: // size - cout << pq.getSize() << "\n"; - break; - case 5: // isEmpty - cout << (pq.isEmpty() ? "true\n" : "false\n"); - default: - return 0; - } - - cin >> choice; - } -} \ No newline at end of file diff --git a/Priority Queues/Min_PriorityQueues.cpp b/Priority Queues/Min_PriorityQueues.cpp deleted file mode 100644 index 74168b41..00000000 --- a/Priority Queues/Min_PriorityQueues.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -Explaination : - Implementation of min priority queue -*/ -#include -#include -#include - -using namespace std; - -class priorityQueue -{ - vector pq; - -public: - priorityQueue() - { - } - bool isEmpty() - { - return pq.size() == 0; - } - int getSize() - { - return pq.size(); - } - int getMin() - { - if (isEmpty()) - { - return -1; - } - return pq[0]; - } - - void insert(int data) - { - pq.push_back(data); - int childIndex = pq.size() - 1; - while (childIndex > 0) - { - int parentIndex = (childIndex - 1) / 2; - if (pq[childIndex] < pq[parentIndex]) - { - int temp = pq[childIndex]; - pq[childIndex] = pq[parentIndex]; - pq[parentIndex] = temp; - } - else - { - break; - } - childIndex = parentIndex; - } - } - - int removeMin() - { - if (pq.size() == 0) - { - return -1; - } - int ans = getMin(); - int temp = pq[0]; - pq[0] = pq[pq.size() - 1]; - pq[pq.size() - 1] = temp; - pq.pop_back(); - int parentIndex = 0; - int childIndex1 = 2 * parentIndex + 1; - int childIndex2 = 2 * parentIndex + 2; - while (childIndex1 < pq.size()) - { - int minIndex = parentIndex; - if (pq[minIndex] > pq[childIndex1]) - { - minIndex = childIndex1; - } - if (childIndex2 < pq.size() && pq[minIndex] > pq[childIndex2]) - { - minIndex = childIndex2; - } - swap(pq[parentIndex], pq[minIndex]); - if (minIndex == parentIndex) - { - break; - } - parentIndex = minIndex; - childIndex1 = 2 * parentIndex + 1; - childIndex2 = 2 * parentIndex + 2; - } - return ans; - } -}; - -int main() -{ - priorityQueue p; - p.insert(100); - p.insert(10); - p.insert(15); - p.insert(4); - p.insert(17); - p.insert(21); - p.insert(67); - - cout << p.getSize() << endl; - cout << p.getMin() << endl; - while (!p.isEmpty()) - cout << p.removeMin() << " "; - return 0; -} \ No newline at end of file diff --git a/Priority Queues/BuyTheTicket.cpp b/Priority Queues/buy_the_ticket.cpp similarity index 100% rename from Priority Queues/BuyTheTicket.cpp rename to Priority Queues/buy_the_ticket.cpp diff --git a/Priority Queues/CheckMaxHeap.cpp b/Priority Queues/check_max_heap.cpp similarity index 100% rename from Priority Queues/CheckMaxHeap.cpp rename to Priority Queues/check_max_heap.cpp diff --git a/Priority Queues/KthLargestElement.cpp b/Priority Queues/kth_largest_element.cpp similarity index 100% rename from Priority Queues/KthLargestElement.cpp rename to Priority Queues/kth_largest_element.cpp diff --git a/Priority Queues/KSmallestElement.cpp b/Priority Queues/kth_smallest_element.cpp similarity index 100% rename from Priority Queues/KSmallestElement.cpp rename to Priority Queues/kth_smallest_element.cpp diff --git a/Priority Queues/MergeKSortedArrays.cpp b/Priority Queues/merge_k_sorted_arrays.cpp similarity index 100% rename from Priority Queues/MergeKSortedArrays.cpp rename to Priority Queues/merge_k_sorted_arrays.cpp diff --git a/Priority Queues/RunningMedian.cpp b/Priority Queues/running_median.cpp similarity index 100% rename from Priority Queues/RunningMedian.cpp rename to Priority Queues/running_median.cpp diff --git a/Priority Queues/tempCodeRunnerFile.cpp b/Priority Queues/tempCodeRunnerFile.cpp deleted file mode 100644 index ac7d3036..00000000 --- a/Priority Queues/tempCodeRunnerFile.cpp +++ /dev/null @@ -1,2 +0,0 @@ -6 -6 2 1 3 7 5 \ No newline at end of file From 19e0bb2e80dcb4939ccdb811af5e51535933a207 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 23:01:28 +0530 Subject: [PATCH 1566/1894] rename file to shorter version --- ...of_points_inside_a_circle.js => num_points_inside_a_circle.js} | 0 ...of_points_inside_a_circle.py => num_points_inside_a_circle.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Math/{add_queries_on_number_of_points_inside_a_circle.js => num_points_inside_a_circle.js} (100%) rename Math/{add_queries_on_number_of_points_inside_a_circle.py => num_points_inside_a_circle.py} (100%) diff --git a/Math/add_queries_on_number_of_points_inside_a_circle.js b/Math/num_points_inside_a_circle.js similarity index 100% rename from Math/add_queries_on_number_of_points_inside_a_circle.js rename to Math/num_points_inside_a_circle.js diff --git a/Math/add_queries_on_number_of_points_inside_a_circle.py b/Math/num_points_inside_a_circle.py similarity index 100% rename from Math/add_queries_on_number_of_points_inside_a_circle.py rename to Math/num_points_inside_a_circle.py From 759227a812843e2dc91ede97b2ed0d4b9f7a8b55 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 23:02:32 +0530 Subject: [PATCH 1567/1894] remove duplicate and rename file --- Math/Number of Substrings With Only 1s.js | 83 ----------------------- Math/number_of_substring_with_only_1.js | 50 -------------- 2 files changed, 133 deletions(-) delete mode 100644 Math/Number of Substrings With Only 1s.js delete mode 100644 Math/number_of_substring_with_only_1.js diff --git a/Math/Number of Substrings With Only 1s.js b/Math/Number of Substrings With Only 1s.js deleted file mode 100644 index f5624013..00000000 --- a/Math/Number of Substrings With Only 1s.js +++ /dev/null @@ -1,83 +0,0 @@ -/* - PROBLEM STATEMENT: - - Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. - - EXAMPLE 1: - Input: s = "0110111" - Output: 9 - Explanation: There are 9 substring in total with only 1's characters. - "1" -> 5 times. - "11" -> 3 times. - "111" -> 1 time. - EXAMPLE 2: - Input: s = "101" - Output: 2 - Explanation: Substring "1" is shown 2 times in s. - - CONSTRAINT: - Constraints: - 1 <= s.length <= 105 - s[i] is either '0' or '1'. -*/ - -/* Explaination - - The function begins by initializing two variables - "count" and "answer" - to 0. - "count" will be used to keep track of the current number of consecutive 1's in the string, - while "answer" will eventually store the final answer. - -The constant "mod" is defined to be 10^9+7, which will be used to take modulo of the answer -at each step, in order to prevent overflow. - -The function then iterates through the input string using a for loop. -For each character in the string, it checks if it is a 1 or a 0. If it is a 1, -the "count" variable is incremented by 1. If it is a 0, the "count" variable is reset to 0. - -At each step of the loop, the value of "count" is added to "answer" and then taken modulo "mod". -This is done to count the number of substrings with all 1's and prevent overflow of the result. - -After the loop has finished, the final value of "answer" is returned as the solution to the problem. - - -*/ - - -var numSub = function(s) { - // count stores the current number of consecutive 1's - var count=0; - // answer storese the final answer to be returned - var answer=0; - // we mod the sum at each step so that they don't overflow - const mod=1000000007; - // iterate the entire string - for(let i=0;i Date: Fri, 7 Jul 2023 23:02:40 +0530 Subject: [PATCH 1568/1894] rename --- Math/number_of_substring_with_only_1s.js | 83 ++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Math/number_of_substring_with_only_1s.js diff --git a/Math/number_of_substring_with_only_1s.js b/Math/number_of_substring_with_only_1s.js new file mode 100644 index 00000000..f5624013 --- /dev/null +++ b/Math/number_of_substring_with_only_1s.js @@ -0,0 +1,83 @@ +/* + PROBLEM STATEMENT: + + Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. + + EXAMPLE 1: + Input: s = "0110111" + Output: 9 + Explanation: There are 9 substring in total with only 1's characters. + "1" -> 5 times. + "11" -> 3 times. + "111" -> 1 time. + EXAMPLE 2: + Input: s = "101" + Output: 2 + Explanation: Substring "1" is shown 2 times in s. + + CONSTRAINT: + Constraints: + 1 <= s.length <= 105 + s[i] is either '0' or '1'. +*/ + +/* Explaination + + The function begins by initializing two variables - "count" and "answer" - to 0. + "count" will be used to keep track of the current number of consecutive 1's in the string, + while "answer" will eventually store the final answer. + +The constant "mod" is defined to be 10^9+7, which will be used to take modulo of the answer +at each step, in order to prevent overflow. + +The function then iterates through the input string using a for loop. +For each character in the string, it checks if it is a 1 or a 0. If it is a 1, +the "count" variable is incremented by 1. If it is a 0, the "count" variable is reset to 0. + +At each step of the loop, the value of "count" is added to "answer" and then taken modulo "mod". +This is done to count the number of substrings with all 1's and prevent overflow of the result. + +After the loop has finished, the final value of "answer" is returned as the solution to the problem. + + +*/ + + +var numSub = function(s) { + // count stores the current number of consecutive 1's + var count=0; + // answer storese the final answer to be returned + var answer=0; + // we mod the sum at each step so that they don't overflow + const mod=1000000007; + // iterate the entire string + for(let i=0;i Date: Fri, 7 Jul 2023 23:03:45 +0530 Subject: [PATCH 1569/1894] rename fil --- ...d_Hamming_dis.cpp => hamming_distance.cpp} | 104 +++++++++--------- ...les.cpp => num_points_inside_a_circle.cpp} | 0 ...s => number_of_substrings_with_only_1s.js} | 0 3 files changed, 52 insertions(+), 52 deletions(-) rename Math/{Find_Hamming_dis.cpp => hamming_distance.cpp} (97%) rename Math/{queries_on_number_of_points_inside_a_circles.cpp => num_points_inside_a_circle.cpp} (100%) rename Math/{number_of_substring_with_only_1s.js => number_of_substrings_with_only_1s.js} (100%) diff --git a/Math/Find_Hamming_dis.cpp b/Math/hamming_distance.cpp similarity index 97% rename from Math/Find_Hamming_dis.cpp rename to Math/hamming_distance.cpp index 59e2e943..f19a033d 100644 --- a/Math/Find_Hamming_dis.cpp +++ b/Math/hamming_distance.cpp @@ -1,52 +1,52 @@ -/* -Example: -Input: nums = [4,14,2] -Output: 6 - -Explanation: -In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just -showing the four bits relevant in this case). -The answer will be: -HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. - -Detailed Explanation: -The totalHammingDistance function takes a reference to a vector of integers nums, and returns the total Hamming distance between all possible pairs of elements in the vector. - -In the function, we initialize the answer ans to 0, and the size of the vector n is obtained using the size() method of the vector. We then loop through all 32 bits (since we are dealing with 32-bit integers), and for each bit position i, we count the number of elements in nums with the i-th bit set by looping through all elements and checking if the bit is set using bitwise AND operator &. - -The count c is then multiplied by (n-c), which gives the number of pairs with different bits at the i-th position. This count is added to the answer ans. Finally, the function returns the total Hamming distance. -The main function is just an example usage, where we create a vector nums and call the totalHammingDistance method of a Solution object to get the total Hamming distance between all possible pairs of elements in nums. -*/ -// code: - -#include -#include - -using namespace std; - -class Solution { -public: - int totalHammingDistance(vector& nums) { - int ans = 0; - int n = nums.size(); - for(int i = 0; i < 32; i++) { - int c = 0; - for(int j = 0; j < n; j++) { - if((nums[j] & (1 << i))) { - c++; - } - } - ans += (c * (n - c)); - } - return ans; - } -}; - -int main() { - // Example usage - vector nums = {4, 14, 2}; - Solution s; - int result = s.totalHammingDistance(nums); - return 0; -} - +/* +Example: +Input: nums = [4,14,2] +Output: 6 + +Explanation: +In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just +showing the four bits relevant in this case). +The answer will be: +HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. + +Detailed Explanation: +The totalHammingDistance function takes a reference to a vector of integers nums, and returns the total Hamming distance between all possible pairs of elements in the vector. + +In the function, we initialize the answer ans to 0, and the size of the vector n is obtained using the size() method of the vector. We then loop through all 32 bits (since we are dealing with 32-bit integers), and for each bit position i, we count the number of elements in nums with the i-th bit set by looping through all elements and checking if the bit is set using bitwise AND operator &. + +The count c is then multiplied by (n-c), which gives the number of pairs with different bits at the i-th position. This count is added to the answer ans. Finally, the function returns the total Hamming distance. +The main function is just an example usage, where we create a vector nums and call the totalHammingDistance method of a Solution object to get the total Hamming distance between all possible pairs of elements in nums. +*/ +// code: + +#include +#include + +using namespace std; + +class Solution { +public: + int totalHammingDistance(vector& nums) { + int ans = 0; + int n = nums.size(); + for(int i = 0; i < 32; i++) { + int c = 0; + for(int j = 0; j < n; j++) { + if((nums[j] & (1 << i))) { + c++; + } + } + ans += (c * (n - c)); + } + return ans; + } +}; + +int main() { + // Example usage + vector nums = {4, 14, 2}; + Solution s; + int result = s.totalHammingDistance(nums); + return 0; +} + diff --git a/Math/queries_on_number_of_points_inside_a_circles.cpp b/Math/num_points_inside_a_circle.cpp similarity index 100% rename from Math/queries_on_number_of_points_inside_a_circles.cpp rename to Math/num_points_inside_a_circle.cpp diff --git a/Math/number_of_substring_with_only_1s.js b/Math/number_of_substrings_with_only_1s.js similarity index 100% rename from Math/number_of_substring_with_only_1s.js rename to Math/number_of_substrings_with_only_1s.js From ff9fd76820239dbdc9cb32acf917773e3e22ba9f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 23:04:13 +0530 Subject: [PATCH 1570/1894] rename file --- Math/{Uniquedigits.cpp => unique_digits.cpp} | 0 Math/{Uniquedigits.java => unique_digits.java} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Math/{Uniquedigits.cpp => unique_digits.cpp} (100%) rename Math/{Uniquedigits.java => unique_digits.java} (100%) diff --git a/Math/Uniquedigits.cpp b/Math/unique_digits.cpp similarity index 100% rename from Math/Uniquedigits.cpp rename to Math/unique_digits.cpp diff --git a/Math/Uniquedigits.java b/Math/unique_digits.java similarity index 100% rename from Math/Uniquedigits.java rename to Math/unique_digits.java From d655095fe03bf548101170791170847c399cb60e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 7 Jul 2023 23:05:05 +0530 Subject: [PATCH 1571/1894] rename file --- Patterns/{NumericalPattern.java => numerical_pattern.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Patterns/{NumericalPattern.java => numerical_pattern.java} (100%) diff --git a/Patterns/NumericalPattern.java b/Patterns/numerical_pattern.java similarity index 100% rename from Patterns/NumericalPattern.java rename to Patterns/numerical_pattern.java From 984284c73009dd2237f6c5874d6dea0ac5af2670 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 8 Jul 2023 16:07:28 +0530 Subject: [PATCH 1572/1894] Partition_string.py closes #1432 --- Hash Table/Partition_string.py | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Hash Table/Partition_string.py diff --git a/Hash Table/Partition_string.py b/Hash Table/Partition_string.py new file mode 100644 index 00000000..120bc12f --- /dev/null +++ b/Hash Table/Partition_string.py @@ -0,0 +1,39 @@ +def is_palindrome(s): + return s == s[::-1] + +def min_partition(s): + n = len(s) + + # Create a hash table to store the results of subproblems + # dp[i] represents the minimum number of partitions in s[0:i] + dp = [float('inf')] * (n + 1) + dp[0] = 0 + + # Iterate through the string + for i in range(1, n + 1): + # Check all possible substrings s[j:i] + for j in range(i): + # If s[j:i] is a palindrome, update the minimum number of partitions + if is_palindrome(s[j:i]): + dp[i] = min(dp[i], dp[j] + 1) + + # Return the minimum number of partitions for the entire string + return dp[n] - 1 + +# Example usage +string = "aabba" +optimal_partitions = min_partition(string) +print("Optimal number of partitions:", optimal_partitions) + + +''' +The min_partition function utilizes dynamic programming to find the minimum number of partitions in the given string s. It iterates through each character in the string and checks all possible substrings. If a substring is a palindrome, it updates the minimum number of partitions accordingly. + +Note that the dp list is initialized with float('inf') values, except for the first element dp[0], which is set to 0. The final result subtracts 1 from dp[n] to account for the fact that the last character does not require a partition. + + + +The time complexity of the given solution is O(n^3), where n is the length of the input string s. This is because there are two nested loops, and for each combination of i and j, the is_palindrome function is called, which has a time complexity of O(n). Hence, the overall time complexity is O(n^3). + +The space complexity of the solution is O(n), where n is the length of the input string s. This is because the dp list, used to store the minimum number of partitions for each substring, has a length of n + 1. Therefore, the space required is linearly proportional to the length of the input string. +''' From f8750e7e08bfed3f9804bf287e0e7f5c21e26b4f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:07:52 +0530 Subject: [PATCH 1573/1894] add powerset in go --- Recursion/powerset.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Recursion/powerset.go diff --git a/Recursion/powerset.go b/Recursion/powerset.go new file mode 100644 index 00000000..9779aa07 --- /dev/null +++ b/Recursion/powerset.go @@ -0,0 +1,34 @@ + +package main + +func Powerset(array []int) [][]int { + // Call the powerset helper function to compute the powerset of the array + return powerset(array, len(array)-1) +} + +func powerset(array []int, index int) [][]int { + // Base case: If the index is less than 0, all elements have been processed, return the empty set + if index < 0 { + return [][]int{{}} + } + + // Retrieve the element at the current index + element := array[index] + + // Recursively call the powerset function with the array and the index decremented by 1 + subset := powerset(array, index-1) + + // Calculate the length of the current subset + length := len(subset) + + // Iterate over the existing subsets and create new subsets by appending the current element + for i := 0; i < length; i++ { + currentSubset := subset[i] + newSubset := append([]int{}, currentSubset...) // Create a new subset by making a copy of the current subset + newSubset = append(newSubset, element) // Append the current element to the new subset + subset = append(subset, newSubset) // Add the new subset to the existing subset slice + } + + // Return the updated subset slice containing all the subsets of the original array + return subset +} From 7ee64ee14668a5e8b42b1e4f5150d369994d4bbb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:09:46 +0530 Subject: [PATCH 1574/1894] add time and space complexity --- Recursion/powerset.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Recursion/powerset.go b/Recursion/powerset.go index 9779aa07..a1b5502c 100644 --- a/Recursion/powerset.go +++ b/Recursion/powerset.go @@ -1,3 +1,43 @@ +/* + + Write a function that takes in an array of unique integers and returns its powerset. + + Sample Input : [1, 2, 3] + Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + + Explanation: + + The code snippet represents a function `Powerset` that takes an array of integers as input and returns the powerset + of the array. The powerset of a set is the set of all possible subsets of that set, including the empty set and the set itself. + + The function `Powerset` calls a helper function `powerset` to perform the actual computation. Here's how the code works: + + 1. The `Powerset` function initializes the computation by calling the `powerset` function with the array and the index + of the last element in the array (`len(array) - 1`). + + 2. The `powerset` function is a recursive function that calculates the powerset. It takes the array and the current + index as input. + + 3. At each recursive call, the function checks if the index is less than 0. If so, it means all elements have been + processed, and it returns a 2D slice containing the empty set as the only subset. + + 4. If the index is not less than 0, the function retrieves the element at the current index from the array. + + 5. The function recursively calls itself with the array and the index decremented by 1 to generate the subsets without + the current element. + + 6. It then calculates the length of the subsets generated so far. + + 7. Using a loop, the function iterates over the existing subsets and creates new subsets by appending the current element + to each subset. The new subsets are added to the existing subset slice. + + 8. Finally, the function returns the updated subset slice, which contains all the subsets of the original array. + + By recursively generating subsets while building upon the subsets generated at each step, the function constructs the + powerset of the given array. + + O(n*2^n) time | O(n*2^n) space - where n is the length of the input array +*/ package main From 2013faea284fded8d7258632899d7e541445c790 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:10:54 +0530 Subject: [PATCH 1575/1894] add powerset in python --- Recursion/powerset.py | 68 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Recursion/powerset.py diff --git a/Recursion/powerset.py b/Recursion/powerset.py new file mode 100644 index 00000000..2e0bd60a --- /dev/null +++ b/Recursion/powerset.py @@ -0,0 +1,68 @@ +''' + + Write a function that takes in an array of unique integers and returns its powerset. + + Sample Input : [1, 2, 3] + Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + + Explanation: + + The code snippet represents a function `Powerset` that takes an array of integers as input and returns the powerset + of the array. The powerset of a set is the set of all possible subsets of that set, including the empty set and the set itself. + + The function `Powerset` calls a helper function `powerset` to perform the actual computation. Here's how the code works: + + 1. The `Powerset` function initializes the computation by calling the `powerset` function with the array and the index + of the last element in the array (`len(array) - 1`). + + 2. The `powerset` function is a recursive function that calculates the powerset. It takes the array and the current + index as input. + + 3. At each recursive call, the function checks if the index is less than 0. If so, it means all elements have been + processed, and it returns a 2D slice containing the empty set as the only subset. + + 4. If the index is not less than 0, the function retrieves the element at the current index from the array. + + 5. The function recursively calls itself with the array and the index decremented by 1 to generate the subsets without + the current element. + + 6. It then calculates the length of the subsets generated so far. + + 7. Using a loop, the function iterates over the existing subsets and creates new subsets by appending the current element + to each subset. The new subsets are added to the existing subset slice. + + 8. Finally, the function returns the updated subset slice, which contains all the subsets of the original array. + + By recursively generating subsets while building upon the subsets generated at each step, the function constructs the + powerset of the given array. + + O(n*2^n) time | O(n*2^n) space - where n is the length of the input array +''' +def powerset(array): + # Base case: when the index reaches -1, return a list with an empty subset + if index < 0: + return [[]] + + element = array[index] + # Recursive call to generate the powerset for the elements up to index - 1 + subset = powerset(array, index - 1) + + # Length of the current subset list + length = len(subset) + + # Iterate through each subset and create new subsets by adding the current element + for i in range(length): + currentSubset = subset[i] + # Create a new subset by making a copy of the current subset + newSubset = currentSubset[:] + # Add the current element to the new subset + newSubset.append(element) + # Add the new subset to the existing subset list + subset.append(newSubset) + + # Return the resulting subset list + return subset + +def Powerset(array): + # Call the helper function to generate the powerset starting from the last index + return powerset(array, len(array) - 1) From 4242717d5bc53b91c646940b7f07c4e30f69ea20 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:11:48 +0530 Subject: [PATCH 1576/1894] add powerset in c++ --- Recursion/powerset.cpp | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Recursion/powerset.cpp diff --git a/Recursion/powerset.cpp b/Recursion/powerset.cpp new file mode 100644 index 00000000..71d1d6b0 --- /dev/null +++ b/Recursion/powerset.cpp @@ -0,0 +1,76 @@ +/* + + Write a function that takes in an array of unique integers and returns its powerset. + + Sample Input : [1, 2, 3] + Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + + Explanation: + + The code snippet represents a function `Powerset` that takes an array of integers as input and returns the powerset + of the array. The powerset of a set is the set of all possible subsets of that set, including the empty set and the set itself. + + The function `Powerset` calls a helper function `powerset` to perform the actual computation. Here's how the code works: + + 1. The `Powerset` function initializes the computation by calling the `powerset` function with the array and the index + of the last element in the array (`len(array) - 1`). + + 2. The `powerset` function is a recursive function that calculates the powerset. It takes the array and the current + index as input. + + 3. At each recursive call, the function checks if the index is less than 0. If so, it means all elements have been + processed, and it returns a 2D slice containing the empty set as the only subset. + + 4. If the index is not less than 0, the function retrieves the element at the current index from the array. + + 5. The function recursively calls itself with the array and the index decremented by 1 to generate the subsets without + the current element. + + 6. It then calculates the length of the subsets generated so far. + + 7. Using a loop, the function iterates over the existing subsets and creates new subsets by appending the current element + to each subset. The new subsets are added to the existing subset slice. + + 8. Finally, the function returns the updated subset slice, which contains all the subsets of the original array. + + By recursively generating subsets while building upon the subsets generated at each step, the function constructs the + powerset of the given array. + + O(n*2^n) time | O(n*2^n) space - where n is the length of the input array +*/ +#include + +using namespace std; + +vector> powerset(vector& array, int index) { + // Base case: when the index reaches -1, return a vector with an empty subset + if (index < 0) { + return {{}}; + } + + int element = array[index]; + // Recursive call to generate the powerset for the elements up to index - 1 + vector> subset = powerset(array, index - 1); + + // Length of the current subset vector + int length = subset.size(); + + // Iterate through each subset and create new subsets by adding the current element + for (int i = 0; i < length; i++) { + vector currentSubset = subset[i]; + // Create a new subset by making a copy of the current subset + vector newSubset = currentSubset; + // Add the current element to the new subset + newSubset.push_back(element); + // Add the new subset to the existing subset vector + subset.push_back(newSubset); + } + + // Return the resulting subset vector + return subset; +} + +vector> Powerset(vector& array) { + // Call the helper function to generate the powerset starting from the last index + return powerset(array, array.size() - 1); +} From f05accae39f845060d1b6e63fc6a5159178df8e0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:15:07 +0530 Subject: [PATCH 1577/1894] add powerset in java --- Recursion/powerset.java | 90 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Recursion/powerset.java diff --git a/Recursion/powerset.java b/Recursion/powerset.java new file mode 100644 index 00000000..70a5e6e9 --- /dev/null +++ b/Recursion/powerset.java @@ -0,0 +1,90 @@ +/* + + Write a function that takes in an array of unique integers and returns its powerset. + + Sample Input : [1, 2, 3] + Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + + Explanation: + + The code snippet represents a function `Powerset` that takes an array of integers as input and returns the powerset + of the array. The powerset of a set is the set of all possible subsets of that set, including the empty set and the set itself. + + The function `Powerset` calls a helper function `powerset` to perform the actual computation. Here's how the code works: + + 1. The `Powerset` function initializes the computation by calling the `powerset` function with the array and the index + of the last element in the array (`len(array) - 1`). + + 2. The `powerset` function is a recursive function that calculates the powerset. It takes the array and the current + index as input. + + 3. At each recursive call, the function checks if the index is less than 0. If so, it means all elements have been + processed, and it returns a 2D slice containing the empty set as the only subset. + + 4. If the index is not less than 0, the function retrieves the element at the current index from the array. + + 5. The function recursively calls itself with the array and the index decremented by 1 to generate the subsets without + the current element. + + 6. It then calculates the length of the subsets generated so far. + + 7. Using a loop, the function iterates over the existing subsets and creates new subsets by appending the current element + to each subset. The new subsets are added to the existing subset slice. + + 8. Finally, the function returns the updated subset slice, which contains all the subsets of the original array. + + By recursively generating subsets while building upon the subsets generated at each step, the function constructs the + powerset of the given array. + + O(n*2^n) time | O(n*2^n) space - where n is the length of the input array +*/ +import java.util.ArrayList; +import java.util.List; + +class Main { + + public static List> powerset(int[] array, int index) { + // Base case: when the index reaches -1, return a list with an empty subset + if (index < 0) { + List> subsets = new ArrayList<>(); + subsets.add(new ArrayList<>()); + return subsets; + } + + int element = array[index]; + // Recursive call to generate the powerset for the elements up to index - 1 + List> subsets = powerset(array, index - 1); + + // Length of the current subsets list + int length = subsets.size(); + + // Iterate through each subset and create new subsets by adding the current element + for (int i = 0; i < length; i++) { + List currentSubset = subsets.get(i); + // Create a new subset by making a copy of the current subset + List newSubset = new ArrayList<>(currentSubset); + // Add the current element to the new subset + newSubset.add(element); + // Add the new subset to the existing subsets list + subsets.add(newSubset); + } + + // Return the resulting subsets list + return subsets; + } + + public static List> powerset(int[] array) { + // Call the helper function to generate the powerset starting from the last index + return powerset(array, array.length - 1); + } + + public static void main(String[] args) { + int[] array = {1, 2, 3}; + List> subsets = powerset(array); + + // Print the subsets + for (List subset : subsets) { + System.out.println(subset); + } + } +} From 0c0d79b394d50d3d1f877feb99e4c877d61b933a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:16:27 +0530 Subject: [PATCH 1578/1894] add powerset in js --- Recursion/powerset.js | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Recursion/powerset.js diff --git a/Recursion/powerset.js b/Recursion/powerset.js new file mode 100644 index 00000000..50bf87aa --- /dev/null +++ b/Recursion/powerset.js @@ -0,0 +1,79 @@ +/* + + Write a function that takes in an array of unique integers and returns its powerset. + + Sample Input : [1, 2, 3] + Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] + + Explanation: + + The code snippet represents a function `Powerset` that takes an array of integers as input and returns the powerset + of the array. The powerset of a set is the set of all possible subsets of that set, including the empty set and the set itself. + + The function `Powerset` calls a helper function `powerset` to perform the actual computation. Here's how the code works: + + 1. The `Powerset` function initializes the computation by calling the `powerset` function with the array and the index + of the last element in the array (`len(array) - 1`). + + 2. The `powerset` function is a recursive function that calculates the powerset. It takes the array and the current + index as input. + + 3. At each recursive call, the function checks if the index is less than 0. If so, it means all elements have been + processed, and it returns a 2D slice containing the empty set as the only subset. + + 4. If the index is not less than 0, the function retrieves the element at the current index from the array. + + 5. The function recursively calls itself with the array and the index decremented by 1 to generate the subsets without + the current element. + + 6. It then calculates the length of the subsets generated so far. + + 7. Using a loop, the function iterates over the existing subsets and creates new subsets by appending the current element + to each subset. The new subsets are added to the existing subset slice. + + 8. Finally, the function returns the updated subset slice, which contains all the subsets of the original array. + + By recursively generating subsets while building upon the subsets generated at each step, the function constructs the + powerset of the given array. + + O(n*2^n) time | O(n*2^n) space - where n is the length of the input array +*/ +function powerset(array, index) { + // Base case: when the index reaches -1, return a list with an empty subset + if (index < 0) { + return [[]]; + } + + const element = array[index]; + // Recursive call to generate the powerset for the elements up to index - 1 + const subsets = powerset(array, index - 1); + + // Create new subsets by adding the current element to existing subsets + const length = subsets.length; + for (let i = 0; i < length; i++) { + const currentSubset = subsets[i]; + // Create a new subset by making a copy of the current subset + const newSubset = [...currentSubset]; + // Add the current element to the new subset + newSubset.push(element); + // Add the new subset to the existing subsets array + subsets.push(newSubset); + } + + // Return the resulting subsets array + return subsets; +} + +function getPowerSet(array) { + // Call the helper function to generate the powerset starting from the last index + return powerset(array, array.length - 1); +} + +// Example usage +const array = [1, 2, 3]; +const subsets = getPowerSet(array); + +// Print the subsets +subsets.forEach((subset) => { + console.log(subset); +}); From 72029f339aad1db07b4128f427a9f378c18e90fa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:26:25 +0530 Subject: [PATCH 1579/1894] add iterative approach --- Recursion/powerset.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Recursion/powerset.cpp b/Recursion/powerset.cpp index 71d1d6b0..08de5b64 100644 --- a/Recursion/powerset.cpp +++ b/Recursion/powerset.cpp @@ -74,3 +74,31 @@ vector> Powerset(vector& array) { // Call the helper function to generate the powerset starting from the last index return powerset(array, array.size() - 1); } + +// Iterative approach +vector> powerset(vector& array) { + vector> subset; + subset.push_back({}); // Initialize the powerset with the empty subset + + // Iterate over each element in the input array + for (int ele : array) { + int length = subset.size(); // Get the current length of the subset + + // Iterate over each existing subset + for (int i = 0; i < length; i++) { + vector currentSubset = subset[i]; // Get the current subset + + // Create a new subset by making a copy of the current subset + vector newSubset = currentSubset; + + // Add the current element to the new subset + newSubset.push_back(ele); + + // Append the new subset to the powerset + subset.push_back(newSubset); + } + } + + // Return the powerset + return subset; +} \ No newline at end of file From 1a673d7b27f58a5cc17637cdf829beca11febf1b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:26:28 +0530 Subject: [PATCH 1580/1894] add iterative approach --- Recursion/powerset.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Recursion/powerset.go b/Recursion/powerset.go index a1b5502c..a9a5a4f8 100644 --- a/Recursion/powerset.go +++ b/Recursion/powerset.go @@ -72,3 +72,34 @@ func powerset(array []int, index int) [][]int { // Return the updated subset slice containing all the subsets of the original array return subset } + +// Iterative approach + +func PowersetIterative(array []int) [][]int { + // Initialize the powerset with the empty subset + subset := [][]int{{}} + + // Iterate over each element in the input array + for _, ele := range array { + // Get the current length of the subset + length := len(subset) + + // Iterate over each existing subset + for i := 0; i < length; i++ { + // Get the current subset + currentSubset := subset[i] + + // Create a new subset by making a copy of the current subset + newSubset := append([]int{}, currentSubset...) + + // Add the current element to the new subset + newSubset = append(newSubset, ele) + + // Append the new subset to the powerset + subset = append(subset, newSubset) + } + } + + // Return the powerset + return subset +} From 731c735e38158cd57da9a8946f956f9dc199e57b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:26:30 +0530 Subject: [PATCH 1581/1894] add iterative approach --- Recursion/powerset.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Recursion/powerset.java b/Recursion/powerset.java index 70a5e6e9..1c93b214 100644 --- a/Recursion/powerset.java +++ b/Recursion/powerset.java @@ -88,3 +88,40 @@ public static void main(String[] args) { } } } + + +// Iterative approach +public class Powerset { + public static List> powerset(int[] array) { + List> subset = new ArrayList<>(); + subset.add(new ArrayList<>()); // Initialize the powerset with the empty subset + + // Iterate over each element in the input array + for (int ele : array) { + int length = subset.size(); // Get the current length of the subset + + // Iterate over each existing subset + for (int i = 0; i < length; i++) { + List currentSubset = new ArrayList<>(subset.get(i)); // Get the current subset + + // Create a new subset by making a copy of the current subset + List newSubset = new ArrayList<>(currentSubset); + + // Add the current element to the new subset + newSubset.add(ele); + + // Append the new subset to the powerset + subset.add(newSubset); + } + } + + // Return the powerset + return subset; + } + + public static void main(String[] args) { + int[] array = {1, 2, 3}; + List> result = powerset(array); + System.out.println(result); + } +} \ No newline at end of file From 47dda386785b3e354cd9fd2389e2d59bd846bc7d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:26:33 +0530 Subject: [PATCH 1582/1894] add iterative approach --- Recursion/powerset.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Recursion/powerset.js b/Recursion/powerset.js index 50bf87aa..7bfff2a8 100644 --- a/Recursion/powerset.js +++ b/Recursion/powerset.js @@ -77,3 +77,33 @@ const subsets = getPowerSet(array); subsets.forEach((subset) => { console.log(subset); }); + +// Iterative approach +function powersetIterative(array) { + // Initialize the powerset with the empty subset + let subset = [[]]; + + // Iterate over each element in the input array + for (let ele of array) { + // Get the current length of the subset + let length = subset.length; + + // Iterate over each existing subset + for (let i = 0; i < length; i++) { + // Get the current subset + let currentSubset = subset[i]; + + // Create a new subset by making a copy of the current subset + let newSubset = [...currentSubset]; + + // Add the current element to the new subset + newSubset.push(ele); + + // Append the new subset to the powerset + subset.push(newSubset); + } + } + + // Return the powerset + return subset; +} From 7db115d58fc4273c0ce12a62726f7cf1ec67f16c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 8 Jul 2023 23:26:36 +0530 Subject: [PATCH 1583/1894] add iterative approach --- Recursion/powerset.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Recursion/powerset.py b/Recursion/powerset.py index 2e0bd60a..7a3a8939 100644 --- a/Recursion/powerset.py +++ b/Recursion/powerset.py @@ -66,3 +66,31 @@ def powerset(array): def Powerset(array): # Call the helper function to generate the powerset starting from the last index return powerset(array, len(array) - 1) + + +# Iterative approach +def powersetIterative(array): + # Initialize the powerset with the empty subset + subset = [[]] + + # Iterate over each element in the input array + for ele in array: + # Get the current length of the subset + length = len(subset) + + # Iterate over each existing subset + for i in range(length): + # Get the current subset + currentSubset = subset[i] + + # Create a new subset by making a copy of the current subset + newSubset = list(currentSubset) + + # Add the current element to the new subset + newSubset.append(ele) + + # Append the new subset to the powerset + subset.append(newSubset) + + # Return the powerset + return subset From 25b2b68c58553826edfc31282015cb45626efafb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:13:33 +0530 Subject: [PATCH 1584/1894] add task assignment in go --- Greedy/task_assignment.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Greedy/task_assignment.go diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go new file mode 100644 index 00000000..e69de29b From 52910a3ed9a6946c816d15ad058467f8c44b642a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:13:56 +0530 Subject: [PATCH 1585/1894] add task assignment in go --- Greedy/task_assignment.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index e69de29b..49017677 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -0,0 +1,36 @@ +package main + +import "sort" +func TaskAssignment(k int, tasks []int) [][]int { + pairedTasks := make([][]int, 0) + taskDurationToIndices := getTaskDurationToIndices(tasks) + sort.Ints(tasks) + + var task1Idx, task2Idx int + for idx := 0; idx < k; idx++ { + task1Duration := tasks[idx] + indicesWithTask1Duration := taskDurationToIndices[task1Duration] + task1Idx , taskDurationToIndices[task1Duration] = + indicesWithTask1Duration[len(indicesWithTask1Duration) - 1], + indicesWithTask1Duration[:len(indicesWithTask1Duration) - 1] + + task2SortedIndex := len(tasks) - 1 - idx + task2Duration := tasks[task2SortedIndex] + indicesWithTask2Duration := taskDurationToIndices[task2Duration] + task2Idx, taskDurationToIndices[task2Duration] = + indicesWithTask2Duration[len(indicesWithTask2Duration) - 1], + indicesWithTask2Duration[:len(indicesWithTask2Duration) - 1] + pairedTasks = append(pairedTasks, []int{task1Idx, task2Idx}) + } + return pairedTasks +} + +func getTaskDurationToIndices(tasks []int) map[int][]int { + taskDurationToIndices := map[int][]int{} + + for idx := range tasks { + taskDuration := tasks[idx] + taskDurationToIndices[taskDuration] = append(taskDurationToIndices[taskDuration], idx) + } + return taskDurationToIndices +} \ No newline at end of file From 74133fe2e83e1d2f0c0a2edd51c54f8b4032e8eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:14:11 +0530 Subject: [PATCH 1586/1894] add comments --- Greedy/task_assignment.go | 67 +++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index 49017677..6e2449c2 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -1,36 +1,43 @@ -package main - import "sort" + +// TaskAssignment pairs tasks from the given list based on their durations. +// It returns a list of paired task indices. func TaskAssignment(k int, tasks []int) [][]int { + // Initialize variables pairedTasks := make([][]int, 0) - taskDurationToIndices := getTaskDurationToIndices(tasks) - sort.Ints(tasks) - - var task1Idx, task2Idx int - for idx := 0; idx < k; idx++ { - task1Duration := tasks[idx] - indicesWithTask1Duration := taskDurationToIndices[task1Duration] - task1Idx , taskDurationToIndices[task1Duration] = - indicesWithTask1Duration[len(indicesWithTask1Duration) - 1], - indicesWithTask1Duration[:len(indicesWithTask1Duration) - 1] - - task2SortedIndex := len(tasks) - 1 - idx - task2Duration := tasks[task2SortedIndex] - indicesWithTask2Duration := taskDurationToIndices[task2Duration] - task2Idx, taskDurationToIndices[task2Duration] = - indicesWithTask2Duration[len(indicesWithTask2Duration) - 1], - indicesWithTask2Duration[:len(indicesWithTask2Duration) - 1] - pairedTasks = append(pairedTasks, []int{task1Idx, task2Idx}) - } - return pairedTasks + taskDurationToIndices := getTaskDurationToIndices(tasks) + sort.Ints(tasks) + var task1Idx, task2Idx int + + // Pair tasks + for idx := 0; idx < k; idx++ { + // Get the shortest duration task + task1Duration := tasks[idx] + indicesWithTask1Duration := taskDurationToIndices[task1Duration] + task1Idx, taskDurationToIndices[task1Duration] = indicesWithTask1Duration[len(indicesWithTask1Duration)-1], indicesWithTask1Duration[:len(indicesWithTask1Duration)-1] + + // Get the longest duration task + task2SortedIndex := len(tasks) - 1 - idx + task2Duration := tasks[task2SortedIndex] + indicesWithTask2Duration := taskDurationToIndices[task2Duration] + task2Idx, taskDurationToIndices[task2Duration] = indicesWithTask2Duration[len(indicesWithTask2Duration)-1], indicesWithTask2Duration[:len(indicesWithTask2Duration)-1] + + // Add the paired tasks to the result + pairedTasks = append(pairedTasks, []int{task1Idx, task2Idx}) + } + + return pairedTasks } +// getTaskDurationToIndices creates a map that maps each task duration to a list of indices +// where tasks with that duration occur in the given tasks list. func getTaskDurationToIndices(tasks []int) map[int][]int { - taskDurationToIndices := map[int][]int{} - - for idx := range tasks { - taskDuration := tasks[idx] - taskDurationToIndices[taskDuration] = append(taskDurationToIndices[taskDuration], idx) - } - return taskDurationToIndices -} \ No newline at end of file + taskDurationToIndices := map[int][]int{} + + for idx := range tasks { + taskDuration := tasks[idx] + taskDurationToIndices[taskDuration] = append(taskDurationToIndices[taskDuration], idx) + } + + return taskDurationToIndices +} From cbdb4302931f8150c55716186845eb113f1d7dd4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:15:21 +0530 Subject: [PATCH 1587/1894] add explanation --- Greedy/task_assignment.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index 6e2449c2..31d80c44 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -1,3 +1,28 @@ +/* + Explanation: + The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. + + - The function `TaskAssignment` takes two parameters: `k` (the number of workers) and `tasks` (a list of task durations). + - It initializes variables for `pairedTasks`, which will store the paired tasks, and `taskDurationToIndices`, which is + a map that will store the indices of each task duration. + - The `getTaskDurationToIndices` function is called to create the map `taskDurationToIndices`, which maps each task + duration to a list of indices. + - The task durations are sorted in ascending order using `sort.Ints(tasks)`. This allows us to pair the shortest and + longest durations together efficiently. + - The loop runs `k` times to pair tasks. In each iteration: + - The shortest duration task is selected and its index is retrieved from `taskDurationToIndices`. + - The index of the selected task is removed from the list of indices to ensure it is not paired again. + - The longest duration task is selected in a similar manner, but from the opposite end of the sorted task durations. + - The paired task indices are added to `pairedTasks`. + - Finally, `pairedTasks` is returned as the result. + + + The `getTaskDurationToIndices` function is a helper function that creates a map `taskDurationToIndices`, which maps each + task duration to a list of indices where tasks with that duration occur in the `tasks` list. + + Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. + The result is a list of paired task indices. +*/ import "sort" // TaskAssignment pairs tasks from the given list based on their durations. From 18b9fc3ea9f3e0793b67449aae6bba481e003df0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:15:46 +0530 Subject: [PATCH 1588/1894] add time and space --- Greedy/task_assignment.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index 31d80c44..bf9cc929 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -22,6 +22,8 @@ Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. The result is a list of paired task indices. + + O(nlog(n)) time | O(n) space - where n is the number of tasks */ import "sort" From 512ead9c39de5935515f01950638f6a425f2f99b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:18:00 +0530 Subject: [PATCH 1589/1894] add question --- Greedy/task_assignment.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index bf9cc929..6b2e6285 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -1,4 +1,19 @@ /* + + You're given an integer k representing a number of workers and an array of positive integers representing durations of + tasks that must be completed by the workers. Specifically, each worker must complete two unique tasks and can only work + on one task at a time. The number of tasks will always be equal to 2k such that each worker always has exactly two tasks + to complete. All tasks are independent of one another and can be completed in any order. Workers will complete their + assigned tasks in parallel, and the time taken to complete all tasks will be equal to the time taken to complete + the longest pair of tasks (see the sample output for an explanation). + + + Write a function that returns the optimal assignment of tasks to each worker such that the tasks are completed as fast + as possible. Your function should return a list of pairs, where each pair stores the indices of the tasks that should + be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and + task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any + correct answer will be accepted. + Explanation: The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. From df074b79d7202b1d9a78f2533677a2c67a93b89f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:19:04 +0530 Subject: [PATCH 1590/1894] add sample io --- Greedy/task_assignment.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Greedy/task_assignment.go b/Greedy/task_assignment.go index 6b2e6285..1270ab1c 100644 --- a/Greedy/task_assignment.go +++ b/Greedy/task_assignment.go @@ -13,7 +13,16 @@ be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any correct answer will be accepted. - + + Sample Input: K = 3 + tasks : [1, 3, 5, 3, 1, 4] + + Output: [ + [0, 2], + [4, 5], + [1, 3] + ] + Explanation: The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. From bd17e98e140d5ba275c6e456f1ed3014cf51d66f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:22:32 +0530 Subject: [PATCH 1591/1894] add task assignment in c++ --- Greedy/task_assignment.cpp | 100 +++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Greedy/task_assignment.cpp diff --git a/Greedy/task_assignment.cpp b/Greedy/task_assignment.cpp new file mode 100644 index 00000000..8a436ebb --- /dev/null +++ b/Greedy/task_assignment.cpp @@ -0,0 +1,100 @@ +/* + + You're given an integer k representing a number of workers and an array of positive integers representing durations of + tasks that must be completed by the workers. Specifically, each worker must complete two unique tasks and can only work + on one task at a time. The number of tasks will always be equal to 2k such that each worker always has exactly two tasks + to complete. All tasks are independent of one another and can be completed in any order. Workers will complete their + assigned tasks in parallel, and the time taken to complete all tasks will be equal to the time taken to complete + the longest pair of tasks (see the sample output for an explanation). + + + Write a function that returns the optimal assignment of tasks to each worker such that the tasks are completed as fast + as possible. Your function should return a list of pairs, where each pair stores the indices of the tasks that should + be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and + task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any + correct answer will be accepted. + + Sample Input: K = 3 + tasks : [1, 3, 5, 3, 1, 4] + + Output: [ + [0, 2], + [4, 5], + [1, 3] + ] + + Explanation: + The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. + + - The function `TaskAssignment` takes two parameters: `k` (the number of workers) and `tasks` (a list of task durations). + - It initializes variables for `pairedTasks`, which will store the paired tasks, and `taskDurationToIndices`, which is + a map that will store the indices of each task duration. + - The `getTaskDurationToIndices` function is called to create the map `taskDurationToIndices`, which maps each task + duration to a list of indices. + - The task durations are sorted in ascending order using `sort.Ints(tasks)`. This allows us to pair the shortest and + longest durations together efficiently. + - The loop runs `k` times to pair tasks. In each iteration: + - The shortest duration task is selected and its index is retrieved from `taskDurationToIndices`. + - The index of the selected task is removed from the list of indices to ensure it is not paired again. + - The longest duration task is selected in a similar manner, but from the opposite end of the sorted task durations. + - The paired task indices are added to `pairedTasks`. + - Finally, `pairedTasks` is returned as the result. + + + The `getTaskDurationToIndices` function is a helper function that creates a map `taskDurationToIndices`, which maps each + task duration to a list of indices where tasks with that duration occur in the `tasks` list. + + Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. + The result is a list of paired task indices. + + O(nlog(n)) time | O(n) space - where n is the number of tasks +*/ +#include +#include +#include + +using namespace std; + +// Function to create a map that maps each task duration to a list of indices +// where tasks with that duration occur in the given tasks list. +unordered_map> getTaskDurationToIndices(vector& tasks) { + unordered_map> taskDurationToIndices; + + for (int idx = 0; idx < tasks.size(); idx++) { + int taskDuration = tasks[idx]; + taskDurationToIndices[taskDuration].push_back(idx); + } + + return taskDurationToIndices; +} + +// Function to pair tasks from the given list based on their durations. +// It returns a vector of paired task indices. +vector> TaskAssignment(int k, vector& tasks) { + // Initialize variables + vector> pairedTasks; + unordered_map> taskDurationToIndices = getTaskDurationToIndices(tasks); + sort(tasks.begin(), tasks.end()); + int task1Idx, task2Idx; + + // Pair tasks + for (int idx = 0; idx < k; idx++) { + // Get the shortest duration task + int task1Duration = tasks[idx]; + vector& indicesWithTask1Duration = taskDurationToIndices[task1Duration]; + task1Idx = indicesWithTask1Duration.back(); + indicesWithTask1Duration.pop_back(); + + // Get the longest duration task + int task2SortedIndex = tasks.size() - 1 - idx; + int task2Duration = tasks[task2SortedIndex]; + vector& indicesWithTask2Duration = taskDurationToIndices[task2Duration]; + task2Idx = indicesWithTask2Duration.back(); + indicesWithTask2Duration.pop_back(); + + // Add the paired tasks to the result + pairedTasks.push_back({task1Idx, task2Idx}); + } + + return pairedTasks; +} From 520701268c6f6d348975dfb4f9076a4c1c3a2cdc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:22:37 +0530 Subject: [PATCH 1592/1894] add task assignment in java --- Greedy/task_assignment.java | 110 ++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Greedy/task_assignment.java diff --git a/Greedy/task_assignment.java b/Greedy/task_assignment.java new file mode 100644 index 00000000..4d551004 --- /dev/null +++ b/Greedy/task_assignment.java @@ -0,0 +1,110 @@ +/* + + You're given an integer k representing a number of workers and an array of positive integers representing durations of + tasks that must be completed by the workers. Specifically, each worker must complete two unique tasks and can only work + on one task at a time. The number of tasks will always be equal to 2k such that each worker always has exactly two tasks + to complete. All tasks are independent of one another and can be completed in any order. Workers will complete their + assigned tasks in parallel, and the time taken to complete all tasks will be equal to the time taken to complete + the longest pair of tasks (see the sample output for an explanation). + + + Write a function that returns the optimal assignment of tasks to each worker such that the tasks are completed as fast + as possible. Your function should return a list of pairs, where each pair stores the indices of the tasks that should + be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and + task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any + correct answer will be accepted. + + Sample Input: K = 3 + tasks : [1, 3, 5, 3, 1, 4] + + Output: [ + [0, 2], + [4, 5], + [1, 3] + ] + + Explanation: + The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. + + - The function `TaskAssignment` takes two parameters: `k` (the number of workers) and `tasks` (a list of task durations). + - It initializes variables for `pairedTasks`, which will store the paired tasks, and `taskDurationToIndices`, which is + a map that will store the indices of each task duration. + - The `getTaskDurationToIndices` function is called to create the map `taskDurationToIndices`, which maps each task + duration to a list of indices. + - The task durations are sorted in ascending order using `sort.Ints(tasks)`. This allows us to pair the shortest and + longest durations together efficiently. + - The loop runs `k` times to pair tasks. In each iteration: + - The shortest duration task is selected and its index is retrieved from `taskDurationToIndices`. + - The index of the selected task is removed from the list of indices to ensure it is not paired again. + - The longest duration task is selected in a similar manner, but from the opposite end of the sorted task durations. + - The paired task indices are added to `pairedTasks`. + - Finally, `pairedTasks` is returned as the result. + + + The `getTaskDurationToIndices` function is a helper function that creates a map `taskDurationToIndices`, which maps each + task duration to a list of indices where tasks with that duration occur in the `tasks` list. + + Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. + The result is a list of paired task indices. + + O(nlog(n)) time | O(n) space - where n is the number of tasks +*/ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TaskAssignment { + + public static int[][] taskAssignment(int k, int[] tasks) { + // Initialize variables + List pairedTasks = new ArrayList<>(); + Map> taskDurationToIndices = getTaskDurationToIndices(tasks); + Arrays.sort(tasks); + int task1Idx, task2Idx; + + // Pair tasks + for (int idx = 0; idx < k; idx++) { + // Get the shortest duration task + int task1Duration = tasks[idx]; + List indicesWithTask1Duration = taskDurationToIndices.get(task1Duration); + task1Idx = indicesWithTask1Duration.remove(indicesWithTask1Duration.size() - 1); + + // Get the longest duration task + int task2SortedIndex = tasks.length - 1 - idx; + int task2Duration = tasks[task2SortedIndex]; + List indicesWithTask2Duration = taskDurationToIndices.get(task2Duration); + task2Idx = indicesWithTask2Duration.remove(indicesWithTask2Duration.size() - 1); + + // Add the paired tasks to the result + pairedTasks.add(new int[]{task1Idx, task2Idx}); + } + + return pairedTasks.toArray(new int[0][2]); + } + + private static Map> getTaskDurationToIndices(int[] tasks) { + Map> taskDurationToIndices = new HashMap<>(); + + for (int idx = 0; idx < tasks.length; idx++) { + int taskDuration = tasks[idx]; + List indices = taskDurationToIndices.getOrDefault(taskDuration, new ArrayList<>()); + indices.add(idx); + taskDurationToIndices.put(taskDuration, indices); + } + + return taskDurationToIndices; + } + + public static void main(String[] args) { + int k = 3; + int[] tasks = {1, 3, 5, 3, 1, 4}; + int[][] pairedTasks = taskAssignment(k, tasks); + + // Print the paired tasks + for (int[] pair : pairedTasks) { + System.out.println(Arrays.toString(pair)); + } + } +} From ae68506b5a4fdf9a66626faa9b707d69c24adf67 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:22:43 +0530 Subject: [PATCH 1593/1894] add task assignment in javascript --- Greedy/task_assignment.js | 100 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Greedy/task_assignment.js diff --git a/Greedy/task_assignment.js b/Greedy/task_assignment.js new file mode 100644 index 00000000..211ef209 --- /dev/null +++ b/Greedy/task_assignment.js @@ -0,0 +1,100 @@ +/* + + You're given an integer k representing a number of workers and an array of positive integers representing durations of + tasks that must be completed by the workers. Specifically, each worker must complete two unique tasks and can only work + on one task at a time. The number of tasks will always be equal to 2k such that each worker always has exactly two tasks + to complete. All tasks are independent of one another and can be completed in any order. Workers will complete their + assigned tasks in parallel, and the time taken to complete all tasks will be equal to the time taken to complete + the longest pair of tasks (see the sample output for an explanation). + + + Write a function that returns the optimal assignment of tasks to each worker such that the tasks are completed as fast + as possible. Your function should return a list of pairs, where each pair stores the indices of the tasks that should + be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and + task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any + correct answer will be accepted. + + Sample Input: K = 3 + tasks : [1, 3, 5, 3, 1, 4] + + Output: [ + [0, 2], + [4, 5], + [1, 3] + ] + + Explanation: + The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. + + - The function `TaskAssignment` takes two parameters: `k` (the number of workers) and `tasks` (a list of task durations). + - It initializes variables for `pairedTasks`, which will store the paired tasks, and `taskDurationToIndices`, which is + a map that will store the indices of each task duration. + - The `getTaskDurationToIndices` function is called to create the map `taskDurationToIndices`, which maps each task + duration to a list of indices. + - The task durations are sorted in ascending order using `sort.Ints(tasks)`. This allows us to pair the shortest and + longest durations together efficiently. + - The loop runs `k` times to pair tasks. In each iteration: + - The shortest duration task is selected and its index is retrieved from `taskDurationToIndices`. + - The index of the selected task is removed from the list of indices to ensure it is not paired again. + - The longest duration task is selected in a similar manner, but from the opposite end of the sorted task durations. + - The paired task indices are added to `pairedTasks`. + - Finally, `pairedTasks` is returned as the result. + + + The `getTaskDurationToIndices` function is a helper function that creates a map `taskDurationToIndices`, which maps each + task duration to a list of indices where tasks with that duration occur in the `tasks` list. + + Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. + The result is a list of paired task indices. + + O(nlog(n)) time | O(n) space - where n is the number of tasks +*/ +function taskAssignment(k, tasks) { + // Initialize variables + const pairedTasks = []; + const taskDurationToIndices = getTaskDurationToIndices(tasks); + tasks.sort((a, b) => a - b); + let task1Idx, task2Idx; + + // Pair tasks + for (let idx = 0; idx < k; idx++) { + // Get the shortest duration task + const task1Duration = tasks[idx]; + const indicesWithTask1Duration = taskDurationToIndices[task1Duration]; + task1Idx = indicesWithTask1Duration.pop(); + + // Get the longest duration task + const task2SortedIndex = tasks.length - 1 - idx; + const task2Duration = tasks[task2SortedIndex]; + const indicesWithTask2Duration = taskDurationToIndices[task2Duration]; + task2Idx = indicesWithTask2Duration.pop(); + + // Add the paired tasks to the result + pairedTasks.push([task1Idx, task2Idx]); + } + + return pairedTasks; +} + +function getTaskDurationToIndices(tasks) { + const taskDurationToIndices = {}; + + for (let idx = 0; idx < tasks.length; idx++) { + const taskDuration = tasks[idx]; + if (!taskDurationToIndices[taskDuration]) { + taskDurationToIndices[taskDuration] = []; + } + taskDurationToIndices[taskDuration].push(idx); + } + + return taskDurationToIndices; +} + +const k = 3; +const tasks = [1, 3, 5, 3, 1, 4]; +const pairedTasks = taskAssignment(k, tasks); + +// Print the paired tasks +pairedTasks.forEach((pair) => { + console.log(pair); +}); From d7f328322b661ccd499ae92717ab9e710bd9f364 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 9 Jul 2023 23:22:48 +0530 Subject: [PATCH 1594/1894] add task assignment in python --- Greedy/task_assignment.py | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Greedy/task_assignment.py diff --git a/Greedy/task_assignment.py b/Greedy/task_assignment.py new file mode 100644 index 00000000..13ea0346 --- /dev/null +++ b/Greedy/task_assignment.py @@ -0,0 +1,94 @@ +''' + + You're given an integer k representing a number of workers and an array of positive integers representing durations of + tasks that must be completed by the workers. Specifically, each worker must complete two unique tasks and can only work + on one task at a time. The number of tasks will always be equal to 2k such that each worker always has exactly two tasks + to complete. All tasks are independent of one another and can be completed in any order. Workers will complete their + assigned tasks in parallel, and the time taken to complete all tasks will be equal to the time taken to complete + the longest pair of tasks (see the sample output for an explanation). + + + Write a function that returns the optimal assignment of tasks to each worker such that the tasks are completed as fast + as possible. Your function should return a list of pairs, where each pair stores the indices of the tasks that should + be completed by one worker. The pairs should be in the following format: [task1, task2] , where the order of task1 and + task2 doesn't matter. Your function can return the pairs in any order. If multiple optimal assignments exist, any + correct answer will be accepted. + + Sample Input: K = 3 + tasks : [1, 3, 5, 3, 1, 4] + + Output: [ + [0, 2], + [4, 5], + [1, 3] + ] + + Explanation: + The code snippet is an implementation of the "Task Assignment" algorithm. It pairs tasks from a list based on their durations. The goal is to assign tasks to workers in a way that minimizes the total execution time. + + - The function `TaskAssignment` takes two parameters: `k` (the number of workers) and `tasks` (a list of task durations). + - It initializes variables for `pairedTasks`, which will store the paired tasks, and `taskDurationToIndices`, which is + a map that will store the indices of each task duration. + - The `getTaskDurationToIndices` function is called to create the map `taskDurationToIndices`, which maps each task + duration to a list of indices. + - The task durations are sorted in ascending order using `sort.Ints(tasks)`. This allows us to pair the shortest and + longest durations together efficiently. + - The loop runs `k` times to pair tasks. In each iteration: + - The shortest duration task is selected and its index is retrieved from `taskDurationToIndices`. + - The index of the selected task is removed from the list of indices to ensure it is not paired again. + - The longest duration task is selected in a similar manner, but from the opposite end of the sorted task durations. + - The paired task indices are added to `pairedTasks`. + - Finally, `pairedTasks` is returned as the result. + + + The `getTaskDurationToIndices` function is a helper function that creates a map `taskDurationToIndices`, which maps each + task duration to a list of indices where tasks with that duration occur in the `tasks` list. + + Overall, the algorithm pairs tasks based on their durations while considering the shortest and longest durations together. + The result is a list of paired task indices. + + O(nlog(n)) time | O(n) space - where n is the number of tasks +''' + +def task_assignment(k, tasks): + # Initialize variables + paired_tasks = [] + task_duration_to_indices = get_task_duration_to_indices(tasks) + tasks.sort() + + for idx in range(k): + # Get the shortest duration task + task1_duration = tasks[idx] + indices_with_task1_duration = task_duration_to_indices[task1_duration] + task1_idx = indices_with_task1_duration.pop() + + # Get the longest duration task + task2_sorted_index = len(tasks) - 1 - idx + task2_duration = tasks[task2_sorted_index] + indices_with_task2_duration = task_duration_to_indices[task2_duration] + task2_idx = indices_with_task2_duration.pop() + + # Add the paired tasks to the result + paired_tasks.append([task1_idx, task2_idx]) + + return paired_tasks + +def get_task_duration_to_indices(tasks): + task_duration_to_indices = {} + + for idx in range(len(tasks)): + task_duration = tasks[idx] + if task_duration not in task_duration_to_indices: + task_duration_to_indices[task_duration] = [] + task_duration_to_indices[task_duration].append(idx) + + return task_duration_to_indices + +# Example usage +k = 3 +tasks = [1, 3, 5, 3, 1, 4] +paired_tasks = task_assignment(k, tasks) + +# Print the paired tasks +for pair in paired_tasks: + print(pair) From e45f826a1dae4df0581da2f7550733c4ec055f56 Mon Sep 17 00:00:00 2001 From: Mrinal Anand <97303675+MrinalCom@users.noreply.github.com> Date: Mon, 10 Jul 2023 14:07:57 +0530 Subject: [PATCH 1595/1894] Create Convert an array to reduced form using hashing.cpp --- ...an array to reduced form using hashing.cpp | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Hash Table/Convert an array to reduced form using hashing.cpp diff --git a/Hash Table/Convert an array to reduced form using hashing.cpp b/Hash Table/Convert an array to reduced form using hashing.cpp new file mode 100644 index 00000000..017eced5 --- /dev/null +++ b/Hash Table/Convert an array to reduced form using hashing.cpp @@ -0,0 +1,83 @@ +/*Declare an array of name ar[ ] with n elements +Create a temp[ ] array of size n +Create a hashmap for the same datatype of the array +Copy the elements of array ar [ ] to temp[ ] array +Sort the temp[ ] array in ascending order +After sorting, mapping the values from 0 to n-1 with the temp array. +Replace the ar[ ] element with the hashtable values. +Print the ar[ ] */ + + + + + + + + +#include +using namespace std; +int main() +{ + int ar[] = {12,34,5,6,8}; + + /* calculating the size of the given array */ + int size = sizeof(ar)/sizeof(ar[0]); + + /* creating temp array to sort and manipulate the array*/ + int temp[size],val=0; + + /* creating an unordered_map*/ + unordered_map mapped; + + + /* copying the elements from ar to temp array*/ + for(int i=0;i Date: Mon, 10 Jul 2023 23:38:19 +0530 Subject: [PATCH 1596/1894] update heap in go --- Heaps/heap.go | 194 +++++++++++++++++--------------------------------- 1 file changed, 67 insertions(+), 127 deletions(-) diff --git a/Heaps/heap.go b/Heaps/heap.go index e91bbe04..4c087db1 100644 --- a/Heaps/heap.go +++ b/Heaps/heap.go @@ -1,147 +1,87 @@ package main -import ( - "fmt" - "math" -) +// Do not edit the class below except for the buildHeap, +// siftDown, siftUp, peek, remove, and insert methods. +// Feel free to add new properties and methods to the class. +type MinHeap []int -// Item: Defines the interface for an element to be held by a Heap instance -type Item interface { - Less(item Item) bool -} -// Heap: binary heap with support for min heap operations -type Heap struct { - size int - data []Item -} - -// New: returns a pointer to an empty min-heap -func New() *Heap { - return &Heap{} -} - -// Parent: For a node at ith location its parent is ar (i - 1) / 2 location -func Parent(i int) int { - return int(math.Floor(float64(i - 1) / 2.0)) -} - -// LeftChild: For a node at ith location its left children is at 2 * i + 1 location -func LeftChild(parent int) int { - return (2 * parent) + 1 +func NewMinHeap(array []int) *MinHeap { + // Do not edit the lines below. + heap := MinHeap(array) + ptr := &heap + ptr.BuildHeap(array) + return ptr } -// RightChild: For a node at ith location its right children is at 2 * i + 2 th locations -func RightChild(parent int) int { - return (2 * parent) + 2 +func (h *MinHeap) BuildHeap(array []int) { + first := (len(array) - 2) / 2 + for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { + h.siftDown(currentIdx, len(array) - 1) + } } -// GetMinimum: Minimum element is always at root -func GetMinimum(h *Heap) (Item, error) { - if h.size == 0 { - return nil, fmt.Errorf("Unable to get element from empty heap") - } - return h.data[0], nil +func (h *MinHeap) siftDown(currentIndex, endIndex int) { + childOneIdx := currentIndex * 2 + 1 + for childOneIdx <= endIndex { + childTwoIdx := -1 + if currentIndex * 2 + 2 <= endIndex { + childTwoIdx = currentIndex * 2 + 2 + } + indexToSwap := childOneIdx + if childTwoIdx > -1 && (*h)[childOneIdx] > (*h)[childTwoIdx] { + indexToSwap = childTwoIdx + } + if (*h)[currentIndex] > (*h)[indexToSwap] { + h.swap(currentIndex, indexToSwap) + currentIndex = indexToSwap + childOneIdx = currentIndex * 2 + 1 + } else { + return + } + } + } -// Note: Deleting an element uses percolateUp, and inserting an element uses percolateDown. -// PercolateUp: move from bottom to top -// Heap is a complete binary tree and in the worst case we start at the root and come -// down to the leaf. This is equal to the height of the complete binary tree. -// Time Complexity: O(log n) Space Complexity: O(1). -func (h *Heap) percolateUp() { - idx := h.size - if idx <= 0 { - return - } - for { - p := Parent(idx) - if p < 0 || h.data[p].Less(h.data[idx]) { - break - } - swap(h, p, idx) - idx = p - } +func (h *MinHeap) siftUp() { + currentIdx := h.length() - 1 + parentIdx := (currentIdx - 1) / 2 + for currentIdx > 0 { + current, parent := (*h)[currentIdx], (*h)[parentIdx] + if current < parent { + h.swap(currentIdx, parentIdx) + currentIdx = parentIdx + parentIdx = (currentIdx - 1) / 2 + } else { + return + } + } } -// To delete an element from heap, we just need to delete the element from the root. This is the only operation -// (maximum element) supported by standard heap. After deleting the root element, copy the last element of the heap -// (tree) and delete that last element. -// After replacing the last element, the tree may not satisfy the heap property. To make it heap again, call the -// percolateDown function. -// 1 Copy the first element into some variable -// 2 Copy the last element into first element location -// 3 percolateDown the first element -// Time Complexity: O(log n) Space Complexity: O(1). -func (h *Heap) percolateDown(i int) { - p := i - for { - l := LeftChild(p) - r := RightChild(p) - s := p - if l < h.size && h.data[l].Less(h.data[s]) { - s = l - } - if r < h.size && h.data[r].Less(h.data[s]) { - s = r - } - if s == p { - break - } - swap(h, p, s) - p = s - } +func (h MinHeap) Peek() int { + if len(h) == 0 { + return -1 + } + return h[0] } -func swap(h *Heap, i int, j int) { - temp := h.data[i] - h.data[i] = h.data[j] - h.data[j] = temp +func (h *MinHeap) Remove() int { + l := h.length() + h.swap(0, l - 1) + peeked := (*h)[l - 1] + *h = (*h)[: l - 1] + h.siftDown(0, l - 1) + return peeked } -// Extract - removes and returns the 'item' at the top of the heap, maintaining the min-heap invariant -func (h *Heap) Extract() (Item, error) { - n := h.size - if n == 0 { - return nil, fmt.Errorf("Unable to extract from empty Heap") - } - m := h.data[0] - h.data[0] = h.data[n-1] - h.data = h.data[:n-1] - h.size-- - if h.size > 0 { - h.percolateDown(0) - } else { - h.data = nil - } - return m, nil +func (h *MinHeap) Insert(value int) { + *h = append(*h, value) + h.siftUp() } -// Insert - inserts 'item' into the Heap, maintaining the min-heap -func (h *Heap) Insert(item Item) { - if h.size == 0 { - h.data = make([]Item, 1) - h.data[0] = item - } else { - h.data = append(h.data, item) - } - h.size++ - h.percolateUp() +func (h MinHeap) swap(i, j int) { + h[i], h[j] = h[j], h[i] } -// Heapify - returns a pointer to a min-heap composed of the elements of 'items' -// One simple approach for building the heap is, take n input items and place them into an empty heap. This can be -// done with n successive inserts and takes O(nlogn) in the worst case. This is due to the fact that each insert -// operation takes O(logn). -func Heapify(items []Item) *Heap { - h := New() - n := len(items) - h.data = make([]Item, n) - copy(h.data, items) - h.size = len(items) - i := int(n/2) - for i >= 0 { - h.percolateDown(i) - i-- - } - return h +func (h MinHeap) length() int { + return len(h) } \ No newline at end of file From 2c592948aa4378238ff079e483b5de99183630a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:40:28 +0530 Subject: [PATCH 1597/1894] add question --- Heaps/heap.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Heaps/heap.go b/Heaps/heap.go index 4c087db1..753dea52 100644 --- a/Heaps/heap.go +++ b/Heaps/heap.go @@ -1,3 +1,15 @@ +/* + Implement a Min-Heap class that supports + + Building a Min Heap from an input array of integers. + Inserting integers in the heap. + Removing the heap's minimum / root value. + Peeking at the heap's minimum / root value. + Sifting integers up and down the heap, which is to be used when inserting and removing values. + + Note that the heap should be represented in the form of an array. + +*/ package main // Do not edit the class below except for the buildHeap, From 9ff76abf226d6607ee94a57f81aeb8a8419d58d4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:41:23 +0530 Subject: [PATCH 1598/1894] add explanation --- Heaps/heap.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Heaps/heap.go b/Heaps/heap.go index 753dea52..14d677b9 100644 --- a/Heaps/heap.go +++ b/Heaps/heap.go @@ -9,6 +9,28 @@ Note that the heap should be represented in the form of an array. + Explanation: + + The code snippet implements a MinHeap data structure in Go. + + - `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object. + It calls the `BuildHeap` method to construct the heap structure. + - `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the + last non-leaf node. + - `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary. + - `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position. + It compares the element with its parent and swaps it if necessary. + - `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it. + - `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element, + removes the last element from the heap, and then calls `siftDown` to maintain the heap property. + - `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then + calls `siftUp` to maintain the heap property. + - `swap`: This method swaps two elements in the heap given their indices. + - `length`: This method returns the number of elements in the heap. + + Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, + and retrieval of the minimum element. + */ package main From 62b4fe53f914ae84660a9b49b8187801c1773fb4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:42:17 +0530 Subject: [PATCH 1599/1894] add comments --- Heaps/heap.go | 107 +++++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 49 deletions(-) diff --git a/Heaps/heap.go b/Heaps/heap.go index 14d677b9..3a516815 100644 --- a/Heaps/heap.go +++ b/Heaps/heap.go @@ -34,88 +34,97 @@ */ package main -// Do not edit the class below except for the buildHeap, -// siftDown, siftUp, peek, remove, and insert methods. -// Feel free to add new properties and methods to the class. +// MinHeap represents a min heap data structure. type MinHeap []int +// NewMinHeap creates a new MinHeap from an input array and returns a pointer to it. func NewMinHeap(array []int) *MinHeap { - // Do not edit the lines below. + // Create a heap from the input array heap := MinHeap(array) ptr := &heap + // Build the heap structure ptr.BuildHeap(array) return ptr } +// BuildHeap constructs the heap by calling siftDown on each parent node. func (h *MinHeap) BuildHeap(array []int) { + // Calculate the index of the first parent node first := (len(array) - 2) / 2 - for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { - h.siftDown(currentIdx, len(array) - 1) - } + // Iterate over each parent node and sift it down + for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { + h.siftDown(currentIdx, len(array)-1) + } } +// siftDown moves an element down the heap until it reaches its correct position. func (h *MinHeap) siftDown(currentIndex, endIndex int) { - childOneIdx := currentIndex * 2 + 1 - for childOneIdx <= endIndex { - childTwoIdx := -1 - if currentIndex * 2 + 2 <= endIndex { - childTwoIdx = currentIndex * 2 + 2 - } - indexToSwap := childOneIdx - if childTwoIdx > -1 && (*h)[childOneIdx] > (*h)[childTwoIdx] { - indexToSwap = childTwoIdx - } - if (*h)[currentIndex] > (*h)[indexToSwap] { - h.swap(currentIndex, indexToSwap) - currentIndex = indexToSwap - childOneIdx = currentIndex * 2 + 1 - } else { - return - } - } - + childOneIdx := currentIndex*2 + 1 + for childOneIdx <= endIndex { + childTwoIdx := -1 + if currentIndex*2+2 <= endIndex { + childTwoIdx = currentIndex*2 + 2 + } + indexToSwap := childOneIdx + if childTwoIdx > -1 && (*h)[childOneIdx] > (*h)[childTwoIdx] { + indexToSwap = childTwoIdx + } + if (*h)[currentIndex] > (*h)[indexToSwap] { + h.swap(currentIndex, indexToSwap) + currentIndex = indexToSwap + childOneIdx = currentIndex*2 + 1 + } else { + return + } + } } +// siftUp moves an element up the heap until it reaches its correct position. func (h *MinHeap) siftUp() { currentIdx := h.length() - 1 - parentIdx := (currentIdx - 1) / 2 - for currentIdx > 0 { - current, parent := (*h)[currentIdx], (*h)[parentIdx] - if current < parent { - h.swap(currentIdx, parentIdx) - currentIdx = parentIdx - parentIdx = (currentIdx - 1) / 2 - } else { - return - } - } + parentIdx := (currentIdx - 1) / 2 + for currentIdx > 0 { + current, parent := (*h)[currentIdx], (*h)[parentIdx] + if current < parent { + h.swap(currentIdx, parentIdx) + currentIdx = parentIdx + parentIdx = (currentIdx - 1) / 2 + } else { + return + } + } } +// Peek returns the minimum element in the heap without removing it. func (h MinHeap) Peek() int { if len(h) == 0 { - return -1 - } - return h[0] + return -1 + } + return h[0] } +// Remove removes and returns the minimum element in the heap. func (h *MinHeap) Remove() int { l := h.length() - h.swap(0, l - 1) - peeked := (*h)[l - 1] - *h = (*h)[: l - 1] - h.siftDown(0, l - 1) - return peeked + h.swap(0, l-1) + peeked := (*h)[l-1] + *h = (*h)[:l-1] + h.siftDown(0, l-1) + return peeked } +// Insert inserts a new element into the heap. func (h *MinHeap) Insert(value int) { *h = append(*h, value) - h.siftUp() + h.siftUp() } +// swap swaps two elements in the heap given their indices. func (h MinHeap) swap(i, j int) { - h[i], h[j] = h[j], h[i] + h[i], h[j] = h[j], h[i] } +// length returns the number of elements in the heap. func (h MinHeap) length() int { - return len(h) -} \ No newline at end of file + return len(h) +} From 7e31e6e252c5942ca8f93226c21f904887c36838 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:42:50 +0530 Subject: [PATCH 1600/1894] add time and space complexity --- Heaps/heap.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Heaps/heap.go b/Heaps/heap.go index 3a516815..30198d5a 100644 --- a/Heaps/heap.go +++ b/Heaps/heap.go @@ -31,6 +31,13 @@ Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, and retrieval of the minimum element. + BuildHeap: O(n) time | O(1) space - where n is the length of the input array + SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap + SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap + Peek: O(1) time | O(1) space + Remove: O(log(n)) time | O(1) space - where n is the length of the heap + Insert: O(log(n)) time | O(1) space - where n is the length of the heap + */ package main From 631721370f7f143778b65b78a82fa6341b36938b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:46:09 +0530 Subject: [PATCH 1601/1894] add heap in python --- Heaps/heap.py | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Heaps/heap.py diff --git a/Heaps/heap.py b/Heaps/heap.py new file mode 100644 index 00000000..76ba70ad --- /dev/null +++ b/Heaps/heap.py @@ -0,0 +1,109 @@ +''' + Implement a Min-Heap class that supports + + Building a Min Heap from an input array of integers. + Inserting integers in the heap. + Removing the heap's minimum / root value. + Peeking at the heap's minimum / root value. + Sifting integers up and down the heap, which is to be used when inserting and removing values. + + Note that the heap should be represented in the form of an array. + + Explanation: + + The code snippet implements a MinHeap data structure in Go. + + - `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object. + It calls the `BuildHeap` method to construct the heap structure. + - `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the + last non-leaf node. + - `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary. + - `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position. + It compares the element with its parent and swaps it if necessary. + - `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it. + - `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element, + removes the last element from the heap, and then calls `siftDown` to maintain the heap property. + - `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then + calls `siftUp` to maintain the heap property. + - `swap`: This method swaps two elements in the heap given their indices. + - `length`: This method returns the number of elements in the heap. + + Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, + and retrieval of the minimum element. + + BuildHeap: O(n) time | O(1) space - where n is the length of the input array + SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap + SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap + Peek: O(1) time | O(1) space + Remove: O(log(n)) time | O(1) space - where n is the length of the heap + Insert: O(log(n)) time | O(1) space - where n is the length of the heap + +''' +class MinHeap: + def __init__(self): + self.heap = [] # The heap represented as a list + + def build_heap(self, array): + # Build the heap by calling sift_down on each parent node + first = (len(array) - 2) // 2 # Start from the last parent node + for current_idx in range(first, -1, -1): + self.sift_down(current_idx, len(array) - 1) + + def sift_down(self, current_idx, end_idx): + child_one_idx = current_idx * 2 + 1 # Calculate the index of the first child + while child_one_idx <= end_idx: + child_two_idx = -1 # Initialize the index of the second child + if current_idx * 2 + 2 <= end_idx: + child_two_idx = current_idx * 2 + 2 # Calculate the index of the second child if it exists + index_to_swap = child_one_idx # Assume the first child is the one to swap with + if child_two_idx > -1 and self.heap[child_one_idx] > self.heap[child_two_idx]: + # If the second child exists and is smaller, update the index to swap with + index_to_swap = child_two_idx + if self.heap[current_idx] > self.heap[index_to_swap]: + # If the current element is greater than the one to swap with, perform the swap + self.swap(current_idx, index_to_swap) + current_idx = index_to_swap + child_one_idx = current_idx * 2 + 1 # Update the index of the first child + else: + return + + def sift_up(self): + current_idx = len(self.heap) - 1 # Start from the last element + parent_idx = (current_idx - 1) // 2 # Calculate the index of the parent + while current_idx > 0: + current, parent = self.heap[current_idx], self.heap[parent_idx] + if current < parent: + # If the current element is smaller than the parent, perform the swap + self.swap(current_idx, parent_idx) + current_idx = parent_idx + parent_idx = (current_idx - 1) // 2 # Update the index of the parent + else: + return + + def peek(self): + if not self.heap: + return -1 + return self.heap[0] # Return the minimum element at the top of the heap + + def remove(self): + l = len(self.heap) + self.swap(0, l - 1) # Swap the root with the last element + peeked = self.heap.pop() # Remove the last element (minimum) and store it + self.sift_down(0, l - 2) # Sift down the new root element + return peeked + + def insert(self, value): + self.heap.append(value) # Append the new element to the end of the heap + self.sift_up() # Sift up the new element to its correct position + + def swap(self, i, j): + self.heap[i], self.heap[j] = self.heap[j], self.heap[i] # Swap elements at indices i and j + + def length(self): + return len(self.heap) # Return the number of elements in the heap + + +def new_min_heap(array): + heap = MinHeap() # Create a new MinHeap object + heap.build_heap(array) # Build the heap using the given array + return heap From 2aaff5c45237051e7fff2502f1c2ae32ba911ece Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:47:52 +0530 Subject: [PATCH 1602/1894] add heap in c++ --- Heaps/heap.cpp | 131 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 Heaps/heap.cpp diff --git a/Heaps/heap.cpp b/Heaps/heap.cpp new file mode 100644 index 00000000..3dbf3431 --- /dev/null +++ b/Heaps/heap.cpp @@ -0,0 +1,131 @@ +/* + Implement a Min-Heap class that supports + + Building a Min Heap from an input array of integers. + Inserting integers in the heap. + Removing the heap's minimum / root value. + Peeking at the heap's minimum / root value. + Sifting integers up and down the heap, which is to be used when inserting and removing values. + + Note that the heap should be represented in the form of an array. + + Explanation: + + The code snippet implements a MinHeap data structure in Go. + + - `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object. + It calls the `BuildHeap` method to construct the heap structure. + - `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the + last non-leaf node. + - `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary. + - `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position. + It compares the element with its parent and swaps it if necessary. + - `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it. + - `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element, + removes the last element from the heap, and then calls `siftDown` to maintain the heap property. + - `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then + calls `siftUp` to maintain the heap property. + - `swap`: This method swaps two elements in the heap given their indices. + - `length`: This method returns the number of elements in the heap. + + Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, + and retrieval of the minimum element. + + BuildHeap: O(n) time | O(1) space - where n is the length of the input array + SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap + SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap + Peek: O(1) time | O(1) space + Remove: O(log(n)) time | O(1) space - where n is the length of the heap + Insert: O(log(n)) time | O(1) space - where n is the length of the heap + +*/ +#include + +class MinHeap { +public: + std::vector heap; // The heap represented as a vector + + void buildHeap(std::vector& array) { + int first = (array.size() - 2) / 2; // Start from the last parent node + for (int currentIdx = first; currentIdx >= 0; currentIdx--) { + siftDown(currentIdx, array.size() - 1); + } + } + + void siftDown(int currentIndex, int endIndex) { + int childOneIdx = currentIndex * 2 + 1; // Calculate the index of the first child + while (childOneIdx <= endIndex) { + int childTwoIdx = -1; // Initialize the index of the second child + if (currentIndex * 2 + 2 <= endIndex) { + childTwoIdx = currentIndex * 2 + 2; // Calculate the index of the second child if it exists + } + int indexToSwap = childOneIdx; // Assume the first child is the one to swap with + if (childTwoIdx > -1 && heap[childOneIdx] > heap[childTwoIdx]) { + // If the second child exists and is smaller, update the index to swap with + indexToSwap = childTwoIdx; + } + if (heap[currentIndex] > heap[indexToSwap]) { + // If the current element is greater than the one to swap with, perform the swap + swap(currentIndex, indexToSwap); + currentIndex = indexToSwap; + childOneIdx = currentIndex * 2 + 1; // Update the index of the first child + } else { + return; + } + } + } + + void siftUp() { + int currentIdx = heap.size() - 1; // Start from the last element + int parentIdx = (currentIdx - 1) / 2; // Calculate the index of the parent + while (currentIdx > 0) { + int current = heap[currentIdx]; + int parent = heap[parentIdx]; + if (current < parent) { + // If the current element is smaller than the parent, perform the swap + swap(currentIdx, parentIdx); + currentIdx = parentIdx; + parentIdx = (currentIdx - 1) / 2; // Update the index of the parent + } else { + return; + } + } + } + + int peek() { + if (heap.empty()) { + return -1; + } + return heap[0]; // Return the minimum element at the top of the heap + } + + int remove() { + int l = heap.size(); + swap(0, l - 1); // Swap the root with the last element + int peeked = heap[l - 1]; // Remove the last element (minimum) and store it + heap.pop_back(); + siftDown(0, l - 2); // Sift down the new root element + return peeked; + } + + void insert(int value) { + heap.push_back(value); // Append the new element to the end of the heap + siftUp(); // Sift up the new element to its correct position + } + + void swap(int i, int j) { + int temp = heap[i]; + heap[i] = heap[j]; + heap[j] = temp; // Swap elements at indices i and j + } + + int length() { + return heap.size(); // Return the number of elements in the heap + } +}; + +MinHeap* newMinHeap(std::vector& array) { + MinHeap* heap = new MinHeap(); // Create a new MinHeap object + heap->buildHeap(array); // Build the heap using the given array + return heap; +} From 556c0373bfdbd9bf26cfd9f7d78c4714dc4a64d7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:48:51 +0530 Subject: [PATCH 1603/1894] add heap in java --- Heaps/heap.java | 151 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 Heaps/heap.java diff --git a/Heaps/heap.java b/Heaps/heap.java new file mode 100644 index 00000000..d854bf90 --- /dev/null +++ b/Heaps/heap.java @@ -0,0 +1,151 @@ +/* + Implement a Min-Heap class that supports + + Building a Min Heap from an input array of integers. + Inserting integers in the heap. + Removing the heap's minimum / root value. + Peeking at the heap's minimum / root value. + Sifting integers up and down the heap, which is to be used when inserting and removing values. + + Note that the heap should be represented in the form of an array. + + Explanation: + + The code snippet implements a MinHeap data structure in Go. + + - `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object. + It calls the `BuildHeap` method to construct the heap structure. + - `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the + last non-leaf node. + - `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary. + - `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position. + It compares the element with its parent and swaps it if necessary. + - `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it. + - `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element, + removes the last element from the heap, and then calls `siftDown` to maintain the heap property. + - `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then + calls `siftUp` to maintain the heap property. + - `swap`: This method swaps two elements in the heap given their indices. + - `length`: This method returns the number of elements in the heap. + + Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, + and retrieval of the minimum element. + + BuildHeap: O(n) time | O(1) space - where n is the length of the input array + SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap + SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap + Peek: O(1) time | O(1) space + Remove: O(log(n)) time | O(1) space - where n is the length of the heap + Insert: O(log(n)) time | O(1) space - where n is the length of the heap + +*/ +import java.util.Arrays; + +public class MinHeap { + private int[] heap; // The heap represented as an array + private int size; // The current size of the heap + + public MinHeap(int[] array) { + heap = Arrays.copyOf(array, array.length); // Create a copy of the input array + size = array.length; + buildHeap(); // Build the heap + } + + private void buildHeap() { + int first = (size - 2) / 2; // Start from the last parent node + for (int currentIdx = first; currentIdx >= 0; currentIdx--) { + siftDown(currentIdx); + } + } + + private void siftDown(int currentIndex) { + int childOneIdx = currentIndex * 2 + 1; // Calculate the index of the first child + while (childOneIdx < size) { + int childTwoIdx = -1; // Initialize the index of the second child + if (currentIndex * 2 + 2 < size) { + childTwoIdx = currentIndex * 2 + 2; // Calculate the index of the second child if it exists + } + int indexToSwap = childOneIdx; // Assume the first child is the one to swap with + if (childTwoIdx > -1 && heap[childOneIdx] > heap[childTwoIdx]) { + // If the second child exists and is smaller, update the index to swap with + indexToSwap = childTwoIdx; + } + if (heap[currentIndex] > heap[indexToSwap]) { + // If the current element is greater than the one to swap with, perform the swap + swap(currentIndex, indexToSwap); + currentIndex = indexToSwap; + childOneIdx = currentIndex * 2 + 1; // Update the index of the first child + } else { + return; + } + } + } + + private void siftUp() { + int currentIdx = size - 1; // Start from the last element + int parentIdx = (currentIdx - 1) / 2; // Calculate the index of the parent + while (currentIdx > 0) { + int current = heap[currentIdx]; + int parent = heap[parentIdx]; + if (current < parent) { + // If the current element is smaller than the parent, perform the swap + swap(currentIdx, parentIdx); + currentIdx = parentIdx; + parentIdx = (currentIdx - 1) / 2; // Update the index of the parent + } else { + return; + } + } + } + + public int peek() { + if (size == 0) { + return -1; + } + return heap[0]; // Return the minimum element at the top of the heap + } + + public int remove() { + swap(0, size - 1); // Swap the root with the last element + int peeked = heap[size - 1]; // Remove the last element (minimum) and store it + size--; + siftDown(0); // Sift down the new root element + return peeked; + } + + public void insert(int value) { + if (size >= heap.length) { + heap = Arrays.copyOf(heap, size * 2); // Resize the array if necessary + } + heap[size] = value; // Append the new element to the end of the heap + size++; + siftUp(); // Sift up the new element to its correct position + } + + private void swap(int i, int j) { + int temp = heap[i]; + heap[i] = heap[j]; + heap[j] = temp; // Swap elements at indices i and j + } + + public int length() { + return size; // Return the number of elements in the heap + } +} + +public class Main { + public static void main(String[] args) { + int[] array = { 9, 4, 7, 1, -2, 6, 5 }; + MinHeap minHeap = new MinHeap(array); + + System.out.println("Peek: " + minHeap.peek()); + System.out.println("Remove: " + minHeap.remove()); + System.out.println("Length: " + minHeap.length()); + + minHeap.insert(2); + minHeap.insert(-5); + + System.out.println("Peek: " + minHeap.peek()); + System.out.println("Length: " + minHeap.length()); + } +} From fb92d84e3a1f19e19b119c3bda054d22d2d883c8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 10 Jul 2023 23:49:42 +0530 Subject: [PATCH 1604/1894] add heap in javascript --- Heaps/heap.js | 139 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 Heaps/heap.js diff --git a/Heaps/heap.js b/Heaps/heap.js new file mode 100644 index 00000000..4fbcd714 --- /dev/null +++ b/Heaps/heap.js @@ -0,0 +1,139 @@ +/* + Implement a Min-Heap class that supports + + Building a Min Heap from an input array of integers. + Inserting integers in the heap. + Removing the heap's minimum / root value. + Peeking at the heap's minimum / root value. + Sifting integers up and down the heap, which is to be used when inserting and removing values. + + Note that the heap should be represented in the form of an array. + + Explanation: + + The code snippet implements a MinHeap data structure in Go. + + - `NewMinHeap`: This function creates a new MinHeap from an input array and returns a pointer to the MinHeap object. + It calls the `BuildHeap` method to construct the heap structure. + - `BuildHeap`: This method constructs the heap by iteratively calling `siftDown` on each parent node starting from the + last non-leaf node. + - `siftDown`: This method corrects the heap property by moving an element down the heap until it reaches its correct position. It compares the element with its children and swaps it with the smaller child if necessary. + - `siftUp`: This method corrects the heap property by moving an element up the heap until it reaches its correct position. + It compares the element with its parent and swaps it if necessary. + - `Peek`: This method returns the minimum element in the heap (the root of the heap) without removing it. + - `Remove`: This method removes and returns the minimum element in the heap. It swaps the root with the last element, + removes the last element from the heap, and then calls `siftDown` to maintain the heap property. + - `Insert`: This method inserts a new element into the heap. It appends the element to the end of the heap and then + calls `siftUp` to maintain the heap property. + - `swap`: This method swaps two elements in the heap given their indices. + - `length`: This method returns the number of elements in the heap. + + Overall, this code provides a basic implementation of a MinHeap data structure, allowing for efficient insertion, removal, + and retrieval of the minimum element. + + BuildHeap: O(n) time | O(1) space - where n is the length of the input array + SiftDown: O(log(n)) time | O(1) space - where n is the length of the heap + SiftUp: O(log(n)) time | O(1) space - where n is the length of the heap + Peek: O(1) time | O(1) space + Remove: O(log(n)) time | O(1) space - where n is the length of the heap + Insert: O(log(n)) time | O(1) space - where n is the length of the heap + +*/ +class MinHeap { + constructor(array) { + this.heap = array.slice(); // Create a copy of the input array + this.size = array.length; + this.buildHeap(); // Build the heap + } + + buildHeap() { + const first = Math.floor((this.size - 2) / 2); // Start from the last parent node + for (let currentIdx = first; currentIdx >= 0; currentIdx--) { + this.siftDown(currentIdx); + } + } + + siftDown(currentIndex) { + let childOneIdx = currentIndex * 2 + 1; // Calculate the index of the first child + while (childOneIdx < this.size) { + let childTwoIdx = -1; // Initialize the index of the second child + if (currentIndex * 2 + 2 < this.size) { + childTwoIdx = currentIndex * 2 + 2; // Calculate the index of the second child if it exists + } + let indexToSwap = childOneIdx; // Assume the first child is the one to swap with + if (childTwoIdx > -1 && this.heap[childOneIdx] > this.heap[childTwoIdx]) { + // If the second child exists and is smaller, update the index to swap with + indexToSwap = childTwoIdx; + } + if (this.heap[currentIndex] > this.heap[indexToSwap]) { + // If the current element is greater than the one to swap with, perform the swap + this.swap(currentIndex, indexToSwap); + currentIndex = indexToSwap; + childOneIdx = currentIndex * 2 + 1; // Update the index of the first child + } else { + return; + } + } + } + + siftUp() { + let currentIdx = this.size - 1; // Start from the last element + let parentIdx = Math.floor((currentIdx - 1) / 2); // Calculate the index of the parent + while (currentIdx > 0) { + const current = this.heap[currentIdx]; + const parent = this.heap[parentIdx]; + if (current < parent) { + // If the current element is smaller than the parent, perform the swap + this.swap(currentIdx, parentIdx); + currentIdx = parentIdx; + parentIdx = Math.floor((currentIdx - 1) / 2); // Update the index of the parent + } else { + return; + } + } + } + + peek() { + if (this.size === 0) { + return -1; + } + return this.heap[0]; // Return the minimum element at the top of the heap + } + + remove() { + this.swap(0, this.size - 1); // Swap the root with the last element + const peeked = this.heap[this.size - 1]; // Remove the last element (minimum) and store it + this.size--; + this.heap.length = this.size; // Resize the heap array + this.siftDown(0); // Sift down the new root element + return peeked; + } + + insert(value) { + this.heap.push(value); // Append the new element to the end of the heap + this.size++; + this.siftUp(); // Sift up the new element to its correct position + } + + swap(i, j) { + [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; // Swap elements at indices i and j + } + + length() { + return this.size; // Return the number of elements in the heap + } +} + +// Example usage: +const array = [9, 4, 7, 1, -2, 6, 5]; +const minHeap = new MinHeap(array); + +console.log("Peek:", minHeap.peek()); +console.log("Remove:", minHeap.remove()); +console.log("Length:", minHeap.length()); + +minHeap.insert(2); +minHeap.insert(-5); + +console.log("Peek:", minHeap.peek()); +console.log("Length:", minHeap.length()); From 55e8dd64249b7c24da72ce8a19333e2bdcc93fbd Mon Sep 17 00:00:00 2001 From: "ASHWIN A.R" Date: Tue, 11 Jul 2023 02:45:07 +0530 Subject: [PATCH 1605/1894] Create Case-specific Sorting of Strings(GFG) --- Case-specific Sorting of Strings(GFG) | 65 +++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Case-specific Sorting of Strings(GFG) diff --git a/Case-specific Sorting of Strings(GFG) b/Case-specific Sorting of Strings(GFG) new file mode 100644 index 00000000..199e653a --- /dev/null +++ b/Case-specific Sorting of Strings(GFG) @@ -0,0 +1,65 @@ +Case-specific Sorting of Strings (GFG) +Given a string S consisting of only uppercase and lowercase characters. The task is to sort uppercase and lowercase letters separately such that if the ith place in the original string had an Uppercase character then it should not have a lowercase character after being sorted and vice versa. + +Example 1: + +Input: +N = 12 +S = defRTSersUXI +Output: deeIRSfrsTUX +Explanation: Sorted form of given string +with the same case of character as that +in original string is deeIRSfrsTUX +Example 2: + +Input: +N = 6 +S = srbDKi +Output: birDKs +Explanation: Sorted form of given string +with the same case of character +result in output as birDKs. +Your Task: +You only need to complete the function caseSort, that takes a string str and the length of the string n and returns sorted string. + +Explanation: In this problem, we create three strings based on the given string.One for storing the capital letters named as caps string (string caps=""), second for small letters (string small="") and finally the third string (string ans="") which would store the final result. +We will sort the strings in order to maintain alphabetical order. +Then we traverse the given string using x (pointer) , i and j pointers for the caps and small strings. j pointer is used to traverse the string caps while i used to traverse the string small. +x pointer is used to iterate through the given string as a whole and for each capital letter found we will insert the the letter from string caps into the string ans. +Similarly, for each small letter, we will insert it from the string small into the ans string. +Finally we return the ans string. + +CODE: + +class Solution +{ + public: + //Function to perform case-specific sorting of strings. + string caseSort(string str, int n) + { + string small="", caps = "",ans=""; + for(auto x:str){ + if(isupper(x)){ + caps+=x; + } + else{ + small+=x; + } + } + sort(caps.begin(),caps.end()); + sort(small.begin(),small.end()); + int i=0,j=0; + for(auto x:str){ + if(isupper(x)){ + ans+=caps[j]; + j++; + } + else{ + ans+=small[i]; + i++; + } + } + return ans; + // your code here + } +}; From 13eca9c5b0b58081d15fcec085ead875fc29b902 Mon Sep 17 00:00:00 2001 From: "ASHWIN A.R" Date: Tue, 11 Jul 2023 19:05:25 +0530 Subject: [PATCH 1606/1894] Update Case-specific Sorting of Strings(GFG)/Strings --- Case-specific Sorting of Strings(GFG) | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Case-specific Sorting of Strings(GFG) b/Case-specific Sorting of Strings(GFG) index 199e653a..939b6bfe 100644 --- a/Case-specific Sorting of Strings(GFG) +++ b/Case-specific Sorting of Strings(GFG) @@ -1,4 +1,4 @@ -Case-specific Sorting of Strings (GFG) +case-specific sorting of strings (GFG) Given a string S consisting of only uppercase and lowercase characters. The task is to sort uppercase and lowercase letters separately such that if the ith place in the original string had an Uppercase character then it should not have a lowercase character after being sorted and vice versa. Example 1: From 6fb495869a07ab332c2baa1f16c3a98eb0ee15d8 Mon Sep 17 00:00:00 2001 From: "ASHWIN A.R" Date: Tue, 11 Jul 2023 19:12:57 +0530 Subject: [PATCH 1607/1894] Rename Case-specific Sorting of Strings(GFG) to case-specific sorting of strings(gfg).cpp --- ...g of Strings(GFG) => case-specific sorting of strings(gfg).cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Case-specific Sorting of Strings(GFG) => case-specific sorting of strings(gfg).cpp (100%) diff --git a/Case-specific Sorting of Strings(GFG) b/case-specific sorting of strings(gfg).cpp similarity index 100% rename from Case-specific Sorting of Strings(GFG) rename to case-specific sorting of strings(gfg).cpp From 54366cd2cc2a310d854eca88d531a3d8f299e9e9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:42:38 +0530 Subject: [PATCH 1608/1894] add group anagrams in go --- Strings/group_anagrams.go | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Strings/group_anagrams.go diff --git a/Strings/group_anagrams.go b/Strings/group_anagrams.go new file mode 100644 index 00000000..3995d825 --- /dev/null +++ b/Strings/group_anagrams.go @@ -0,0 +1,40 @@ +package main + +import "sort" + +// `GroupAnagrams` groups anagrams together. +func GroupAnagrams(words []string) [][]string { + // Create a map where the keys are sorted strings of words and the values are lists of words + // that have the same sorted string. + anagrams := map[string][]string{} + for _, word := range words { + // Get the sorted string for the word. + sortedWord := sortWord(word) + + // Add the word to the list of words associated with the sorted string in the map. + anagrams[sortedWord] = append(anagrams[sortedWord], word) + } + + // Create a list of lists, where each inner list contains all the anagrams of a word in the original list. + result := [][]string{} + for _, group := range anagrams { + result = append(result, group) + } + + // Return the list of lists. + return result +} + +// `sortWord` takes a word as input and returns a string that contains the word's letters in sorted order. +func sortWord(word string) string { + // Convert the word to a byte array. + wordBytes := []byte(word) + + // Sort the byte array. + sort.Slice(wordBytes, func(i, j int) bool { + return wordBytes[i] < wordBytes[j] + }) + + // Return a string that contains the sorted byte array. + return string(wordBytes) +} From 61b93facab45cefe57f8b839a4bddb3e777219ac Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:43:36 +0530 Subject: [PATCH 1609/1894] add explanation --- Strings/group_anagrams.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Strings/group_anagrams.go b/Strings/group_anagrams.go index 3995d825..e116a0ec 100644 --- a/Strings/group_anagrams.go +++ b/Strings/group_anagrams.go @@ -1,3 +1,22 @@ +/* + Group Anagrams + + Explanation: + + The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging + the letters of another word or phrase. + + The function first defines two functions: GroupAnagrams and sortWord. The GroupAnagrams function takes a list of words + as input and returns a list of lists, where each inner list contains all the anagrams of a word in the original list. + The sortWord function takes a word as input and returns a string that contains the word's letters in sorted order. + + The GroupAnagrams function works by first creating a map where the keys are sorted strings of words and the values are + lists of words that have the same sorted string. Then, the function iterates through the list of words, calling the + sortWord function to get the sorted string for each word. The function then adds the word to the list of words associated with the sorted string in the map. Finally, the function iterates through the map, adding each list of words to a list of lists. + + The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort + the byte array. The function then returns a string that contains the sorted byte array. +*/ package main import "sort" From 8b0771401714fae4d86cf74316a1c63fbc629444 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:44:09 +0530 Subject: [PATCH 1610/1894] add time and space --- Strings/group_anagrams.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Strings/group_anagrams.go b/Strings/group_anagrams.go index e116a0ec..590c3583 100644 --- a/Strings/group_anagrams.go +++ b/Strings/group_anagrams.go @@ -16,6 +16,9 @@ The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort the byte array. The function then returns a string that contains the sorted byte array. + + O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is the length of the longest word + */ package main From 70087550ea615ff4321523f391e90686a53db33a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:44:44 +0530 Subject: [PATCH 1611/1894] add sample io --- Strings/group_anagrams.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Strings/group_anagrams.go b/Strings/group_anagrams.go index 590c3583..bdd3209d 100644 --- a/Strings/group_anagrams.go +++ b/Strings/group_anagrams.go @@ -1,6 +1,9 @@ /* Group Anagrams + Sample Input: = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"] + Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]] + Explanation: The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging From df1eb553fdbca1748826705813d779b1185eaa35 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:48:17 +0530 Subject: [PATCH 1612/1894] update group anagrams --- Strings/group_anagrams.cpp | 107 ++++++++++++++++++++----------------- 1 file changed, 59 insertions(+), 48 deletions(-) diff --git a/Strings/group_anagrams.cpp b/Strings/group_anagrams.cpp index 07ef9fe8..460cbf84 100644 --- a/Strings/group_anagrams.cpp +++ b/Strings/group_anagrams.cpp @@ -1,67 +1,78 @@ /* -Given an array of strings strs, group the anagrams together. You can return the answer in any order. + Group Anagrams -An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + Sample Input: = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"] + Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]] -Example 1: + Explanation: -Input: strs = ["eat","tea","tan","ate","nat","bat"] -Output: [["bat"],["nat","tan"],["ate","eat","tea"]] -Example 2: + The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging + the letters of another word or phrase. -Input: strs = [""] -Output: [[""]] -Example 3: + The function first defines two functions: GroupAnagrams and sortWord. The GroupAnagrams function takes a list of words + as input and returns a list of lists, where each inner list contains all the anagrams of a word in the original list. + The sortWord function takes a word as input and returns a string that contains the word's letters in sorted order. -Input: strs = ["a"] -Output: [["a"]] + The GroupAnagrams function works by first creating a map where the keys are sorted strings of words and the values are + lists of words that have the same sorted string. Then, the function iterates through the list of words, calling the + sortWord function to get the sorted string for each word. The function then adds the word to the list of words associated with the sorted string in the map. Finally, the function iterates through the map, adding each list of words to a list of lists. -Approach: -1. Go through the list of words -2. Sort each word. All annograms of the word would look the same being sorted. -3. Find matching bucket in map and put the word to it -4. When finished, convert the map to vector of vectors and return it + The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort + the byte array. The function then returns a string that contains the sorted byte array. + + O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is the length of the longest word */ -#include +#include #include -#include #include +#include -using namespace std; +// Function to sort a word and return the sorted string +std::string sortWord(const std::string& word) { + std::string sortedWord = word; + std::sort(sortedWord.begin(), sortedWord.end()); + return sortedWord; +} -class Solution { -public: - vector> groupAnagrams(vector& strs) { - std::unordered_map> hashed_annograms; +// Function to group anagrams together +std::vector> GroupAnagrams(const std::vector& words) { + // Create a map where the keys are sorted strings of words and the values are lists of words + // that have the same sorted string. + std::unordered_map> anagrams; - for (const string str: strs) { - string sorted_letters = sort_letters(str); - if (hashed_annograms.find(sorted_letters) == hashed_annograms.end()) { - hashed_annograms[sorted_letters] = vector(); - } - hashed_annograms[sorted_letters].emplace_back(str); - } + // Iterate through the words + for (const std::string& word : words) { + // Get the sorted string for the word + std::string sortedWord = sortWord(word); - vector> result; - result.reserve(hashed_annograms.size()); - for (const auto kv: hashed_annograms) { - result.emplace_back(kv.second); - } - - return result; + // Add the word to the list of words associated with the sorted string in the map + anagrams[sortedWord].push_back(word); } -private: - string sort_letters(string input) { - vector chars; - chars.reserve(input.size()); - for (auto c: input) { - chars.emplace_back(c); - } - sort(chars.begin(), chars.end()); - string result(chars.begin(), chars.end()); - return result; + // Create a vector of vectors, where each inner vector contains all the anagrams of a word in the original list + std::vector> result; + for (const auto& pair : anagrams) { + result.push_back(pair.second); } -}; + + // Return the vector of vectors + return result; +} + +int main() { + // Example usage + std::vector words = { "eat", "tea", "tan", "ate", "nat", "bat" }; + std::vector> groupedAnagrams = GroupAnagrams(words); + + // Print the grouped anagrams + for (const std::vector& group : groupedAnagrams) { + for (const std::string& word : group) { + std::cout << word << " "; + } + std::cout << std::endl; + } + + return 0; +} From 3d950202f2cb8724b41d76176de18abaa12dfb79 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:49:27 +0530 Subject: [PATCH 1613/1894] update group anagrams in python --- Strings/group_anagrams.py | 91 +++++++++++++++++++++++++-------------- 1 file changed, 58 insertions(+), 33 deletions(-) diff --git a/Strings/group_anagrams.py b/Strings/group_anagrams.py index d114cc3f..82eb2e02 100644 --- a/Strings/group_anagrams.py +++ b/Strings/group_anagrams.py @@ -1,33 +1,58 @@ -# Given an array of strings strs, group the anagrams together. You can return the answer in any order. - -# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. - -# Example 1: -# Input: strs = ["eat","tea","tan","ate","nat","bat"] -# Output: [["bat"],["nat","tan"],["ate","eat","tea"]] - -# Example 2: -# Input: strs = [""] -# Output: [[""]] - -# Example 3: -# Input: strs = ["a"] -# Output: [["a"]] -# Approach: -# 1. Go through the list of words -# 2. Sort each word. All annograms of the word would look the same being sorted. -# 3. Find matching bucket in map and put the word to it -# 4. When finished, convert the map to vector of vectors and return it - - - -class Solution: - def groupAnagrams(self,strs): - result = {} - for i in strs: - x = "".join(sorted(i)) - if x in result: - result[x].append(i) - else: - result[x] = [i] - return list(result.values()) \ No newline at end of file +''' + Group Anagrams + + Sample Input: = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"] + Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]] + + Explanation: + + The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging + the letters of another word or phrase. + + The function first defines two functions: GroupAnagrams and sortWord. The GroupAnagrams function takes a list of words + as input and returns a list of lists, where each inner list contains all the anagrams of a word in the original list. + The sortWord function takes a word as input and returns a string that contains the word's letters in sorted order. + + The GroupAnagrams function works by first creating a map where the keys are sorted strings of words and the values are + lists of words that have the same sorted string. Then, the function iterates through the list of words, calling the + sortWord function to get the sorted string for each word. The function then adds the word to the list of words associated with the sorted string in the map. Finally, the function iterates through the map, adding each list of words to a list of lists. + + The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort + the byte array. The function then returns a string that contains the sorted byte array. + + O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is the length of the longest word + +''' +from typing import List +from collections import defaultdict + +def sortWord(word: str) -> str: + # Sort the characters in the word and return the sorted string + return ''.join(sorted(word)) + +def GroupAnagrams(words: List[str]) -> List[List[str]]: + # Create a defaultdict where the keys are sorted strings of words and the values are lists of words + # that have the same sorted string. + anagrams = defaultdict(list) + + # Iterate through the words + for word in words: + # Get the sorted string for the word + sortedWord = sortWord(word) + + # Add the word to the list of words associated with the sorted string in the defaultdict + anagrams[sortedWord].append(word) + + # Create a list of lists, where each inner list contains all the anagrams of a word in the original list + result = list(anagrams.values()) + + # Return the list of lists + return result + +# Example usage +words = ["eat", "tea", "tan", "ate", "nat", "bat"] +groupedAnagrams = GroupAnagrams(words) + +# Print the grouped anagrams +for group in groupedAnagrams: + print(group) From fbc3c563d7e28633860825b37d05a4daeebb6e04 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:50:36 +0530 Subject: [PATCH 1614/1894] update group anagrams --- Strings/group_anagrams.js | 83 +++++++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 30 deletions(-) diff --git a/Strings/group_anagrams.js b/Strings/group_anagrams.js index 3159e6df..7d524343 100644 --- a/Strings/group_anagrams.js +++ b/Strings/group_anagrams.js @@ -1,39 +1,62 @@ -/* Given an array of strings strs, group the anagrams together. You can return the answer in any order. +/* + Group Anagrams - An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + Sample Input: = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"] + Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]] - Example 1: - Input: strs = ["eat","tea","tan","ate","nat","bat"] - Output: [["bat"],["nat","tan"],["ate","eat","tea"]] + Explanation: - Example 2: - Input: strs = [""] - Output: [[""]] + The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging + the letters of another word or phrase. - Example 3: - Input: strs = ["a"] - Output: [["a"]] + The function first defines two functions: GroupAnagrams and sortWord. The GroupAnagrams function takes a list of words + as input and returns a list of lists, where each inner list contains all the anagrams of a word in the original list. + The sortWord function takes a word as input and returns a string that contains the word's letters in sorted order. + + The GroupAnagrams function works by first creating a map where the keys are sorted strings of words and the values are + lists of words that have the same sorted string. Then, the function iterates through the list of words, calling the + sortWord function to get the sorted string for each word. The function then adds the word to the list of words associated with the sorted string in the map. Finally, the function iterates through the map, adding each list of words to a list of lists. + + The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort + the byte array. The function then returns a string that contains the sorted byte array. + + O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is the length of the longest word - - * @param {string[]} strs - * @return {string[][]} */ -// Approach: -// 1. Go through the list of words -// 2. Sort each word. All annograms of the word would look the same being sorted. -// 3. Find matching bucket in map and put the word to it -// 4. When finished, convert the map to vector of vectors and return it - -function groupAnagrams(strs) { - let result = {}; - - for (let i of strs) { - let anagram = i.split("").sort().join(""); - if (result[anagram]) { - result[anagram].push(i); - } else { - result[anagram] = [i]; +function sortWord(word) { + // Sort the characters in the word and return the sorted string + return word.split("").sort().join(""); +} + +function groupAnagrams(words) { + // Create an object where the keys are sorted strings of words and the values are arrays of words + // that have the same sorted string. + const anagrams = {}; + + // Iterate through the words + for (const word of words) { + // Get the sorted string for the word + const sortedWord = sortWord(word); + + // Add the word to the array associated with the sorted string in the object + if (!anagrams[sortedWord]) { + anagrams[sortedWord] = []; } + anagrams[sortedWord].push(word); } - return Object.values(result); + + // Create an array of arrays, where each inner array contains all the anagrams of a word in the original array + const result = Object.values(anagrams); + + // Return the array of arrays + return result; +} + +// Example usage +const words = ["eat", "tea", "tan", "ate", "nat", "bat"]; +const groupedAnagrams = groupAnagrams(words); + +// Print the grouped anagrams +for (const group of groupedAnagrams) { + console.log(group); } From 1ae5113d560c9b67d31a5fc14f681ec62f443960 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 11 Jul 2023 23:51:53 +0530 Subject: [PATCH 1615/1894] update group anagrams in java --- Strings/group_anagrams.java | 103 ++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 39 deletions(-) diff --git a/Strings/group_anagrams.java b/Strings/group_anagrams.java index a07b1a33..64d4dbd3 100644 --- a/Strings/group_anagrams.java +++ b/Strings/group_anagrams.java @@ -1,55 +1,80 @@ -/*Given an array of strings strs, group the anagrams together. You can return the answer in any order. +/* + Group Anagrams -An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + Sample Input: = ["yo", "act", "flop", "tac", "foo", "cat", "oy", "olfp"] + Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"], ["foo"]] - + Explanation: -Example 1: + The code snippet is a function that groups anagrams together. An anagram is a word or phrase formed by rearranging + the letters of another word or phrase. -Input: strs = ["eat","tea","tan","ate","nat","bat"] -Output: [["bat"],["nat","tan"],["ate","eat","tea"]] -Example 2: + The function first defines two functions: GroupAnagrams and sortWord. The GroupAnagrams function takes a list of words + as input and returns a list of lists, where each inner list contains all the anagrams of a word in the original list. + The sortWord function takes a word as input and returns a string that contains the word's letters in sorted order. -Input: strs = [""] -Output: [[""]] -Example 3: + The GroupAnagrams function works by first creating a map where the keys are sorted strings of words and the values are + lists of words that have the same sorted string. Then, the function iterates through the list of words, calling the + sortWord function to get the sorted string for each word. The function then adds the word to the list of words associated with the sorted string in the map. Finally, the function iterates through the map, adding each list of words to a list of lists. -Input: strs = ["a"] -Output: [["a"]] -*/ -// Approach: -// 1. Go through the list of words -// 2. Sort each word. All annograms of the word would look the same being sorted. -// 3. Find matching bucket in map and put the word to it -// 4. When finished, convert the map to vector of vectors and return it + The sortWord function works by converting the word to a byte array and then calling the sort.Slice function to sort + the byte array. The function then returns a string that contains the sorted byte array. -package Strings; + O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is the length of the longest word -import java.util.*; +*/ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; -public class groupAnagram { +public class GroupAnagrams { + public List> groupAnagrams(String[] words) { + // Create a map where the keys are sorted strings of words and the values are lists of words + // that have the same sorted string. + Map> anagrams = new HashMap<>(); - public List> groupAnagrams(String[] strs) { + // Iterate through the words + for (String word : words) { + // Get the sorted string for the word + String sortedWord = sortWord(word); - HashMap> map = new HashMap<>(); - - for(int i = 0 ; i < strs.length ; i++) { - char[] charArr = strs[i].toCharArray(); - Arrays.sort(charArr); - String string = new String(charArr); - - if(!map.containsKey(string)){ - map.put(string, new ArrayList<>()); + // Add the word to the list of words associated with the sorted string in the map + if (!anagrams.containsKey(sortedWord)) { + anagrams.put(sortedWord, new ArrayList<>()); } - map.get(string).add(strs[i]); - } - - List> result = new ArrayList<>(); - - for(String st : map.keySet()) { - List list = map.get(st); - result.add(list); + anagrams.get(sortedWord).add(word); } + + // Create a list of lists, where each inner list contains all the anagrams of a word in the original array + List> result = new ArrayList<>(anagrams.values()); + + // Return the list of lists return result; } + + // Helper method to sort the characters in a word and return the sorted string + private String sortWord(String word) { + // Convert the word to a character array + char[] wordChars = word.toCharArray(); + + // Sort the character array + Arrays.sort(wordChars); + + // Return the sorted string + return new String(wordChars); + } + + public static void main(String[] args) { + // Example usage + String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"}; + GroupAnagrams groupAnagrams = new GroupAnagrams(); + List> groupedAnagrams = groupAnagrams.groupAnagrams(words); + + // Print the grouped anagrams + for (List group : groupedAnagrams) { + System.out.println(group); + } + } } From c9604bd094d78f76d9d0297f144753a62ca398dd Mon Sep 17 00:00:00 2001 From: Gal Fudim <32942415+galfudim@users.noreply.github.com> Date: Tue, 11 Jul 2023 20:56:17 +0000 Subject: [PATCH 1616/1894] Create: linked_list_middle.go to solve https://leetcode.com/problems/middle-of-the-linked-list/description/ --- Linked List/linked_list_middle.go | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Linked List/linked_list_middle.go diff --git a/Linked List/linked_list_middle.go b/Linked List/linked_list_middle.go new file mode 100644 index 00000000..8542271b --- /dev/null +++ b/Linked List/linked_list_middle.go @@ -0,0 +1,39 @@ +/** + * Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. + * + * Example #1: + * Input: head = [1,2,3,4,5] + * Output: [3,4,5] + * Explanation: The middle node of the list is node 3. + * + * Example #2: + * Input: head = [1,2,3,4,5,6] + * Output: [4,5,6] + * Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. + * + * Constraints: + * The number of nodes in the list is in the range [1, 100]. + * 1 <= Node.val <= 100 + * + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + * + * Solution: to find the middle of a linked list, we can use two pointers ("slow" and "fast"). They should both start at head. + * While traversing the list, we move the slow pointer one node at a time and the fast pointer two nodes at a time. + * When the fast pointer reaches the end of the linked list, the slow pointer will be pointing to the middle node. + * + * Time complexity: O(n), space complexity: O(n) + */ + func middleNode(head *ListNode) *ListNode { + slow, fast := head, head + + for (fast != nil && fast.Next != nil) { + slow = slow.Next + fast = fast.Next.Next + } + + return slow +} From 29a7ef1f69dc45dd59748436660af2dcefcb6f5b Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 12 Jul 2023 19:23:10 +0530 Subject: [PATCH 1617/1894] Create DiamondPattern.java --- Patterns/DiamondPattern.java | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Patterns/DiamondPattern.java diff --git a/Patterns/DiamondPattern.java b/Patterns/DiamondPattern.java new file mode 100644 index 00000000..e712a138 --- /dev/null +++ b/Patterns/DiamondPattern.java @@ -0,0 +1,61 @@ +/* +Approach: +1. We take the number of rows for the diamond pattern as input. +2. We start by printing the upper half of the diamond pattern. In each row, we first print the required spaces and then print the required number of asterisks. +3. After the upper half, we print the lower half of the diamond pattern using a similar logic. + +Time Complexity: The time complexity of this code is O(n^2) as we use nested loops to print the pattern. + +Space Complexity: The space complexity of this code is O(1) as we are not using any additional data structures. + +Sample Input: 5 + +Sample Output: + * + *** + ***** + ******* +********* + ******* + ***** + *** + * +*/ + +public class DiamondPattern { + + public static void main(String[] args) { + int n = 5; // Specify the number of rows for the diamond pattern + printDiamondPattern(n); + } + + public static void printDiamondPattern(int n) { + if (n <= 0) { + System.out.println("Number of rows should be positive."); + return; + } + + // Printing upper half of the diamond pattern + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n - i; j++) { + System.out.print(" "); + } + for (int k = 1; k <= i * 2 - 1; k++) { + System.out.print("*"); + } + System.out.println(); + } + + // Printing lower half of the diamond pattern + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= n - i; j++) { + System.out.print(" "); + } + for (int k = 1; k <= i * 2 - 1; k++) { + System.out.print("*"); + } + System.out.println(); + } + } + + From 8ecdc7ed0f584a99b602e6222aac31a3c0f374e3 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 12 Jul 2023 19:27:11 +0530 Subject: [PATCH 1618/1894] Create diamond_pattern.py --- Patterns/diamond_pattern.py | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Patterns/diamond_pattern.py diff --git a/Patterns/diamond_pattern.py b/Patterns/diamond_pattern.py new file mode 100644 index 00000000..c3850abe --- /dev/null +++ b/Patterns/diamond_pattern.py @@ -0,0 +1,52 @@ +''' +Approach: +- The code above prints a diamond pattern with `n` rows. The approach used is to iterate through each row of the diamond pattern, calculate the number of spaces and asterisks in each row based on the current row number, and then print the spaces and asterisks accordingly. +- In the upper half of the diamond, the number of spaces decreases by 1 and the number of asterisks increases by 2 in each row. In the lower half of the diamond, the number of spaces increases by 1 and the number of asterisks decreases by 2 in each row. + +Sample input: `4`, the function `print_diamond_pattern(4)` + +Sample Output: + * + *** + ***** +******* + ***** + *** + * + +Time Complexity: The time complexity of this code is O(n^2), where n is the input parameter representing the number of rows in the diamond pattern. This is because we need to loop through each row and perform a constant number of operations for each row. + +Space Complexity: The space complexity of this code is O(1), as we are not using any additional data structures whose space requirements depend on the input size. + +NOTE: This code assumes that the input `n` is a positive integer greater than 0. It does not handle invalid inputs or edge cases where `n` is negative or zero. +''' + +def print_diamond_pattern(n): + # Calculate the number of rows in the diamond pattern + num_rows = 2 * n - 1 + + # Iterate through each row of the diamond pattern + for i in range(num_rows): + + # Calculate the number of spaces and asterisks in each row + if i < n: # Upper half of the diamond + num_spaces = n - i - 1 + num_asterisks = 2 * i + 1 + else: # Lower half of the diamond + num_spaces = i - n + 1 + num_asterisks = 2 * (num_rows - i) - 1 + + # Print the spaces before the asterisks + for _ in range(num_spaces): + print(" ", end="") + + # Print the asterisks + for _ in range(num_asterisks): + print("*", end="") + + # Move to the next line + print() + +# Testing the function with a sample input +print_diamond_pattern(4) + From b55e9787c36cb1337e392897f00133ad3d71a991 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 12 Jul 2023 19:29:55 +0530 Subject: [PATCH 1619/1894] Create DiamondPattern.cpp --- Patterns/DiamondPattern.cpp | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Patterns/DiamondPattern.cpp diff --git a/Patterns/DiamondPattern.cpp b/Patterns/DiamondPattern.cpp new file mode 100644 index 00000000..fad0b218 --- /dev/null +++ b/Patterns/DiamondPattern.cpp @@ -0,0 +1,78 @@ +/* +Approach: +1. We use two nested loops to iterate through each row and each column of the diamond pattern. +2. The first loop is used to iterate through the rows of the diamond. It starts from 0 and goes up to n-1 rows for the upper half of the diamond. +3. Inside the first loop, we use a nested loop to print spaces before the pattern of each row. The number of spaces decreases by 1 as we move down the rows. +4. Again inside the first loop, we use another nested loop to print the pattern of asterisks (*) for each row. The number of asterisks increases by 2 as we move down the rows. +5. After printing each row, we move to the next line using `cout << endl;`. +6. Now, we need to print the lower half of the diamond. For this, we use another loop that starts from n-2 (as we have already printed the top-most row in the first loop) and moves down to 0 rows. +7. Inside this loop, we print the spaces and pattern the same way as in the first loop. +8. Finally, we have the main function where we take input from the user for the number of rows and call the `printDiamondPattern` function. + +Time Complexity: O(n^2) - as we use nested loops to iterate through each row and each column of the diamond pattern. + +Space Complexity: O(1) - as we only use a constant amount of additional space for variables. + +Sample Input: +Enter the number of rows: 5 + +Sample Output: + * + *** + ***** + ******* +********* + ******* + ***** + *** + * +*/ + + +#include +using namespace std; + +void printDiamondPattern(int n) { + // Print the upper half of the diamond + for (int i = 0; i < n; i++) { + // Print spaces before the pattern for each row + for (int j = 0; j < n - i - 1; j++) { + cout << " "; + } + + // Print the pattern for each row + for (int j = 0; j < 2 * i + 1; j++) { + cout << "*"; + } + + cout << endl; // Move to the next line + } + + // Print the lower half of the diamond + for (int i = n-2; i >= 0; i--) { + // Print spaces before the pattern for each row + for (int j = 0; j < n - i - 1; j++) { + cout << " "; + } + + // Print the pattern for each row + for (int j = 0; j < 2 * i + 1; j++) { + cout << "*"; + } + + cout << endl; // Move to the next line + } +} + +int main() { + int n; + cout << "Enter the number of rows: "; + cin >> n; + + printDiamondPattern(n); + + return 0; +} + + + From 54a511b1a4f6e6f57622ed5c0532e300149ea2f4 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Wed, 12 Jul 2023 19:32:47 +0530 Subject: [PATCH 1620/1894] Create DiamondPattern.go --- Patterns/DiamondPattern.go | 74 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Patterns/DiamondPattern.go diff --git a/Patterns/DiamondPattern.go b/Patterns/DiamondPattern.go new file mode 100644 index 00000000..629f7389 --- /dev/null +++ b/Patterns/DiamondPattern.go @@ -0,0 +1,74 @@ +/* +In this code, the user enters a number, and the program will print a diamond pattern with that number as the widest point. + +Explanation of the approach: +- We define two helper functions: `printSpaces` and `printStars`. These functions are used to print the desired spaces and stars, respectively. +- The `printDiamondPattern` function takes an integer `n` as input. It prints the upper half and lower half of the diamond pattern using a combination of spaces and stars. +- In the upper half, the number of spaces in each row decreases by 1, while the number of stars increases by 2. +- In the lower half, the number of spaces in each row increases by 1, while the number of stars decreases by 2. +- The `main` function prompts the user to enter a number and calls the `printDiamondPattern` function to print the diamond pattern. + +Time Complexity: The time complexity of this code is O(n^2), where n is the number entered by the user. This is because there are two nested loops used to print the diamond pattern. + +Space Complexity: The space complexity of this code is O(1), as there are no additional data structures used that depend on the input size. + +Sample Input: +Enter a number for the widest point of the diamond: 5 + +Sample Output: + * + *** + ***** + ******* +********* + ******* + ***** + *** + * + +*/ + + +package main + +import ( + "fmt" + "math" +) + +func printSpaces(num int) { + for i := 1; i <= num; i++ { + fmt.Print(" ") + } +} + +func printStars(num int) { + for i := 1; i <= num; i++ { + fmt.Print("* ") + } +} + +func printDiamondPattern(n int) { + // upper half of the diamond + for i := 0; i < n; i++ { + printSpaces(n - i - 1) + printStars(2*i + 1) + fmt.Println() + } + + // lower half of the diamond + for i := 0; i < n-1; i++ { + printSpaces(i + 1) + printStars(2*(n-i-1) - 1) + fmt.Println() + } +} + +func main() { + var num int + fmt.Print("Enter a number for the widest point of the diamond: ") + fmt.Scan(&num) + + printDiamondPattern(num) +} + From e2b7fb4407997119954b23a9077e8021020fdc45 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Jul 2023 22:59:01 +0530 Subject: [PATCH 1621/1894] rename and move to strings --- .../case_specific_sorting_of_strings.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename case-specific sorting of strings(gfg).cpp => Strings/case_specific_sorting_of_strings.cpp (100%) diff --git a/case-specific sorting of strings(gfg).cpp b/Strings/case_specific_sorting_of_strings.cpp similarity index 100% rename from case-specific sorting of strings(gfg).cpp rename to Strings/case_specific_sorting_of_strings.cpp From 89aa720d3a14ea21548ba1f78a518a8d0d403c85 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 12 Jul 2023 22:59:35 +0530 Subject: [PATCH 1622/1894] rename --- Patterns/{DiamondPattern.cpp => diamond_pattern.cpp} | 0 Patterns/{DiamondPattern.go => diamond_pattern.go} | 0 Patterns/{DiamondPattern.java => diamond_pattern.java} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Patterns/{DiamondPattern.cpp => diamond_pattern.cpp} (100%) rename Patterns/{DiamondPattern.go => diamond_pattern.go} (100%) rename Patterns/{DiamondPattern.java => diamond_pattern.java} (100%) diff --git a/Patterns/DiamondPattern.cpp b/Patterns/diamond_pattern.cpp similarity index 100% rename from Patterns/DiamondPattern.cpp rename to Patterns/diamond_pattern.cpp diff --git a/Patterns/DiamondPattern.go b/Patterns/diamond_pattern.go similarity index 100% rename from Patterns/DiamondPattern.go rename to Patterns/diamond_pattern.go diff --git a/Patterns/DiamondPattern.java b/Patterns/diamond_pattern.java similarity index 100% rename from Patterns/DiamondPattern.java rename to Patterns/diamond_pattern.java From a4a410e770fac230693d4f657f69557b756064ba Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Wed, 12 Jul 2023 23:32:59 +0530 Subject: [PATCH 1623/1894] Create shuffle_array.java >>added time and space complexity >>added sample i/o --- Arrays/shuffle_array.java | 110 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Arrays/shuffle_array.java diff --git a/Arrays/shuffle_array.java b/Arrays/shuffle_array.java new file mode 100644 index 00000000..d87b68c4 --- /dev/null +++ b/Arrays/shuffle_array.java @@ -0,0 +1,110 @@ +// + +Input: Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. +Implement the Solution class: +Solution(int[] nums) Initializes the object with the integer array nums. +int[] reset() Resets the array to its original configuration and returns it. +int[] shuffle() Returns a random shuffling of the array. + +Example: +Input +["Solution", "shuffle", "reset", "shuffle"] +[[[1, 2, 3]], [], [], []] +Output +[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] + +Explanation +Solution solution = new Solution([1, 2, 3]); +solution.shuffle(); // Shuffle the array [1,2,3] and return its result. + // Any permutation of [1,2,3] must be equally likely to be returned. + // Example: return [3, 1, 2] +solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] +solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] + +Time Complexity:O(n) +Space Complexity:O(n) + +Explanation: In the shuffle function +>>int[] rand = Arrays.copyOf(nums, nums.length); creates a copy of the original array nums using Arrays.copyOf() method. +This copy, called rand, will be shuffled to avoid modifying the original array. + +>>The for loop iterates over each element of the array. The loop variable i represents the current index being processed. + +>>Inside the loop, int r = (int) (Math.random() * (i+1)); generates a random index r between 0 and i, inclusive. + This index r will be used to swap elements in the rand array. + +>>The lines int temp = rand[i];, rand[i] = rand[r];, and rand[r] = temp; perform the swapping of elements. + The element at index i is temporarily stored in temp, then the element at index r is moved to index i, and finally, the element stored in temp is moved to index r. This swapping step ensures a random shuffling of the elements. + +>>After the loop completes, the shuffled array rand is returned. + +>>The Fisher-Yates algorithm used in the shuffle() method ensures that each possible permutation of the array has an equal probability of occurring. + By swapping elements randomly, it guarantees a uniform and unbiased shuffling of the array. + + // + + import java.util.Arrays; +import java.util.Scanner; + +public class Solution { + private int[] nums; + + public Solution(int[] nums) { + this.nums = nums; + } + + public int[] reset() { + return nums; + } + + public int[] shuffle() { + int[] rand = Arrays.copyOf(nums, nums.length); + for (int i = 0; i < nums.length; i++) { + int r = (int) (Math.random() * (i+1)); + int temp = rand[i]; + rand[i] = rand[r]; + rand[r] = temp; + } + return rand; + } + + public static void main(String[] args) { + int[] nums = {1, 2, 3, 4, 5}; + + Solution solution = new Solution(nums); + + Scanner scanner = new Scanner(System.in); + + while (true) { + System.out.println("Enter 1 to reset the array, 2 to shuffle the array, or 0 to exit:"); + int choice = scanner.nextInt(); + + if (choice == 1) { + int[] resetArray = solution.reset(); + System.out.println("Reset Array:"); + printArray(resetArray); + } else if (choice == 2) { + int[] shuffledArray = solution.shuffle(); + System.out.println("Shuffled Array:"); + printArray(shuffledArray); + } else if (choice == 0) { + System.out.println("Exiting..."); + break; + } else { + System.out.println("Invalid choice. Please try again."); + } + } + + scanner.close(); + } + + public static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } +} + + + From 68d910009b8b90083d074fe99e3b14a2bb3563f2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:00:07 +0530 Subject: [PATCH 1624/1894] rename file --- search_2d_sorted_array.py | 77 --------------------------------------- 1 file changed, 77 deletions(-) delete mode 100644 search_2d_sorted_array.py diff --git a/search_2d_sorted_array.py b/search_2d_sorted_array.py deleted file mode 100644 index f5117b30..00000000 --- a/search_2d_sorted_array.py +++ /dev/null @@ -1,77 +0,0 @@ -''' -Date:28/6/23 -About:Search in 2D sorted array in Python - -Input: -You are given an m x n integer matrix matrix with the following two properties: -Each row is sorted in non-decreasing order. -The first integer of each row is greater than the last integer of the previous row. -Given an integer target, return true if target is in matrix or false otherwise. - -Time Complexity: -You must write a solution in O(log(m * n)) time complexity. -Space Complexity:O(1) - -//Example 1: -Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 -Output: true -//Example 2: -Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 -Output: false - -//Explanation -The method takes two parameters: matrix, which represents the sorted matrix, and target, which is the value we want to find in the matrix. - -The code initializes variables nRows and nCols to store the number of rows and columns in the matrix, respectively. - -The starting position for the search is set to the bottom-left corner of the matrix (row = nRows - 1, col = 0). - -The code enters a while loop that continues as long as the current row index (row) is within the bounds of the matrix (0 to nRows - 1 -and the current column index (col) is within the bounds of the matrix (0 to nCols - 1). - -Inside the loop, the code retrieves the value at the current position in the matrix (val = matrix[row][col]). - -If the current value (val) == value, the method returns True, indicating that the target is found in the matrix. - -If the current value (val) < target value, it means the target can only be found in the rows above the current row. -Therefore, the column index (col) is incremented to move to the next column. - -If the current value (val) >target value, it means the target can only be found in the columns to the left of the current column. -Therefore, the row index (row) is decremented to move to the previous row. - -If the loop completes without finding the target value, the method returns False. - -''' -class Solution(object): - def searchMatrix(self, matrix, target): - nRows = len(matrix) - nCols = len(matrix[0]) - row = nRows - 1 - col = 0 - while 0 <= row < nRows and 0 <= col < nCols: - val = matrix[row][col] - if val == target: - return True - elif val < target: - col += 1 - else: - row -= 1 - return False - - -# Create an instance of the Solution class -solution = Solution() - -# Define the matrix and target value -matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] -target = 3 - -# Call the searchMatrix method and print the result -result = solution.searchMatrix(matrix, target) -print(result) - - - - - - From eb0f2689693c4432adb69b4e152dde4d25229c7a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:00:19 +0530 Subject: [PATCH 1625/1894] move to 2d directory --- .../searching_in_sorted_array.py | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 2D Arrays (Matrix)/searching_in_sorted_array.py diff --git a/2D Arrays (Matrix)/searching_in_sorted_array.py b/2D Arrays (Matrix)/searching_in_sorted_array.py new file mode 100644 index 00000000..f5117b30 --- /dev/null +++ b/2D Arrays (Matrix)/searching_in_sorted_array.py @@ -0,0 +1,77 @@ +''' +Date:28/6/23 +About:Search in 2D sorted array in Python + +Input: +You are given an m x n integer matrix matrix with the following two properties: +Each row is sorted in non-decreasing order. +The first integer of each row is greater than the last integer of the previous row. +Given an integer target, return true if target is in matrix or false otherwise. + +Time Complexity: +You must write a solution in O(log(m * n)) time complexity. +Space Complexity:O(1) + +//Example 1: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true +//Example 2: +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false + +//Explanation +The method takes two parameters: matrix, which represents the sorted matrix, and target, which is the value we want to find in the matrix. + +The code initializes variables nRows and nCols to store the number of rows and columns in the matrix, respectively. + +The starting position for the search is set to the bottom-left corner of the matrix (row = nRows - 1, col = 0). + +The code enters a while loop that continues as long as the current row index (row) is within the bounds of the matrix (0 to nRows - 1 +and the current column index (col) is within the bounds of the matrix (0 to nCols - 1). + +Inside the loop, the code retrieves the value at the current position in the matrix (val = matrix[row][col]). + +If the current value (val) == value, the method returns True, indicating that the target is found in the matrix. + +If the current value (val) < target value, it means the target can only be found in the rows above the current row. +Therefore, the column index (col) is incremented to move to the next column. + +If the current value (val) >target value, it means the target can only be found in the columns to the left of the current column. +Therefore, the row index (row) is decremented to move to the previous row. + +If the loop completes without finding the target value, the method returns False. + +''' +class Solution(object): + def searchMatrix(self, matrix, target): + nRows = len(matrix) + nCols = len(matrix[0]) + row = nRows - 1 + col = 0 + while 0 <= row < nRows and 0 <= col < nCols: + val = matrix[row][col] + if val == target: + return True + elif val < target: + col += 1 + else: + row -= 1 + return False + + +# Create an instance of the Solution class +solution = Solution() + +# Define the matrix and target value +matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] +target = 3 + +# Call the searchMatrix method and print the result +result = solution.searchMatrix(matrix, target) +print(result) + + + + + + From 6a15c624ce914422e8d680abc03e12f561770a71 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:02:29 +0530 Subject: [PATCH 1626/1894] add one edit --- Strings/one_edit.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Strings/one_edit.go diff --git a/Strings/one_edit.go b/Strings/one_edit.go new file mode 100644 index 00000000..24f71c07 --- /dev/null +++ b/Strings/one_edit.go @@ -0,0 +1,34 @@ +package main + +func OneEdit(stringOne string, stringTwo string) bool { + lengthOne := len(stringOne) + lengthTwo := len(stringTwo) + if abs(lengthOne-lengthTwo) > 1 { + return false + } + for i := 0; i < min(lengthOne, lengthTwo); i++ { + if stringOne[i] != stringTwo[i] { + if lengthOne > lengthTwo { + return stringOne[i+1:] == stringTwo[i:] + } else if lengthTwo > lengthOne { + return stringTwo[i+1:] == stringOne[i:] + } else { + return stringOne[i+1:] == stringTwo[i+1:] + } + } + } + return true +} + +func abs(a int) int { + if a < 0 { + return -a + } + return a +} +func min(a, b int) int { + if a < b { + return a + } + return b +} From c7635b182cf3dcc60eb245622479b35ab749825c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:03:44 +0530 Subject: [PATCH 1627/1894] add comments --- Strings/one_edit.go | 63 ++++++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 24f71c07..564f0b1a 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -1,34 +1,43 @@ -package main - func OneEdit(stringOne string, stringTwo string) bool { - lengthOne := len(stringOne) - lengthTwo := len(stringTwo) - if abs(lengthOne-lengthTwo) > 1 { - return false - } - for i := 0; i < min(lengthOne, lengthTwo); i++ { - if stringOne[i] != stringTwo[i] { - if lengthOne > lengthTwo { - return stringOne[i+1:] == stringTwo[i:] - } else if lengthTwo > lengthOne { - return stringTwo[i+1:] == stringOne[i:] - } else { - return stringOne[i+1:] == stringTwo[i+1:] - } - } - } - return true + lengthOne := len(stringOne) + lengthTwo := len(stringTwo) + + // Check the difference in lengths between the two strings. + // If the difference is greater than 1, it is not possible to make one edit to make them equal. + if abs(lengthOne - lengthTwo) > 1 { + return false + } + + // Traverse the strings until the shorter one is fully traversed or an unequal character is found. + for i := 0; i < min(lengthOne, lengthTwo); i++ { + // If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. + if stringOne[i] != stringTwo[i] { + // Check the remaining characters in the longer string compared to the remaining characters in the shorter string. + // Return true if they match, indicating they are one edit away. + if lengthOne > lengthTwo { + return stringOne[i+1:] == stringTwo[i:] + } else if lengthTwo > lengthOne { + return stringTwo[i+1:] == stringOne[i:] + } else { + return stringOne[i+1:] == stringTwo[i+1:] + } + } + } + + // If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. + return true } func abs(a int) int { - if a < 0 { - return -a - } - return a + if a < 0 { + return -a + } + return a } + func min(a, b int) int { - if a < b { - return a - } - return b + if a < b { + return a + } + return b } From 0ce29ecb5be74e20aa3aa3f14b843732b21019d1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:05:21 +0530 Subject: [PATCH 1628/1894] add question --- Strings/one_edit.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 564f0b1a..725e6dc3 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -1,3 +1,15 @@ +/* + You're given two strings stringone and stringtwo. Write a function that determines if these + two strings can be made equal using only one edit. + + + There are 3 possible edits: + Replace: One character in one string is swapped for a different character. + Add:: One character is added at any index in one string. + Remove: One character is removed at any index in one string. + + +*/ func OneEdit(stringOne string, stringTwo string) bool { lengthOne := len(stringOne) lengthTwo := len(stringTwo) From a01e3cd6092b16be6aa07228555caf5eff1f17d7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:06:21 +0530 Subject: [PATCH 1629/1894] add explanation --- Strings/one_edit.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 725e6dc3..39057493 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -7,6 +7,30 @@ Replace: One character in one string is swapped for a different character. Add:: One character is added at any index in one string. Remove: One character is removed at any index in one string. + + Explanation: + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. + + The `OneEdit` function takes two strings as input and returns a boolean indicating whether + they are one edit away. Here's the breakdown of the algorithm: + + 1. Calculate the lengths of the two strings. + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + not possible to make one edit to make the strings equal. + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + found. + 4. If an unequal character is found, check the remaining portion of the strings to determine + if they are still one edit away. + 5. Check the remaining characters in the longer string compared to the remaining characters + in the shorter string. + 6. Return `true` if the remaining portions match, indicating they are one edit away. + 7. If the loop completes without finding any unequal characters, the strings are either + identical or differ only in length by 1, which means they are one edit away. + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + and minimum of two integers, respectively. + + The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. */ From 6bfcad7f71b770dc7eea7bdc7bec8528e88d970b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:07:07 +0530 Subject: [PATCH 1630/1894] add sample io --- Strings/one_edit.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 39057493..8f90d4f3 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -8,6 +8,10 @@ Add:: One character is added at any index in one string. Remove: One character is removed at any index in one string. + Sample Input: StringOne: alaska StringTwo: aloska + Output: True + + Explanation: The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. From 3f3ad07078ef92aa0133778903e1a599e1eed26b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:07:24 +0530 Subject: [PATCH 1631/1894] add time and space --- Strings/one_edit.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 8f90d4f3..06c814d2 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -35,6 +35,8 @@ and minimum of two integers, respectively. The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. + + O(n) time | O(1) space - where n is the length of the shorter string */ From 9d573ba425e2647e46fe1f0cab3342a8446b0d4b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 13 Jul 2023 23:09:10 +0530 Subject: [PATCH 1632/1894] add oneedit in python --- Strings/one_edit.go | 26 ++++++++-------- Strings/one_edit.py | 75 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 12 deletions(-) create mode 100644 Strings/one_edit.py diff --git a/Strings/one_edit.go b/Strings/one_edit.go index 06c814d2..59505eef 100644 --- a/Strings/one_edit.go +++ b/Strings/one_edit.go @@ -1,8 +1,8 @@ /* - You're given two strings stringone and stringtwo. Write a function that determines if these + You're given two strings stringone and stringtwo. Write a function that determines if these two strings can be made equal using only one edit. - + There are 3 possible edits: Replace: One character in one string is swapped for a different character. Add:: One character is added at any index in one string. @@ -13,33 +13,35 @@ Explanation: - The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. - The `OneEdit` function takes two strings as input and returns a boolean indicating whether + The `OneEdit` function takes two strings as input and returns a boolean indicating whether they are one edit away. Here's the breakdown of the algorithm: 1. Calculate the lengths of the two strings. - 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's not possible to make one edit to make the strings equal. - 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is found. - 4. If an unequal character is found, check the remaining portion of the strings to determine + 4. If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. - 5. Check the remaining characters in the longer string compared to the remaining characters + 5. Check the remaining characters in the longer string compared to the remaining characters in the shorter string. 6. Return `true` if the remaining portions match, indicating they are one edit away. - 7. If the loop completes without finding any unequal characters, the strings are either + 7. If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1, which means they are one edit away. - 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value and minimum of two integers, respectively. The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. O(n) time | O(1) space - where n is the length of the shorter string - - + + */ +package main + func OneEdit(stringOne string, stringTwo string) bool { lengthOne := len(stringOne) lengthTwo := len(stringTwo) diff --git a/Strings/one_edit.py b/Strings/one_edit.py new file mode 100644 index 00000000..9215d1cb --- /dev/null +++ b/Strings/one_edit.py @@ -0,0 +1,75 @@ +''' + You're given two strings stringone and stringtwo. Write a function that determines if these + two strings can be made equal using only one edit. + + + There are 3 possible edits: + Replace: One character in one string is swapped for a different character. + Add:: One character is added at any index in one string. + Remove: One character is removed at any index in one string. + + Sample Input: StringOne: alaska StringTwo: aloska + Output: True + + + Explanation: + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. + + The `OneEdit` function takes two strings as input and returns a boolean indicating whether + they are one edit away. Here's the breakdown of the algorithm: + + 1. Calculate the lengths of the two strings. + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + not possible to make one edit to make the strings equal. + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + found. + 4. If an unequal character is found, check the remaining portion of the strings to determine + if they are still one edit away. + 5. Check the remaining characters in the longer string compared to the remaining characters + in the shorter string. + 6. Return `true` if the remaining portions match, indicating they are one edit away. + 7. If the loop completes without finding any unequal characters, the strings are either + identical or differ only in length by 1, which means they are one edit away. + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + and minimum of two integers, respectively. + + The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. + + O(n) time | O(1) space - where n is the length of the shorter string + +''' +def OneEdit(stringOne, stringTwo): + lengthOne = len(stringOne) + lengthTwo = len(stringTwo) + + # Check the difference in lengths between the two strings. + # If the difference is greater than 1, it is not possible to make one edit to make them equal. + if abs(lengthOne - lengthTwo) > 1: + return False + + # Traverse the strings until the shorter one is fully traversed or an unequal character is found. + for i in range(min(lengthOne, lengthTwo)): + # If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. + if stringOne[i] != stringTwo[i]: + # Check the remaining characters in the longer string compared to the remaining characters in the shorter string. + # Return True if they match, indicating they are one edit away. + if lengthOne > lengthTwo: + return stringOne[i+1:] == stringTwo[i:] + elif lengthTwo > lengthOne: + return stringTwo[i+1:] == stringOne[i:] + else: + return stringOne[i+1:] == stringTwo[i+1:] + + # If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. + return True + +def abs(a): + if a < 0: + return -a + return a + +def min(a, b): + if a < b: + return a + return b From 1f3c4e319d8bd4161c168b6f8ae2870a616e2696 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 14 Jul 2023 23:41:12 +0530 Subject: [PATCH 1633/1894] Create queue_using_stacks.go --- Queue/queue_using_stacks.go | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Queue/queue_using_stacks.go diff --git a/Queue/queue_using_stacks.go b/Queue/queue_using_stacks.go new file mode 100644 index 00000000..874b2e03 --- /dev/null +++ b/Queue/queue_using_stacks.go @@ -0,0 +1,74 @@ +type MyQueue struct { + stack1 []int + stack2 []int +} + +/** Initialize your data structure here. */ +func Constructor() MyQueue { + return MyQueue{} +} + +/** Push element x to the back of queue. */ +func (this *MyQueue) Push(x int) { + this.stack1 = append(this.stack1, x) +} + +/** Removes the element from in front of queue and returns that element. */ +func (this *MyQueue) Pop() int { + if len(this.stack2) == 0 { + this.moveElements() + } + element := this.stack2[len(this.stack2)-1] + this.stack2 = this.stack2[:len(this.stack2)-1] + return element +} + +/** Get the front element. */ +func (this *MyQueue) Peek() int { + if len(this.stack2) == 0 { + this.moveElements() + } + return this.stack2[len(this.stack2)-1] +} + +/** Returns whether the queue is empty. */ +func (this *MyQueue) Empty() bool { + return len(this.stack1) == 0 && len(this.stack2) == 0 +} + +/** Move elements from stack1 to stack2. */ +func (this *MyQueue) moveElements() { + for len(this.stack1) > 0 { + element := this.stack1[len(this.stack1)-1] + this.stack1 = this.stack1[:len(this.stack1)-1] + this.stack2 = append(this.stack2, element) + } +} + +/* + +The MyQueue struct is defined with two slices: stack1 and stack2. stack1 represents the main stack where elements are pushed initially, and stack2 is used to reverse the order of elements for queue operations. + +The Constructor function is a constructor for the MyQueue struct. It initializes an empty MyQueue instance and returns it. + +The Push method takes an integer x and appends it to the stack1 slice, which represents the back of the queue. + +The Pop method removes and returns the element from the front of the queue. It checks if stack2 is empty, and if so, it calls the moveElements method to transfer elements from stack1 to stack2. This ensures that the elements in stack2 are in the correct order for queue operations. The last element of stack2 is then removed and returned as the result. + +The Peek method returns the element at the front of the queue without removing it. It performs the same check as the Pop method to ensure that the elements in stack2 are up to date, and then returns the last element in stack2. + +The Empty method checks if both stack1 and stack2 are empty, indicating whether the queue is empty or not. + +The moveElements method is used to transfer elements from stack1 to stack2 in the correct order. It pops elements from stack1 and appends them to stack2 until stack1 is empty. This ensures that the elements in stack2 are in the reversed order, mimicking the behavior of a queue. +Time Complexity: + +The Push operation has a time complexity of O(1) because it simply appends an element to the stack1 slice. +The Pop operation has an amortized time complexity of O(1). When stack2 is not empty, popping an element is a constant-time operation. If stack2 is empty, the moveElements method is called, which transfers all elements from stack1 to stack2. This transfer operation takes O(n) time, where n is the number of elements in stack1. However, each element is transferred at most twice in total (once from stack1 to stack2 and once from stack2 back to stack1 in future push operations). Therefore, the average time complexity per pop operation is O(1). +The Peek operation has the same amortized time complexity as Pop, which is O(1). +The Empty operation has a time complexity of O(1) because it checks the lengths of both stack1 and stack2 to determine if the queue is empty. +Space Complexity: + +The space complexity of the MyQueue struct is O(n), where n is the number of elements stored in the queue. This includes the space required for the stack1 and stack2 slices. +In the worst case, when all elements are stored in stack1, the space complexity is O(n). However, when elements are transferred from stack1 to stack2, the space complexity remains O(n) because each element is moved and stored only once + +*/ From a839eed7aa6b9d4274342f74f991ca87d3d4a42f Mon Sep 17 00:00:00 2001 From: Anand Date: Sat, 15 Jul 2023 16:42:02 +0530 Subject: [PATCH 1634/1894] Add Recursive Binary Search java Added Binary Search program to find a target with recursion Followed Divide and Conquer Recursive method --- Binary Search/BinarySearchRecursive.java | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Binary Search/BinarySearchRecursive.java diff --git a/Binary Search/BinarySearchRecursive.java b/Binary Search/BinarySearchRecursive.java new file mode 100644 index 00000000..56dceb79 --- /dev/null +++ b/Binary Search/BinarySearchRecursive.java @@ -0,0 +1,48 @@ + +/* + * Problem : Implement Binary Search using Recursion. + * + * RECURSION : Function that calls itself is called recursion. + * + * Algorithm: + * 1) Get an sorted array and a target to be found in the array. + * 2) Find the middle index by dividing the first and last element. + * 3) If the middle element is equal to target , return the mid index. + * 4) If the middle element is greater than the target , in the next recursive call make last element as mid-1 + * 5) If the middle element is smaller than the target , in the next recursive call make first element as mid+1 + * 6) If start is less than end ,ie,if the element not found , return -1. + * + * Time complexity: worst case: O(logN) , N - size of the array. + * + * Space Complexity: O(logN) (since we use stack for function calls) + * + */ + + +public class BinarySearchRecursive { + + public static void main(String[] args) { + int[] arr = {1,2,5,89,99,101}; + int target = 1; + System.out.println(binarySearch(arr , target,0 , arr.length-1)); + } + + static int binarySearch(int[] arr ,int target, int start , int end) { + + int mid = (start + end)/2; + + if (start > end) { + return -1; + } + if (arr[mid] == target) { + return mid; + } + + else if (arr[mid] > target) { + return binarySearch(arr , target , start , mid-1); + } + + return binarySearch(arr ,target , mid+1, end); + + } +} From 461dca01aa3e382000c82c83b7e025bfddff501d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Jul 2023 18:26:34 +0530 Subject: [PATCH 1635/1894] remove duplicate --- Strings/reverse_words.java | 58 -------------------------------------- 1 file changed, 58 deletions(-) delete mode 100644 Strings/reverse_words.java diff --git a/Strings/reverse_words.java b/Strings/reverse_words.java deleted file mode 100644 index e19be5dc..00000000 --- a/Strings/reverse_words.java +++ /dev/null @@ -1,58 +0,0 @@ -/*Name : Abhinav kumar -Github username : Abhinavcode13 -Repository name : data-structures-and-algorithms -Problem : Add Reverse Words in a String in Java -Issue Number : #349 -Problem statement : - -Explanation of the below Java code : - -First, we import the java.util.Scanner class, which allows us to take input from the user. - -We define a class called ReverseWordsInString. - -Inside the main method, we create a new Scanner object named scanner to read user input. - -We prompt the user to enter a string by using System.out.print("Enter a string: ") and then call scanner.nextLine() to read the user's input and store it in the input variable. - -Next, we call the reverseWords method and pass the input string as an argument. The reverseWords method takes the input string, splits it into an array of words using the split("\\s+") method (which splits the string based on whitespace), and stores the words in the words array. - -We create a StringBuilder named reversed to build the reversed string. - -Using a loop, we iterate over the words array in reverse order (starting from the last word) and append each word, followed by a space, to the reversed string. - -Finally, we return the reversed string by calling reversed.toString().trim(), which converts the StringBuilder to a String and trims any leading or trailing whitespace. - -The reversed string is then printed to the console using System.out.println("Reversed String: " + reversed). - -Finally, we close the Scanner object to release system resources by calling scanner.close(). - - - -*/ - --------------------------------------------------------------------------//Java code begins here------------------------------------------------------------- - -import java.util.Scanner; - -public class ReverseWordsInString { - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - System.out.print("Enter a string: "); - String input = scanner.nextLine(); - String reversed = reverseWords(input); - System.out.println("Reversed String: " + reversed); - scanner.close(); - } - - public static String reverseWords(String input) { - String[] words = input.split("\\s+"); - StringBuilder reversed = new StringBuilder(); - - for (int i = words.length - 1; i >= 0; i--) { - reversed.append(words[i]).append(" "); - } - - return reversed.toString().trim(); - } -} From 86baa9661d26a2f9c12a349cf7058bd117460b58 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Jul 2023 18:26:45 +0530 Subject: [PATCH 1636/1894] remove rotate string --- Strings/rotate_string.cpp | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 Strings/rotate_string.cpp diff --git a/Strings/rotate_string.cpp b/Strings/rotate_string.cpp deleted file mode 100644 index 7c0127dd..00000000 --- a/Strings/rotate_string.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// Rotating a string -#include -using namespace std; - -void rotate(char *a, int k){ - int len = strlen(a); - while(len >= 0){ - a[len + k] = a[len]; - len--; - } - len = strlen(a); - int j = len - k; - int s = 0; - while(j < len){ - a[s] = a[j]; - s++; - j++; - } - a[len - k] = '\0'; -} -int main(){ - char a[100] = "abhisekkumar"; - int k = 5; - rotate(a, k); - cout << a << endl; - return 0; -} \ No newline at end of file From 3b7b2ae067ced09e81b31b2e9089157b0428e1d2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Jul 2023 18:35:28 +0530 Subject: [PATCH 1637/1894] add one edit in c++ --- Strings/one_edit.cpp | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Strings/one_edit.cpp diff --git a/Strings/one_edit.cpp b/Strings/one_edit.cpp new file mode 100644 index 00000000..7f3a6122 --- /dev/null +++ b/Strings/one_edit.cpp @@ -0,0 +1,88 @@ + /* + You're given two strings stringone and stringtwo. Write a function that determines if these + two strings can be made equal using only one edit. + + + There are 3 possible edits: + Replace: One character in one string is swapped for a different character. + Add:: One character is added at any index in one string. + Remove: One character is removed at any index in one string. + + Sample Input: StringOne: alaska StringTwo: aloska + Output: True + + + Explanation: + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. + + The `OneEdit` function takes two strings as input and returns a boolean indicating whether + they are one edit away. Here's the breakdown of the algorithm: + + 1. Calculate the lengths of the two strings. + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + not possible to make one edit to make the strings equal. + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + found. + 4. If an unequal character is found, check the remaining portion of the strings to determine + if they are still one edit away. + 5. Check the remaining characters in the longer string compared to the remaining characters + in the shorter string. + 6. Return `true` if the remaining portions match, indicating they are one edit away. + 7. If the loop completes without finding any unequal characters, the strings are either + identical or differ only in length by 1, which means they are one edit away. + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + and minimum of two integers, respectively. + + The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. + + O(n) time | O(1) space - where n is the length of the shorter string + + +*/ +#include +#include +using namespace std; + +bool OneEdit(string stringOne, string stringTwo) { + int lengthOne = stringOne.length(); + int lengthTwo = stringTwo.length(); + + // Check the difference in lengths between the two strings. + // If the difference is greater than 1, it is not possible to make one edit to make them equal. + if (abs(lengthOne - lengthTwo) > 1) { + return false; + } + + // Traverse the strings until the shorter one is fully traversed or an unequal character is found. + for (int i = 0; i < min(lengthOne, lengthTwo); i++) { + // If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. + if (stringOne[i] != stringTwo[i]) { + // Check the remaining characters in the longer string compared to the remaining characters in the shorter string. + // Return true if they match, indicating they are one edit away. + if (lengthOne > lengthTwo) { + return stringOne.substr(i + 1) == stringTwo.substr(i); + } else if (lengthTwo > lengthOne) { + return stringTwo.substr(i + 1) == stringOne.substr(i); + } else { + return stringOne.substr(i + 1) == stringTwo.substr(i + 1); + } + } + } + + // If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. + return true; +} + +int main() { + string stringOne = "pale"; + string stringTwo = "ple"; + + // Check if the strings are one edit away + bool isOneEdit = OneEdit(stringOne, stringTwo); + + // Print the result + cout << "The strings are" << (isOneEdit ? "" : " not") << " one edit away." << endl; + + return 0; +} From b72053a8b2e9c78a74e6ed24d98e559ce7c29952 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Jul 2023 18:38:10 +0530 Subject: [PATCH 1638/1894] add one edit in ajva --- Strings/one_edit.java | 84 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Strings/one_edit.java diff --git a/Strings/one_edit.java b/Strings/one_edit.java new file mode 100644 index 00000000..cafcd67d --- /dev/null +++ b/Strings/one_edit.java @@ -0,0 +1,84 @@ +/* + You're given two strings stringone and stringtwo. Write a function that determines if these + two strings can be made equal using only one edit. + + + There are 3 possible edits: + Replace: One character in one string is swapped for a different character. + Add:: One character is added at any index in one string. + Remove: One character is removed at any index in one string. + + Sample Input: StringOne: alaska StringTwo: aloska + Output: True + + + Explanation: + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. + + The `OneEdit` function takes two strings as input and returns a boolean indicating whether + they are one edit away. Here's the breakdown of the algorithm: + + 1. Calculate the lengths of the two strings. + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + not possible to make one edit to make the strings equal. + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + found. + 4. If an unequal character is found, check the remaining portion of the strings to determine + if they are still one edit away. + 5. Check the remaining characters in the longer string compared to the remaining characters + in the shorter string. + 6. Return `true` if the remaining portions match, indicating they are one edit away. + 7. If the loop completes without finding any unequal characters, the strings are either + identical or differ only in length by 1, which means they are one edit away. + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + and minimum of two integers, respectively. + + The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. + + O(n) time | O(1) space - where n is the length of the shorter string + + +*/ +public class Main { + public static void main(String[] args) { + String stringOne = "pale"; + String stringTwo = "ple"; + + // Check if the strings are one edit away + boolean isOneEdit = isOneEdit(stringOne, stringTwo); + + // Print the result + System.out.println("The strings are" + (isOneEdit ? "" : " not") + " one edit away."); + } + + public static boolean isOneEdit(String stringOne, String stringTwo) { + int lengthOne = stringOne.length(); + int lengthTwo = stringTwo.length(); + + // Check the difference in lengths between the two strings. + // If the difference is greater than 1, it is not possible to make one edit to make them equal. + if (Math.abs(lengthOne - lengthTwo) > 1) { + return false; + } + + // Traverse the strings until the shorter one is fully traversed or an unequal character is found. + for (int i = 0; i < Math.min(lengthOne, lengthTwo); i++) { + // If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. + if (stringOne.charAt(i) != stringTwo.charAt(i)) { + // Check the remaining characters in the longer string compared to the remaining characters in the shorter string. + // Return true if they match, indicating they are one edit away. + if (lengthOne > lengthTwo) { + return stringOne.substring(i + 1).equals(stringTwo.substring(i)); + } else if (lengthTwo > lengthOne) { + return stringTwo.substring(i + 1).equals(stringOne.substring(i)); + } else { + return stringOne.substring(i + 1).equals(stringTwo.substring(i + 1)); + } + } + } + + // If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. + return true; + } +} From 69f8070c329c1a8c96a84d6f1a0f9c38563f13df Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 15 Jul 2023 18:41:14 +0530 Subject: [PATCH 1639/1894] add one edit in java --- Strings/one_edit.js | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Strings/one_edit.js diff --git a/Strings/one_edit.js b/Strings/one_edit.js new file mode 100644 index 00000000..460373b2 --- /dev/null +++ b/Strings/one_edit.js @@ -0,0 +1,80 @@ +/* + You're given two strings stringone and stringtwo. Write a function that determines if these + two strings can be made equal using only one edit. + + + There are 3 possible edits: + Replace: One character in one string is swapped for a different character. + Add:: One character is added at any index in one string. + Remove: One character is removed at any index in one string. + + Sample Input: StringOne: alaska StringTwo: aloska + Output: True + + + Explanation: + The code snippet is implementing the "One Edit Away" algorithm, which determines whether two given + strings are one edit away from each other. An edit is defined as either inserting a character, removing a character, or replacing a character. + + The `OneEdit` function takes two strings as input and returns a boolean indicating whether + they are one edit away. Here's the breakdown of the algorithm: + + 1. Calculate the lengths of the two strings. + 2. Check if the difference in lengths is greater than 1. If so, return `false` because it's + not possible to make one edit to make the strings equal. + 3. Traverse both strings until the shorter one is fully traversed or an unequal character is + found. + 4. If an unequal character is found, check the remaining portion of the strings to determine + if they are still one edit away. + 5. Check the remaining characters in the longer string compared to the remaining characters + in the shorter string. + 6. Return `true` if the remaining portions match, indicating they are one edit away. + 7. If the loop completes without finding any unequal characters, the strings are either + identical or differ only in length by 1, which means they are one edit away. + 8. The `abs` and `min` functions are utility functions used to calculate the absolute value + and minimum of two integers, respectively. + + The algorithm efficiently checks for the possibility of one edit by comparing the characters at corresponding indices and handling cases where the lengths of the strings are different. + + O(n) time | O(1) space - where n is the length of the shorter string + + +*/ +function isOneEdit(stringOne, stringTwo) { + const lengthOne = stringOne.length; + const lengthTwo = stringTwo.length; + + // Check the difference in lengths between the two strings. + // If the difference is greater than 1, it is not possible to make one edit to make them equal. + if (Math.abs(lengthOne - lengthTwo) > 1) { + return false; + } + + // Traverse the strings until the shorter one is fully traversed or an unequal character is found. + for (let i = 0; i < Math.min(lengthOne, lengthTwo); i++) { + // If an unequal character is found, check the remaining portion of the strings to determine if they are still one edit away. + if (stringOne[i] !== stringTwo[i]) { + // Check the remaining characters in the longer string compared to the remaining characters in the shorter string. + // Return true if they match, indicating they are one edit away. + if (lengthOne > lengthTwo) { + return stringOne.slice(i + 1) === stringTwo.slice(i); + } else if (lengthTwo > lengthOne) { + return stringTwo.slice(i + 1) === stringOne.slice(i); + } else { + return stringOne.slice(i + 1) === stringTwo.slice(i + 1); + } + } + } + + // If the loop completes without finding any unequal characters, the strings are either identical or differ only in length by 1. + return true; +} + +const stringOne = "pale"; +const stringTwo = "ple"; + +// Check if the strings are one edit away +const isOneEdit = isOneEdit(stringOne, stringTwo); + +// Print the result +console.log(`The strings are${isOneEdit ? "" : " not"} one edit away.`); From 39abda195a03fe71e75d92d1fb6e7e178f04a863 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:11:42 +0530 Subject: [PATCH 1640/1894] add next greater element --- Stacks/next_greater_element.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Stacks/next_greater_element.go diff --git a/Stacks/next_greater_element.go b/Stacks/next_greater_element.go new file mode 100644 index 00000000..b5f96c91 --- /dev/null +++ b/Stacks/next_greater_element.go @@ -0,0 +1,21 @@ +package main + +func NextGreaterElement(array []int) []int { + result := make([]int, 0) + for range array { + result = append(result, -1) + } + stack := make([]int, 0) + + for idx := 0; idx < 2*len(array); idx++ { + circularIdx := idx % len(array) + + for len(stack) > 0 && array[circularIdx] > array[stack[len(stack)-1]] { + var top int + top, stack = stack[len(stack)-1], stack[:len(stack)-1] + result[top] = array[circularIdx] + } + stack = append(stack, circularIdx) + } + return result +} From 646292598bf24e89830c663fd62c2183afd9b469 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:12:02 +0530 Subject: [PATCH 1641/1894] add comments --- Stacks/next_greater_element.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Stacks/next_greater_element.go b/Stacks/next_greater_element.go index b5f96c91..00dd05bd 100644 --- a/Stacks/next_greater_element.go +++ b/Stacks/next_greater_element.go @@ -1,21 +1,36 @@ package main +// NextGreaterElement finds the next greater element for each element in the input array. func NextGreaterElement(array []int) []int { + // Create a result slice to store the next greater elements. result := make([]int, 0) + // Initialize the result slice with -1 values indicating no greater elements initially. for range array { result = append(result, -1) } + + // Create a stack to keep track of indices of elements from the input array. stack := make([]int, 0) + // Perform two passes over the input array, considering elements in a circular manner. for idx := 0; idx < 2*len(array); idx++ { + // Calculate the circular index by using the modulo operator. circularIdx := idx % len(array) + // Check if the current element is greater than the element at the top of the stack. for len(stack) > 0 && array[circularIdx] > array[stack[len(stack)-1]] { - var top int - top, stack = stack[len(stack)-1], stack[:len(stack)-1] + // Retrieve the top index from the stack. + top := stack[len(stack)-1] + // Update the corresponding element in the result slice with the current element. result[top] = array[circularIdx] + // Remove the top index from the stack. + stack = stack[:len(stack)-1] } + + // Push the current circular index onto the stack. stack = append(stack, circularIdx) } + + // Return the result slice containing the next greater elements. return result } From 3bfc7020802b1b8e39040a891627599efe4a25fd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:14:06 +0530 Subject: [PATCH 1642/1894] add explanation --- Stacks/next_greater_element.go | 40 ++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Stacks/next_greater_element.go b/Stacks/next_greater_element.go index 00dd05bd..d43ac4e7 100644 --- a/Stacks/next_greater_element.go +++ b/Stacks/next_greater_element.go @@ -1,3 +1,43 @@ +/* + + Write a function that takes in an array of integers and returns a new array containing, at each index, the next + element in the input array that's greater than the element at that index in the input array. + Explanation: + + The given code snippet implements the Next Greater Element algorithm. Here's how it works: + + 1. The function `NextGreaterElement` takes an input array of integers and returns an array of the same length + where each element represents the next greater element in the input array. If there is no greater element, the corresponding output element is set to -1. + + 2. The `result` slice is initialized with -1 values, indicating that there are no greater elements initially. + + 3. The `stack` is used to keep track of indices of elements from the input array. It will store indices in a + way that maintains a decreasing order of values from the input array. + + 4. The algorithm performs two passes over the input array. In each pass, it considers the array elements in a + circular manner by using the modulo operator `%` on the index. + + 5. In the inner loop, the algorithm checks if the current element is greater than the element at the top of the stack. + If it is, it means the current element is the next greater element for the element at the top of the stack. + + 6. If a greater element is found, the top index is retrieved from the stack, and the corresponding element in the + `result` slice is updated with the current element from the input array. + + 7. After updating the `result` slice, the top index is removed from the stack. + + 8. The current circular index is then pushed onto the stack to potentially find the next greater element for it in + the future. + + 9. Once the algorithm completes the two passes over the input array, the `result` slice contains the next greater + elements for each element in the input array, or -1 if there is no greater element. + + 10. The `result` slice is returned as the output. + + The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. + By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. + + Note that this implementation assumes the availability of the built-in append function to modify slices in Go. +*/ package main // NextGreaterElement finds the next greater element for each element in the input array. From 923c40eb8e94a3a0cc566c009ab3618464fe4eec Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:14:50 +0530 Subject: [PATCH 1643/1894] add sample io --- Stacks/next_greater_element.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Stacks/next_greater_element.go b/Stacks/next_greater_element.go index d43ac4e7..586f2d76 100644 --- a/Stacks/next_greater_element.go +++ b/Stacks/next_greater_element.go @@ -2,6 +2,9 @@ Write a function that takes in an array of integers and returns a new array containing, at each index, the next element in the input array that's greater than the element at that index in the input array. + + Sample Input:[2, 5, -3, -4, 6, 7, 2] + Output: [5, 6, 6, 6, 7, -1, 5] Explanation: The given code snippet implements the Next Greater Element algorithm. Here's how it works: From 4ab0bf5c449a9efb82b99c3593f31180b3b60d90 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:16:16 +0530 Subject: [PATCH 1644/1894] add time and space --- Stacks/next_greater_element.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Stacks/next_greater_element.go b/Stacks/next_greater_element.go index 586f2d76..d1af1558 100644 --- a/Stacks/next_greater_element.go +++ b/Stacks/next_greater_element.go @@ -40,6 +40,12 @@ By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. Note that this implementation assumes the availability of the built-in append function to modify slices in Go. + + The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. + This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. + + The space complexity of the function is O(n) as well. This is because the function creates two additional + slices: `result` and `stack`, each with a maximum size of n. Therefore, the space required by the function grows linearly with the size of the input array. */ package main From a0bf8667f01b41909bd1d031e80e264377aeab22 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:18:31 +0530 Subject: [PATCH 1645/1894] add next greater element in python --- Stacks/next_greater_element.py | 64 ++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Stacks/next_greater_element.py diff --git a/Stacks/next_greater_element.py b/Stacks/next_greater_element.py new file mode 100644 index 00000000..c6fa7cd8 --- /dev/null +++ b/Stacks/next_greater_element.py @@ -0,0 +1,64 @@ +''' + + Write a function that takes in an array of integers and returns a new array containing, at each index, the next + element in the input array that's greater than the element at that index in the input array. + + Sample Input:[2, 5, -3, -4, 6, 7, 2] + Output: [5, 6, 6, 6, 7, -1, 5] + Explanation: + + The given code snippet implements the Next Greater Element algorithm. Here's how it works: + + 1. The function `NextGreaterElement` takes an input array of integers and returns an array of the same length + where each element represents the next greater element in the input array. If there is no greater element, the corresponding output element is set to -1. + + 2. The `result` slice is initialized with -1 values, indicating that there are no greater elements initially. + + 3. The `stack` is used to keep track of indices of elements from the input array. It will store indices in a + way that maintains a decreasing order of values from the input array. + + 4. The algorithm performs two passes over the input array. In each pass, it considers the array elements in a + circular manner by using the modulo operator `%` on the index. + + 5. In the inner loop, the algorithm checks if the current element is greater than the element at the top of the stack. + If it is, it means the current element is the next greater element for the element at the top of the stack. + + 6. If a greater element is found, the top index is retrieved from the stack, and the corresponding element in the + `result` slice is updated with the current element from the input array. + + 7. After updating the `result` slice, the top index is removed from the stack. + + 8. The current circular index is then pushed onto the stack to potentially find the next greater element for it in + the future. + + 9. Once the algorithm completes the two passes over the input array, the `result` slice contains the next greater + elements for each element in the input array, or -1 if there is no greater element. + + 10. The `result` slice is returned as the output. + + The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. + By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. + + + The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. + This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. + + The space complexity of the function is O(n) as well. This is because the function creates two additional + slices: `result` and `stack`, each with a maximum size of n. Therefore, the space required by the function grows linearly with the size of the input array. +''' + +def next_greater_element(array): + result = [-1] * len(array) # Initialize result array with -1 for all elements + stack = [] # Stack to store indices of elements + + for idx in range(len(array) * 2): + circular_idx = idx % len(array) # Obtain the circular index of the current element + + while stack and array[circular_idx] > array[stack[-1]]: + # While the stack is not empty and the current element is greater than the element at the top of the stack + top = stack.pop() # Pop the index from the stack + result[top] = array[circular_idx] # Update the result for the popped index + + stack.append(circular_idx) # Push the current index to the stack + + return result From 56b93212d63fd2ac0d7279799ff13e1102fe5ee4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:20:04 +0530 Subject: [PATCH 1646/1894] add next greater element in js --- Stacks/next_greater_element.js | 70 ++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Stacks/next_greater_element.js diff --git a/Stacks/next_greater_element.js b/Stacks/next_greater_element.js new file mode 100644 index 00000000..eba4a938 --- /dev/null +++ b/Stacks/next_greater_element.js @@ -0,0 +1,70 @@ +/* + + Write a function that takes in an array of integers and returns a new array containing, at each index, the next + element in the input array that's greater than the element at that index in the input array. + + Sample Input:[2, 5, -3, -4, 6, 7, 2] + Output: [5, 6, 6, 6, 7, -1, 5] + Explanation: + + The given code snippet implements the Next Greater Element algorithm. Here's how it works: + + 1. The function `NextGreaterElement` takes an input array of integers and returns an array of the same length + where each element represents the next greater element in the input array. If there is no greater element, the corresponding output element is set to -1. + + 2. The `result` slice is initialized with -1 values, indicating that there are no greater elements initially. + + 3. The `stack` is used to keep track of indices of elements from the input array. It will store indices in a + way that maintains a decreasing order of values from the input array. + + 4. The algorithm performs two passes over the input array. In each pass, it considers the array elements in a + circular manner by using the modulo operator `%` on the index. + + 5. In the inner loop, the algorithm checks if the current element is greater than the element at the top of the stack. + If it is, it means the current element is the next greater element for the element at the top of the stack. + + 6. If a greater element is found, the top index is retrieved from the stack, and the corresponding element in the + `result` slice is updated with the current element from the input array. + + 7. After updating the `result` slice, the top index is removed from the stack. + + 8. The current circular index is then pushed onto the stack to potentially find the next greater element for it in + the future. + + 9. Once the algorithm completes the two passes over the input array, the `result` slice contains the next greater + elements for each element in the input array, or -1 if there is no greater element. + + 10. The `result` slice is returned as the output. + + The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. + By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. + + Note that this implementation assumes the availability of the built-in append function to modify slices in Go. + + The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. + This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. + + The space complexity of the function is O(n) as well. This is because the function creates two additional + slices: `result` and `stack`, each with a maximum size of n. Therefore, the space required by the function grows linearly with the size of the input array. +*/ +function nextGreaterElement(array) { + const result = new Array(array.length).fill(-1); // Initialize result array with -1 for all elements + const stack = []; // Stack to store indices of elements + + for (let idx = 0; idx < array.length * 2; idx++) { + const circularIdx = idx % array.length; // Obtain the circular index of the current element + + while ( + stack.length && + array[circularIdx] > array[stack[stack.length - 1]] + ) { + // While the stack is not empty and the current element is greater than the element at the top of the stack + const top = stack.pop(); // Pop the index from the stack + result[top] = array[circularIdx]; // Update the result for the popped index + } + + stack.push(circularIdx); // Push the current index to the stack + } + + return result; +} From d3fc81ce10f3dd7eaebc75eaa2bd24906f7a8732 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:22:00 +0530 Subject: [PATCH 1647/1894] remove go specific comment --- Stacks/next_greater_element.js | 1 - Stacks/next_greater_element.py | 1 - 2 files changed, 2 deletions(-) diff --git a/Stacks/next_greater_element.js b/Stacks/next_greater_element.js index eba4a938..e2b2a6e9 100644 --- a/Stacks/next_greater_element.js +++ b/Stacks/next_greater_element.js @@ -39,7 +39,6 @@ The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. - Note that this implementation assumes the availability of the built-in append function to modify slices in Go. The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. diff --git a/Stacks/next_greater_element.py b/Stacks/next_greater_element.py index c6fa7cd8..34464d3f 100644 --- a/Stacks/next_greater_element.py +++ b/Stacks/next_greater_element.py @@ -38,7 +38,6 @@ The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. - The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. From a6f315cb70d1591e7672b4f9f44284adbbf93302 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:22:09 +0530 Subject: [PATCH 1648/1894] add next greater element in c++ --- Stacks/next_greater_element.c++ | 72 +++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Stacks/next_greater_element.c++ diff --git a/Stacks/next_greater_element.c++ b/Stacks/next_greater_element.c++ new file mode 100644 index 00000000..730fc941 --- /dev/null +++ b/Stacks/next_greater_element.c++ @@ -0,0 +1,72 @@ +/* + + Write a function that takes in an array of integers and returns a new array containing, at each index, the next + element in the input array that's greater than the element at that index in the input array. + + Sample Input:[2, 5, -3, -4, 6, 7, 2] + Output: [5, 6, 6, 6, 7, -1, 5] + Explanation: + + The given code snippet implements the Next Greater Element algorithm. Here's how it works: + + 1. The function `NextGreaterElement` takes an input array of integers and returns an array of the same length + where each element represents the next greater element in the input array. If there is no greater element, the corresponding output element is set to -1. + + 2. The `result` slice is initialized with -1 values, indicating that there are no greater elements initially. + + 3. The `stack` is used to keep track of indices of elements from the input array. It will store indices in a + way that maintains a decreasing order of values from the input array. + + 4. The algorithm performs two passes over the input array. In each pass, it considers the array elements in a + circular manner by using the modulo operator `%` on the index. + + 5. In the inner loop, the algorithm checks if the current element is greater than the element at the top of the stack. + If it is, it means the current element is the next greater element for the element at the top of the stack. + + 6. If a greater element is found, the top index is retrieved from the stack, and the corresponding element in the + `result` slice is updated with the current element from the input array. + + 7. After updating the `result` slice, the top index is removed from the stack. + + 8. The current circular index is then pushed onto the stack to potentially find the next greater element for it in + the future. + + 9. Once the algorithm completes the two passes over the input array, the `result` slice contains the next greater + elements for each element in the input array, or -1 if there is no greater element. + + 10. The `result` slice is returned as the output. + + The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. + By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. + + Note that this implementation assumes the availability of the built-in append function to modify slices in Go. + + The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. + This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. + + The space complexity of the function is O(n) as well. This is because the function creates two additional + slices: `result` and `stack`, each with a maximum size of n. Therefore, the space required by the function grows linearly with the size of the input array. +*/ + +#include +#include + +std::vector nextGreaterElement(std::vector& array) { + std::vector result(array.size(), -1); // Initialize result vector with -1 for all elements + std::stack stack; // Stack to store indices of elements + + for (int idx = 0; idx < array.size() * 2; idx++) { + int circularIdx = idx % array.size(); // Obtain the circular index of the current element + + while (!stack.empty() && array[circularIdx] > array[stack.top()]) { + // While the stack is not empty and the current element is greater than the element at the top of the stack + int top = stack.top(); // Get the index from the top of the stack + stack.pop(); // Pop the index from the stack + result[top] = array[circularIdx]; // Update the result for the popped index + } + + stack.push(circularIdx); // Push the current index to the stack + } + + return result; +} From dd9993e9931e4b879e12558aa77d285d6aceabef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 16 Jul 2023 22:22:18 +0530 Subject: [PATCH 1649/1894] add next greater element in java --- Stacks/next_greater_element.java | 71 ++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Stacks/next_greater_element.java diff --git a/Stacks/next_greater_element.java b/Stacks/next_greater_element.java new file mode 100644 index 00000000..5efc1adb --- /dev/null +++ b/Stacks/next_greater_element.java @@ -0,0 +1,71 @@ +/* + + Write a function that takes in an array of integers and returns a new array containing, at each index, the next + element in the input array that's greater than the element at that index in the input array. + + Sample Input:[2, 5, -3, -4, 6, 7, 2] + Output: [5, 6, 6, 6, 7, -1, 5] + Explanation: + + The given code snippet implements the Next Greater Element algorithm. Here's how it works: + + 1. The function `NextGreaterElement` takes an input array of integers and returns an array of the same length + where each element represents the next greater element in the input array. If there is no greater element, the corresponding output element is set to -1. + + 2. The `result` slice is initialized with -1 values, indicating that there are no greater elements initially. + + 3. The `stack` is used to keep track of indices of elements from the input array. It will store indices in a + way that maintains a decreasing order of values from the input array. + + 4. The algorithm performs two passes over the input array. In each pass, it considers the array elements in a + circular manner by using the modulo operator `%` on the index. + + 5. In the inner loop, the algorithm checks if the current element is greater than the element at the top of the stack. + If it is, it means the current element is the next greater element for the element at the top of the stack. + + 6. If a greater element is found, the top index is retrieved from the stack, and the corresponding element in the + `result` slice is updated with the current element from the input array. + + 7. After updating the `result` slice, the top index is removed from the stack. + + 8. The current circular index is then pushed onto the stack to potentially find the next greater element for it in + the future. + + 9. Once the algorithm completes the two passes over the input array, the `result` slice contains the next greater + elements for each element in the input array, or -1 if there is no greater element. + + 10. The `result` slice is returned as the output. + + The algorithm utilizes a stack to efficiently find the next greater element for each element in the input array. + By iterating over the array twice in a circular manner, it ensures that all elements have been considered for finding the next greater elements. + + The time complexity of the `NextGreaterElement` function is O(n), where n is the length of the input array. + This is because the function performs two passes over the input array, and in each pass, it processes each element once. The operations performed within each iteration, such as stack operations, have constant time complexity. + + The space complexity of the function is O(n) as well. This is because the function creates two additional + slices: `result` and `stack`, each with a maximum size of n. Therefore, the space required by the function grows linearly with the size of the input array. +*/ + +import java.util.*; + +public class NextGreaterElement { + public int[] nextGreaterElement(int[] array) { + int[] result = new int[array.length]; + Arrays.fill(result, -1); // Initialize result array with -1 for all elements + Stack stack = new Stack<>(); // Stack to store indices of elements + + for (int idx = 0; idx < array.length * 2; idx++) { + int circularIdx = idx % array.length; // Obtain the circular index of the current element + + while (!stack.isEmpty() && array[circularIdx] > array[stack.peek()]) { + // While the stack is not empty and the current element is greater than the element at the top of the stack + int top = stack.pop(); // Pop the index from the stack + result[top] = array[circularIdx]; // Update the result for the popped index + } + + stack.push(circularIdx); // Push the current index to the stack + } + + return result; + } +} From b871707d1fdfa3c161a0a6671d956252f475d413 Mon Sep 17 00:00:00 2001 From: Manik Dingra Date: Sun, 16 Jul 2023 23:29:53 +0530 Subject: [PATCH 1650/1894] Tries folder and some basic questions added --- Tries/PatternMatching.cpp | 186 ++++++++++++++++++++++++++++++++++++++ Tries/SearchInTries.cpp | 132 +++++++++++++++++++++++++++ Tries/TrieNodeClass.cpp | 153 +++++++++++++++++++++++++++++++ 3 files changed, 471 insertions(+) create mode 100644 Tries/PatternMatching.cpp create mode 100644 Tries/SearchInTries.cpp create mode 100644 Tries/TrieNodeClass.cpp diff --git a/Tries/PatternMatching.cpp b/Tries/PatternMatching.cpp new file mode 100644 index 00000000..2d44e53d --- /dev/null +++ b/Tries/PatternMatching.cpp @@ -0,0 +1,186 @@ +/* +Given a list of n words and a pattern p that we want to search. Check if the pattern p is present the given words or not. Return true if the pattern is present and false otherwise. +Input Format : + +The first line of input contains an integer, that denotes the value of n. +The following line contains n space separated words. +The following line contains a string, that denotes the value of the pattern p. + +Output Format : + +The first and only line of output contains true if the pattern is present and false otherwise. + +Constraints: + +Time Limit: 1 sec + +Sample Input 1 : + +4 +abc def ghi cba +de + +Sample Output 2 : + +true + +Sample Input 2 : + +4 +abc def ghi hg +hi + +Sample Output 2 : + +true + +Sample Input 3 : + +4 +abc def ghi hg +hif + +Sample Output 3 : + +false + +Explaination : + The TrieNode class represents a single node in the Trie. Each node contains a character data, an array of pointers to its child nodes children, and a boolean flag isTerminal to indicate if a word ends at that node. + + The Trie class serves as the main data structure and contains a pointer to the root node of the Trie, along with a count variable to keep track of the number of words inserted. + + The insertWord function is used to insert a word into the Trie. It takes a root parameter representing the current node and a word parameter representing the word to be inserted. The function recursively traverses the Trie, creating new nodes as needed and marking the last node as terminal if the word does not already exist. + + The search function is used to search for a word in the Trie. It takes a root parameter and a word parameter. The function recursively checks if each character in the word exists as a child node starting from the given root. + + The patternMatching function takes a vector of strings vect and a pattern string. It iterates over each word in the vector and inserts all possible substrings of that word into the Trie. Finally, it performs a search operation on the pattern string in the Trie and returns the result. +*/ +#include +#include +#include +using namespace std; + +class TrieNode +{ +public: + char data; + TrieNode **children; + bool isTerminal; + + TrieNode(char data) + { + this->data = data; + children = new TrieNode *[26]; + for (int i = 0; i < 26; i++) + { + children[i] = NULL; + } + isTerminal = false; + } +}; + +class Trie +{ + TrieNode *root; + +public: + int count; + + Trie() + { + this->count = 0; + root = new TrieNode('\0'); + } + + bool insertWord(TrieNode *root, string word) + { + // Base case + if (word.size() == 0) + { + if (!root->isTerminal) + { + root->isTerminal = true; + return true; + } + else + { + return false; + } + } + + // Small calculation + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + child = new TrieNode(word[0]); + root->children[index] = child; + } + + // Recursive call + return insertWord(child, word.substr(1)); + } + + void insertWord(string word) + { + if (insertWord(root, word)) + { + this->count++; + } + } + + bool search(TrieNode *root, string word) + { + if (word.length() == 0) + { + return true; + } + if (root->children[word[0] - 'a'] == NULL) + { + return false; + } + bool ans = search(root->children[word[0] - 'a'], word.substr(1)); + return ans; + } + + bool search(string word) + { + return search(root, word); + } + + bool patternMatching(vector vect, string pattern) + { + for (int i = 0; i < vect.size(); i++) + { + string word = vect[i]; + for (int j = 0; j < word.size(); j++) + { + insertWord(word.substr(j)); + } + } + return search(pattern); + } +}; + +int main() +{ + Trie t; + int n; + cin >> n; + string pattern; + vector vect; + + for (int i = 0; i < n; ++i) + { + string word; + cin >> word; + vect.push_back(word); + } + cin >> pattern; + + cout << (t.patternMatching(vect, pattern) ? "true" : "false"); +} \ No newline at end of file diff --git a/Tries/SearchInTries.cpp b/Tries/SearchInTries.cpp new file mode 100644 index 00000000..59cc41c3 --- /dev/null +++ b/Tries/SearchInTries.cpp @@ -0,0 +1,132 @@ +/* +Implement the function SearchWord for the Trie class. +For a Trie, write the function for searching a word. Return true if the word is found successfully, otherwise return false. +Note : main function is given for your reference which we are using internally to test the code. + +Explaination : + The given code implements a Trie data structure and focuses on implementing the search functionality. The TrieNode class represents a single node in the Trie, and the Trie class serves as the main data structure. + + The insertWord function is used to insert a word into the Trie. It takes a root parameter representing the current node and a word parameter representing the word to be inserted. The function recursively traverses the Trie, creating new nodes as needed and marking the last node as terminal. + + The search function is used to search for a word in the Trie. It takes a root parameter and a word parameter. The function recursively checks if each character in the word exists as a child node starting from the given root. It returns true if the word is found and the last node is marked as terminal, otherwise it returns false. + + In the main function, an instance of the Trie class is created. The program then enters a loop where the user can input commands. The user is prompted to enter a choice: 1 for inserting a word or 2 for searching a word. If the choice is 1, the user can enter a word to be inserted into the Trie. If the choice is 2, the user can enter a word to search for in the Trie. The result of the search operation is printed as "true" or "false" accordingly. +*/ +#include +#include +using namespace std; + +class TrieNode +{ +public: + char data; + TrieNode **children; + bool isTerminal; + + TrieNode(char data) + { + this->data = data; + children = new TrieNode *[26]; + for (int i = 0; i < 26; i++) + { + children[i] = NULL; + } + isTerminal = false; + } +}; + +class Trie +{ + TrieNode *root; + +public: + Trie() + { + root = new TrieNode('\0'); + } + + void insertWord(TrieNode *root, string word) + { + // Base case + if (word.size() == 0) + { + root->isTerminal = true; + return; + } + + // Small Calculation + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + child = new TrieNode(word[0]); + root->children[index] = child; + } + + // Recursive call + insertWord(child, word.substr(1)); + } + + void insertWord(string word) + { + insertWord(root, word); + } + + bool search(TrieNode *root, string word) + { + if (word.length() == 0) + { + return root->isTerminal && true; + } + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + return root->isTerminal && false; + } + bool ans = search(child, word.substr(1)); + return ans; + } + + bool search(string word) + { + return search(root, word); + } +}; + +int main() +{ + int choice; + cin >> choice; + Trie t; + + while (choice != -1) + { + string word; + bool ans; + switch (choice) + { + case 1: // insert + cin >> word; + t.insertWord(word); + break; + case 2: // search + cin >> word; + cout << (t.search(word) ? "true\n" : "false\n"); + break; + default: + return 0; + } + cin >> choice; + } + + return 0; +} \ No newline at end of file diff --git a/Tries/TrieNodeClass.cpp b/Tries/TrieNodeClass.cpp new file mode 100644 index 00000000..496362b6 --- /dev/null +++ b/Tries/TrieNodeClass.cpp @@ -0,0 +1,153 @@ +/* +Explaination : + The TrieNode class represents a single node in the Trie. Each node contains a character data, an array of pointers to its child nodes children, and a boolean flag isTerminal to indicate if a word ends at that node. + + The Trie class serves as the main data structure and contains a pointer to the root node of the Trie. It provides public functions to insert a word into the Trie, search for a word in the Trie, and remove a word from the Trie. + + The insertWord function is a private member function of the Trie class and is responsible for inserting a word into the Trie. It takes a root parameter representing the current node and a word parameter representing the word to be inserted. The function recursively traverses the Trie, creating new nodes as needed and marking the last node as terminal. + + The search function is also a private member function of the Trie class and is used to search for a word in the Trie. It takes a root parameter and a word parameter. The function recursively checks if each character in the word exists as a child node starting from the given root and returns true if the entire word is found and marked as terminal. + + The removeWord function is another private member function of the Trie class and is used to remove a word from the Trie. It takes a root parameter and a word parameter. The function recursively searches for the word in the Trie, marks the last node of the word as non-terminal, and removes any unnecessary child nodes that are not part of other words. + + In the main function, an instance of the Trie class is created. Words "and", "dot", and "double" are inserted into the Trie using the insertWord function. The search function is then used to check if the word "and" exists in the Trie, and the result is printed. The removeWord function is called to remove the word "and" from the Trie, and again the search function is used to check if the word "and" exists in the Trie after removal, and the result is printed. +*/ +#include +#include +using namespace std; + +class TrieNode +{ +public: + char data; + TrieNode **children; + bool isTerminal; + + TrieNode(char data) + { + this->data = data; + children = new TrieNode *[26]; + for (int i = 0; i < 26; i++) + { + children[i] = NULL; + } + isTerminal = false; + } +}; + +class Trie +{ + TrieNode *root; + +public: + Trie() + { + root = new TrieNode('\0'); + } + +private: + void insertWord(TrieNode *root, string word) + { + // Base Case + if (word.length() == 0) + { + root->isTerminal = true; + return; + } + // Small Calculation + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + child = new TrieNode(word[0]); + root->children[index] = child; + } + // Recursive Call + insertWord(child, word.substr(1)); + } + + bool search(TrieNode *root, string word) + { + if (word.length() == 0) + { + return root->isTerminal && true; + } + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + return root->isTerminal && false; + } + bool ans = search(child, word.substr(1)); + return ans; + } + void removeWord(TrieNode *root, string word) + { + if (word.size() == 0) + { + root->isTerminal = false; + return; + } + int index = word[0] - 'a'; + TrieNode *child; + if (root->children[index] != NULL) + { + child = root->children[index]; + } + else + { + // Word not found + return; + } + removeWord(child, word.substr(1)); + + // Remove Child Node if it is useless + if (child->isTerminal == false) + { + for (int i = 0; i < 26; i++) + { + if (child->children[i] != NULL) + { + return; + } + } + delete child; + root->children[index] = NULL; + } + } + +public: + void insertWord(string word) + { + insertWord(root, word); + } + + bool search(string word) + { + return search(root, word); + } + + void removeWord(string word) + { + removeWord(root, word); + } +}; + +int main() +{ + Trie t; + t.insertWord("and"); + t.insertWord("dot"); + t.insertWord("double"); + cout << t.search("and") << endl; + t.removeWord("and"); + cout << t.search("and") << endl; +} \ No newline at end of file From 226874ff75f6304211d62b0c1572f4814f29f933 Mon Sep 17 00:00:00 2001 From: maneesha <97738136+Mani1881@users.noreply.github.com> Date: Mon, 17 Jul 2023 16:38:24 +0530 Subject: [PATCH 1651/1894] Create four_sum.py >>added time and space complexity >>added sample i/o --- four_sum.py | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 four_sum.py diff --git a/four_sum.py b/four_sum.py new file mode 100644 index 00000000..338411c1 --- /dev/null +++ b/four_sum.py @@ -0,0 +1,77 @@ +''' +author:maneesha +Input: +Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: +0 <= a, b, c, d < n +a, b, c, and d are distinct. +nums[a] + nums[b] + nums[c] + nums[d] == target +You may return the answer in any order. + +Example 1: +Input: nums = [1,0,-1,0,-2,2], target = 0 +Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] +Example 2: +Input: nums = [2,2,2,2,2], target = 8 +Output: [[2,2,2,2]] + +Time Complexity:O(n^3) +Space Complexity:O(1) + +Explanation: +>>The fourSum function takes in a list of integers (nums) and a target value (target). +>>The code sorts the nums list in ascending order. +>>It initializes an empty list res to store the resulting quadruplets. +>>Code uses two nested loops to iterate over combinations of four numbers from the nums list. +>>It avoids duplicates by skipping iterations when the current element is the same as the previous element + in both the outer and inner loops. +>>Inside nested loops, code uses two pointers (lo and hi) to find pairs of elements that sum up to the remaining target value. +>>It compares the sum of the four elements with the target value and takes appropriate actions: + +. If sum equals the target, it adds the quadruplet to the result list res and skips any duplicate elements by moving the pointers accordingly. + +. If sum is less than the target, it increments the lo pointer to try larger values. + +. If sum is greater than the target, it decrements the hi pointer to try smaller values. +>>After the nested loops, the function returns the resulting list of quadruplets res. + +''' + from typing import List +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + n = len(nums) + nums.sort() + res = [] + + for i in range(n-3): + # avoid the duplicates while moving i + if i > 0 and nums[i] == nums[i - 1]: + continue + for j in range(i+1, n-2): + # avoid the duplicates while moving j + if j > i + 1 and nums[j] == nums[j - 1]: + continue + lo = j + 1 + hi = n - 1 + while lo < hi: + temp = nums[i] + nums[j] + nums[lo] + nums[hi] + if temp == target: + res += [nums[i], nums[j], nums[lo], nums[hi]], + + # skip duplicates + while lo < hi and nums[lo] == nums[lo + 1]: + lo += 1 + lo += 1 + while lo < hi and nums[hi] == nums[hi - 1]: + hi -= 1 + hi -= 1 + elif temp < target: + lo += 1 + else: + hi -= 1 + return res +# Test case +nums = [1, 0, -1, 0, -2, 2] +target = 0 +solution = Solution() +result = solution.fourSum(nums, target) +print(result) From 533de186d75fbc1a8b833a92940f43c4d0820e23 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Jul 2023 23:29:46 +0530 Subject: [PATCH 1652/1894] update dijkstras algorithm --- Graphs/dijkstras.go | 174 ++++++++++++-------------------------------- 1 file changed, 47 insertions(+), 127 deletions(-) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index e2036cd9..303e786c 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,137 +1,57 @@ -// Dijkstra's algorithm -/* - Dijkstra's algorithm is a pathfinding algorithm that finds the shortest path between two points in a graph. - Here's how it works: - - 1. Start at the starting point (let's call it "A") and mark its distance as 0. - - 2. Visit each of its neighbors (the nodes it's connected to) and mark their distances as their weight - (the distance between node A and its neighbor). - - 3. Choose the neighbor with the shortest distance and mark it as "visited." - - 4. Visit each of its neighbors that haven't been visited yet and calculate their distances by adding the weight - of the edge between them and the current node to the current node's distance. If this distance is shorter than the current distance marked for the node, replace it with the shorter distance. - - 5. Repeat steps 3 and 4 until you reach the destination node or until all nodes have been visited. - - 6. Once you've reached the destination node, the shortest path can be determined by tracing back through the - visited nodes from the destination to the starting point, following the path of the shortest distances. - - Time complexity: - - In the worst case, Dijkstra's algorithm visits every vertex and every edge in the graph. - Each vertex is visited once, and each edge is relaxed once. - Therefore, the time complexity of Dijkstra's algorithm is O(V + E * log V), where V is the number of vertices and E is the number of edges in the graph. - Note that this assumes a priority queue is used to efficiently extract the vertex with the smallest distance. If an array is used instead, the time complexity would be O(V^2 + E). - - Space complexity: - - Dijkstra's algorithm uses two data structures: a priority queue and an array to keep track of the shortest distances from the source vertex to all other vertices. - The priority queue stores at most V vertices at a time. - The array has V entries. - Therefore, the space complexity of Dijkstra's algorithm is O(V). -*/ package main -import ( - "container/heap" - "fmt" - "math" -) - -// priorityQueue is a heap-based priority queue of items -type priorityQueue []*item - -// item represents an item in the priority queue -type item struct { - value string // value of the item - priority int // priority of the item (i.e., its distance from the start vertex) -} - -// Len returns the number of items in the priority queue -func (pq priorityQueue) Len() int { - return len(pq) -} - -// Less returns true if item i has higher priority than item j -func (pq priorityQueue) Less(i, j int) bool { - return pq[i].priority < pq[j].priority -} - -// Swap swaps the positions of items i and j in the priority queue -func (pq priorityQueue) Swap(i, j int) { - pq[i], pq[j] = pq[j], pq[i] -} - -// Push adds an item to the priority queue -func (pq *priorityQueue) Push(x interface{}) { - item := x.(*item) - *pq = append(*pq, item) -} - -// Pop removes the item with the highest priority from the priority queue and returns it -func (pq *priorityQueue) Pop() interface{} { - old := *pq - n := len(old) - item := old[n-1] - *pq = old[0 : n-1] - return item -} - -// Dijkstra's algorithm finds the shortest path between a start vertex and all other vertices in a weighted graph. -// It returns a map of the shortest distance to each vertex and the previous vertex on the shortest path. -// If a vertex is unreachable, its distance is set to infinity. -func Dijkstra(graph map[string]map[string]int, start string) (map[string]int, map[string]string) { - dist := make(map[string]int) // distances from start vertex to each vertex - prev := make(map[string]string) // previous vertex on the shortest path from start to each vertex - queue := make(priorityQueue, 0) // priority queue to track next vertex to visit - - // initialize distances and previous vertices - for v := range graph { - dist[v] = math.MaxInt32 // initialize all distances to infinity - prev[v] = "" // initialize all previous vertices to empty +import "math" +func DijkstrasAlgorithm(start int, edges [][][]int) []int { + numberOfVertices := len(edges) + minDistances := make([]int, 0, len(edges)) + for range edges { + minDistances = append(minDistances, math.MaxInt32) } - dist[start] = 0 // distance from start vertex to itself is 0 - - // add start vertex to priority queue - heap.Push(&queue, &item{value: start, priority: 0}) - - // loop until priority queue is empty - for queue.Len() > 0 { - // remove vertex with minimum distance from priority queue - u := heap.Pop(&queue).(*item).value - - // loop through neighbors of current vertex - for v, w := range graph[u] { - alt := dist[u] + w // calculate alternate distance to neighbor - - // if alternate distance is shorter than current distance, update distances and previous vertices - if alt < dist[v] { - dist[v] = alt - prev[v] = u - - // add neighbor to priority queue - heap.Push(&queue, &item{value: v, priority: alt}) + minDistances[start] = 0 + visited := map[int]bool{} + + for len(visited) != numberOfVertices { + vertex, currentMinDistance := getVertexWithMinDistance(minDistances, visited) + if currentMinDistance == math.MaxInt32 { + break + } + visited[vertex] = true + + for _, edge := range edges[vertex] { + destination, distanceToDestination := edge[0], edge[1] + if visited[destination] { + continue + } + newPathDistance := currentMinDistance + distanceToDestination + currentDestinationDistance := minDistances[destination] + if newPathDistance < currentDestinationDistance { + minDistances[destination] = newPathDistance } } } - - return dist, prev + finalDistances := make([]int, 0, len(minDistances)) + for _, distance := range minDistances { + if distance == math.MaxInt32 { + finalDistances = append(finalDistances, -1) + } else { + finalDistances = append(finalDistances, distance) + } + } + return finalDistances } -func main() { +func getVertexWithMinDistance(distances []int, visited map[int]bool) (int, int) { + currentMinDistance := math.MaxInt32 + vertex := -1 - graph := map[string]map[string]int{ - "A": {"B": 2, "C": 3}, - "B": {"C": 1, "D": 1}, - "C": {"D": 4}, - "D": {"C": 2}, - } - start := "A" - distances, _ := Dijkstra(graph, start) - fmt.Println("Shortest distances from", start, "to all other nodes:") - for node, distance := range distances { - fmt.Println(node, distance) -} + for vertexIdx, distance := range distances { + if visited[vertexIdx] { + continue + } + if distance <= currentMinDistance { + vertex = vertexIdx + currentMinDistance = distance + } + } + return vertex, currentMinDistance } \ No newline at end of file From eacc2c035dbe7c4e79b9ea6059068968720460f2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Jul 2023 23:30:36 +0530 Subject: [PATCH 1653/1894] add comments --- Graphs/dijkstras.go | 153 ++++++++++++++++++++++++++++++-------------- 1 file changed, 104 insertions(+), 49 deletions(-) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 303e786c..321feded 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,57 +1,112 @@ +/* + Explanation: + + The code snippet is an implementation of Dijkstra's algorithm for finding the shortest path from a given starting vertex to all other vertices in a graph. Here's a breakdown of the code: + + 1. The `DijkstrasAlgorithm` function takes the starting vertex (`start`) and the graph represented by the adjacency list (`edges`) as input and returns a list of minimum distances from the starting vertex to all other vertices. + + 2. It initializes `numberOfVertices` as the total number of vertices in the graph. + + 3. The `minDistances` slice is initialized with maximum integer values to represent infinity distance for all vertices. The length of `minDistances` is set to the number of vertices. + + 4. The minimum distance from the starting vertex to itself is set to 0. + + 5. The `visited` map is used to keep track of visited vertices. Initially, it is empty. + + 6. The algorithm iterates until all vertices have been visited. In each iteration, it selects the vertex with the minimum distance from the `minDistances` slice using the `getVertexWithMinDistance` function. + + 7. If the current minimum distance is infinity (i.e., no more vertices to visit), the loop breaks. + + 8. The selected vertex is marked as visited by adding it to the `visited` map. + + 9. For each neighboring vertex of the selected vertex, it calculates the new path distance and updates the `minDistances` if the new distance is smaller. + + 10. After all iterations, the `finalDistances` slice is created to convert the `minDistances` into a format where unreachable vertices are represented as -1. + + 11. The `getVertexWithMinDistance` function returns the vertex with the minimum distance from the `distances` slice and the current minimum distance. + + Overall, the code implements Dijkstra's algorithm to find the shortest path from a starting vertex to all other vertices in a graph, using an adjacency list representation. It keeps track of minimum distances, visited vertices, and updates the distances based on the neighboring vertices. +*/ package main import "math" + +// DijkstrasAlgorithm finds the shortest path from a starting vertex to all other vertices in a graph. func DijkstrasAlgorithm(start int, edges [][][]int) []int { numberOfVertices := len(edges) - minDistances := make([]int, 0, len(edges)) - for range edges { - minDistances = append(minDistances, math.MaxInt32) - } - minDistances[start] = 0 - visited := map[int]bool{} - - for len(visited) != numberOfVertices { - vertex, currentMinDistance := getVertexWithMinDistance(minDistances, visited) - if currentMinDistance == math.MaxInt32 { - break - } - visited[vertex] = true - - for _, edge := range edges[vertex] { - destination, distanceToDestination := edge[0], edge[1] - if visited[destination] { - continue - } - newPathDistance := currentMinDistance + distanceToDestination - currentDestinationDistance := minDistances[destination] - if newPathDistance < currentDestinationDistance { - minDistances[destination] = newPathDistance - } - } - } - finalDistances := make([]int, 0, len(minDistances)) - for _, distance := range minDistances { - if distance == math.MaxInt32 { - finalDistances = append(finalDistances, -1) - } else { - finalDistances = append(finalDistances, distance) - } - } - return finalDistances + minDistances := make([]int, 0, len(edges)) + + // Initialize the minDistances slice with maximum integer values + for range edges { + minDistances = append(minDistances, math.MaxInt32) + } + + // Set the distance of the starting vertex to 0 + minDistances[start] = 0 + visited := map[int]bool{} + + // Iterate until all vertices have been visited + for len(visited) != numberOfVertices { + // Get the vertex with the minimum distance + vertex, currentMinDistance := getVertexWithMinDistance(minDistances, visited) + + // If the current minimum distance is infinity, break the loop + if currentMinDistance == math.MaxInt32 { + break + } + + // Mark the vertex as visited + visited[vertex] = true + + // Explore neighboring vertices + for _, edge := range edges[vertex] { + destination, distanceToDestination := edge[0], edge[1] + + // Skip if the destination vertex is already visited + if visited[destination] { + continue + } + + // Calculate the new path distance to the destination + newPathDistance := currentMinDistance + distanceToDestination + currentDestinationDistance := minDistances[destination] + + // Update the minimum distance if the new distance is smaller + if newPathDistance < currentDestinationDistance { + minDistances[destination] = newPathDistance + } + } + } + + // Convert the minDistances slice to finalDistances, representing unreachable vertices as -1 + finalDistances := make([]int, 0, len(minDistances)) + for _, distance := range minDistances { + if distance == math.MaxInt32 { + finalDistances = append(finalDistances, -1) + } else { + finalDistances = append(finalDistances, distance) + } + } + + return finalDistances } +// getVertexWithMinDistance returns the vertex with the minimum distance from the distances slice. func getVertexWithMinDistance(distances []int, visited map[int]bool) (int, int) { - currentMinDistance := math.MaxInt32 - vertex := -1 - - for vertexIdx, distance := range distances { - if visited[vertexIdx] { - continue - } - if distance <= currentMinDistance { - vertex = vertexIdx - currentMinDistance = distance - } - } - return vertex, currentMinDistance -} \ No newline at end of file + currentMinDistance := math.MaxInt32 + vertex := -1 + + // Find the vertex with the minimum distance among unvisited vertices + for vertexIdx, distance := range distances { + if visited[vertexIdx] { + continue + } + + if distance <= currentMinDistance { + vertex = vertexIdx + currentMinDistance = distance + } + } + + return vertex, currentMinDistance +} From 4ac54ef2439a87e09629b6bb06a3f0a43b9f9590 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Jul 2023 23:32:24 +0530 Subject: [PATCH 1654/1894] add question --- Graphs/dijkstras.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index 321feded..b42c022b 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -1,4 +1,9 @@ /* + + Write a function that computes the lengths of the shortest paths between start and all of the other vertices in the graph using Dijkstra's algorithm and returns them in an array. + + Dijkstras Algorithm + Explanation: The code snippet is an implementation of Dijkstra's algorithm for finding the shortest path from a given starting vertex to all other vertices in a graph. Here's a breakdown of the code: From 3f4a0462d8a10127a41b833cc74ddb837fc2bd6b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Jul 2023 23:33:18 +0530 Subject: [PATCH 1655/1894] add sample io --- Graphs/dijkstras.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index b42c022b..c3376793 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -2,6 +2,18 @@ Write a function that computes the lengths of the shortest paths between start and all of the other vertices in the graph using Dijkstra's algorithm and returns them in an array. + Sample Input: + Start: 0 + Edges : = [ + [[1, 7]], + [[2, 6], [3, 20], [4, 3]], + [[3, 14]], + [[4, 2]], + [], + [], + ] + Output: [0, 7, 13, 27, 10, -1] + Dijkstras Algorithm Explanation: From df262827e865c07e999a96be3c0d506962920f43 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 17 Jul 2023 23:36:22 +0530 Subject: [PATCH 1656/1894] add time and space --- Graphs/dijkstras.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Graphs/dijkstras.go b/Graphs/dijkstras.go index c3376793..3376d266 100644 --- a/Graphs/dijkstras.go +++ b/Graphs/dijkstras.go @@ -43,6 +43,9 @@ 11. The `getVertexWithMinDistance` function returns the vertex with the minimum distance from the `distances` slice and the current minimum distance. Overall, the code implements Dijkstra's algorithm to find the shortest path from a starting vertex to all other vertices in a graph, using an adjacency list representation. It keeps track of minimum distances, visited vertices, and updates the distances based on the neighboring vertices. + + Time Complexity: O(V^2 + e) + Space complexity: O(V) */ package main From 39e83531480cd5ea8bb86c65b925198129cd1dd1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Jul 2023 19:36:37 +0530 Subject: [PATCH 1657/1894] add heap based dijkstras in go --- Graphs/dijkstras_heap_based.go | 120 +++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Graphs/dijkstras_heap_based.go diff --git a/Graphs/dijkstras_heap_based.go b/Graphs/dijkstras_heap_based.go new file mode 100644 index 00000000..3ec7b5d0 --- /dev/null +++ b/Graphs/dijkstras_heap_based.go @@ -0,0 +1,120 @@ +package main +import "math" +func DijkstrasAlgorithm(start int, edges [][][]int) []int { + numberOfVertices := len(edges) + minDistances := make([]int, 0, numberOfVertices) + for range edges { + minDistances = append(minDistances, math.MaxInt32) + } + minDistances[start] = 0 + + minDistancePairs := make([]Item, 0, len(edges)) + for i := range edges { + minDistancePairs = append(minDistancePairs, Item{i, math.MaxInt32}) + } + minDistancesHeap := NewMinHeap(minDistancePairs) + minDistancesHeap.Update(start, 0) + + for !minDistancesHeap.IsEmpty() { + vertex, currentMinDistance := minDistancesHeap.Remove() + if currentMinDistance == math.MaxInt32 { + break + } + for _, edge := range edges[vertex] { + destination, distanceToDestination := edge[0], edge[1] + newPathDistance := currentMinDistance + distanceToDestination + currentDestinationDistance := minDistances[destination] + if newPathDistance < currentDestinationDistance { + minDistances[destination] = newPathDistance + minDistancesHeap.Update(destination, newPathDistance) + } + } + } + finalDistances := make([]int, 0, len(minDistances)) + for _, distance := range minDistances { + if distance == math.MaxInt32 { + finalDistances = append(finalDistances, -1) + } else { + finalDistances = append(finalDistances, distance) + } + } + return finalDistances +} + +type Item struct { + Vertex int + Distance int +} +type MinHeap struct { + array []Item + vertexMap map[int]int +} +func NewMinHeap(array []Item) *MinHeap { + vertexMap := map[int]int{} + for _, item := range array { + vertexMap[item.Vertex] = item.Vertex + } + heap := &MinHeap{array: array, vertexMap: vertexMap} + heap.buildHeap() + return heap +} +func (h *MinHeap) IsEmpty() bool { return h.length() == 0 } + +func (h *MinHeap) Remove() (int, int) { + l := h.length() + h.swap(0, l - 1) + peeked := h.array[l-1] + h.array = h.array[0: l - 1] + delete(h.vertexMap, peeked.Vertex) + h.siftDown(0, l - 2) + return peeked.Vertex, peeked.Distance +} + +func (h *MinHeap) Update(vertex int, value int) { + h.array[h.vertexMap[vertex]] = Item{vertex, value} + h.siftUp(h.vertexMap[vertex]) +} + +func (h MinHeap) swap(i, j int) { + h.vertexMap[h.array[i].Vertex] = j + h.vertexMap[h.array[j].Vertex] = i + h.array[i], h.array[j] = h.array[j], h.array[i] +} + +func (h MinHeap) length() int { return len(h.array) } + +func (h *MinHeap) buildHeap() { + first := (len(h.array) - 2) / 2 + for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { + h.siftDown(currentIdx, len(h.array) - 1) + } +} +func (h *MinHeap)siftDown(currentIdx, endIdx int) { + childOneIdx := currentIdx * 2 + 1 + for childOneIdx <= endIdx { + childTwoIdx := -1 + if currentIdx * 2 + 2 <= endIdx { + childTwoIdx = currentIdx * 2 + 2 + } + indexToSwap := childOneIdx + if childTwoIdx > -1 && h.array[childTwoIdx].Distance < h.array[childOneIdx].Distance { + indexToSwap = childTwoIdx + } + if h.array[indexToSwap].Distance < h.array[currentIdx].Distance { + h.swap(currentIdx, indexToSwap) + currentIdx = indexToSwap + childOneIdx = currentIdx * 2 + 1 + } else { + return + } + } +} + +func (h * MinHeap) siftUp(currentIdx int) { + parentIdx := (currentIdx - 1) / 2 + for currentIdx > 0 && h.array[currentIdx].Distance < h.array[parentIdx].Distance { + h.swap(currentIdx, parentIdx) + currentIdx = parentIdx + parentIdx = (currentIdx - 1) / 2 + } +} \ No newline at end of file From 4def771dddfb82174c6b7da08d8da383c289cc7f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Jul 2023 19:36:52 +0530 Subject: [PATCH 1658/1894] add comments --- Graphs/dijkstras_heap_based.go | 229 ++++++++++++++++++++------------- 1 file changed, 136 insertions(+), 93 deletions(-) diff --git a/Graphs/dijkstras_heap_based.go b/Graphs/dijkstras_heap_based.go index 3ec7b5d0..aded2391 100644 --- a/Graphs/dijkstras_heap_based.go +++ b/Graphs/dijkstras_heap_based.go @@ -1,120 +1,163 @@ package main + import "math" + +// DijkstrasAlgorithm finds the shortest distances from the start vertex to all other vertices using Dijkstra's algorithm. func DijkstrasAlgorithm(start int, edges [][][]int) []int { + // Get the number of vertices in the graph. numberOfVertices := len(edges) - minDistances := make([]int, 0, numberOfVertices) - for range edges { - minDistances = append(minDistances, math.MaxInt32) - } - minDistances[start] = 0 - - minDistancePairs := make([]Item, 0, len(edges)) - for i := range edges { - minDistancePairs = append(minDistancePairs, Item{i, math.MaxInt32}) - } - minDistancesHeap := NewMinHeap(minDistancePairs) - minDistancesHeap.Update(start, 0) - - for !minDistancesHeap.IsEmpty() { - vertex, currentMinDistance := minDistancesHeap.Remove() - if currentMinDistance == math.MaxInt32 { - break - } - for _, edge := range edges[vertex] { - destination, distanceToDestination := edge[0], edge[1] - newPathDistance := currentMinDistance + distanceToDestination - currentDestinationDistance := minDistances[destination] - if newPathDistance < currentDestinationDistance { - minDistances[destination] = newPathDistance - minDistancesHeap.Update(destination, newPathDistance) - } - } - } - finalDistances := make([]int, 0, len(minDistances)) - for _, distance := range minDistances { - if distance == math.MaxInt32 { - finalDistances = append(finalDistances, -1) - } else { - finalDistances = append(finalDistances, distance) - } - } - return finalDistances + + // Initialize the minDistances array with maximum integer values except for the start vertex, which is set to 0. + minDistances := make([]int, 0, numberOfVertices) + for range edges { + minDistances = append(minDistances, math.MaxInt32) + } + minDistances[start] = 0 + + // Create a min-heap to store vertices and their distances from the start vertex. + minDistancePairs := make([]Item, 0, len(edges)) + for i := range edges { + minDistancePairs = append(minDistancePairs, Item{i, math.MaxInt32}) + } + minDistancesHeap := NewMinHeap(minDistancePairs) + minDistancesHeap.Update(start, 0) + + // Explore vertices in the graph using Dijkstra's algorithm until all vertices have been visited. + for !minDistancesHeap.IsEmpty() { + vertex, currentMinDistance := minDistancesHeap.Remove() + + // If the currentMinDistance is still set to the maximum integer value, there is no path from the start vertex to this vertex. + if currentMinDistance == math.MaxInt32 { + break + } + + // Explore the outgoing edges of the current vertex. + for _, edge := range edges[vertex] { + destination, distanceToDestination := edge[0], edge[1] + + // Calculate the new path distance from the start vertex to the destination vertex through the current vertex. + newPathDistance := currentMinDistance + distanceToDestination + + // Update the minDistances array and the minDistancesHeap with the new distance if it is smaller. + currentDestinationDistance := minDistances[destination] + if newPathDistance < currentDestinationDistance { + minDistances[destination] = newPathDistance + minDistancesHeap.Update(destination, newPathDistance) + } + } + } + + // Construct the finalDistances array based on the minDistances array. + finalDistances := make([]int, 0, len(minDistances)) + for _, distance := range minDistances { + // If a vertex's distance is still set to the maximum integer value, there is no path from the start vertex to that vertex. + // So, -1 is stored instead. + if distance == math.MaxInt32 { + finalDistances = append(finalDistances, -1) + } else { + finalDistances = append(finalDistances, distance) + } + } + + return finalDistances } +// Item represents a vertex and its distance in the min-heap. type Item struct { - Vertex int - Distance int + Vertex int // Vertex represents the index of the vertex. + Distance int // Distance represents the distance from the start vertex to the current vertex. } + +// MinHeap represents a min-heap data structure. type MinHeap struct { - array []Item - vertexMap map[int]int + array []Item // array is an array of Item structs to represent the heap. + vertexMap map[int]int // vertexMap is a map to efficiently update and access items in the heap. } + +// NewMinHeap creates a new MinHeap instance with the given array of items. func NewMinHeap(array []Item) *MinHeap { - vertexMap := map[int]int{} - for _, item := range array { - vertexMap[item.Vertex] = item.Vertex - } - heap := &MinHeap{array: array, vertexMap: vertexMap} - heap.buildHeap() - return heap + // Initialize the vertexMap to store the index of each vertex in the heap. + vertexMap := map[int]int{} + for _, item := range array { + vertexMap[item.Vertex] = item.Vertex + } + + // Create the MinHeap with the array and vertexMap. + heap := &MinHeap{array: array, vertexMap: vertexMap} + heap.buildHeap() + return heap } -func (h *MinHeap) IsEmpty() bool { return h.length() == 0 } +// IsEmpty checks if the min-heap is empty. +func (h *MinHeap) IsEmpty() bool { + return h.length() == 0 +} + +// Remove removes the item with the minimum distance from the heap and returns its vertex and distance. func (h *MinHeap) Remove() (int, int) { - l := h.length() - h.swap(0, l - 1) - peeked := h.array[l-1] - h.array = h.array[0: l - 1] - delete(h.vertexMap, peeked.Vertex) - h.siftDown(0, l - 2) - return peeked.Vertex, peeked.Distance + l := h.length() + h.swap(0, l-1) + peeked := h.array[l-1] + h.array = h.array[0:l-1] + delete(h.vertexMap, peeked.Vertex) + h.siftDown(0, l-2) + return peeked.Vertex, peeked.Distance } +// Update updates the distance of a vertex in the heap and maintains the heap property. func (h *MinHeap) Update(vertex int, value int) { - h.array[h.vertexMap[vertex]] = Item{vertex, value} - h.siftUp(h.vertexMap[vertex]) + h.array[h.vertexMap[vertex]] = Item{vertex, value} + h.siftUp(h.vertexMap[vertex]) } +// swap swaps two items in the min-heap. func (h MinHeap) swap(i, j int) { - h.vertexMap[h.array[i].Vertex] = j - h.vertexMap[h.array[j].Vertex] = i - h.array[i], h.array[j] = h.array[j], h.array[i] + h.vertexMap[h.array[i].Vertex] = j + h.vertexMap[h.array[j].Vertex] = i + h.array[i], h.array[j] = h.array[j], h.array[i] } -func (h MinHeap) length() int { return len(h.array) } +// length returns the length of the min-heap. +func (h MinHeap) length() int { + return len(h.array) +} +// buildHeap performs the build-heap operation on the min-heap. func (h *MinHeap) buildHeap() { - first := (len(h.array) - 2) / 2 - for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { - h.siftDown(currentIdx, len(h.array) - 1) - } + first := (len(h.array) - 2) / 2 + for currentIdx := first + 1; currentIdx >= 0; currentIdx-- { + h.siftDown(currentIdx, len(h.array)-1) + } } -func (h *MinHeap)siftDown(currentIdx, endIdx int) { - childOneIdx := currentIdx * 2 + 1 - for childOneIdx <= endIdx { - childTwoIdx := -1 - if currentIdx * 2 + 2 <= endIdx { - childTwoIdx = currentIdx * 2 + 2 - } - indexToSwap := childOneIdx - if childTwoIdx > -1 && h.array[childTwoIdx].Distance < h.array[childOneIdx].Distance { - indexToSwap = childTwoIdx - } - if h.array[indexToSwap].Distance < h.array[currentIdx].Distance { - h.swap(currentIdx, indexToSwap) - currentIdx = indexToSwap - childOneIdx = currentIdx * 2 + 1 - } else { - return - } - } + +// siftDown performs the sift-down operation to maintain the heap property. +func (h *MinHeap) siftDown(currentIdx, endIdx int) { + childOneIdx := currentIdx*2 + 1 + for childOneIdx <= endIdx { + childTwoIdx := -1 + if currentIdx*2+2 <= endIdx { + childTwoIdx = currentIdx*2 + 2 + } + indexToSwap := childOneIdx + if childTwoIdx > -1 && h.array[childTwoIdx].Distance < h.array[childOneIdx].Distance { + indexToSwap = childTwoIdx + } + if h.array[indexToSwap].Distance < h.array[currentIdx].Distance { + h.swap(currentIdx, indexToSwap) + currentIdx = indexToSwap + childOneIdx = currentIdx*2 + 1 + } else { + return + } + } } -func (h * MinHeap) siftUp(currentIdx int) { - parentIdx := (currentIdx - 1) / 2 - for currentIdx > 0 && h.array[currentIdx].Distance < h.array[parentIdx].Distance { - h.swap(currentIdx, parentIdx) - currentIdx = parentIdx - parentIdx = (currentIdx - 1) / 2 - } -} \ No newline at end of file +// siftUp performs the sift-up operation to maintain the heap property. +func (h *MinHeap) siftUp(currentIdx int) { + parentIdx := (currentIdx - 1) / 2 + for currentIdx > 0 && h.array[currentIdx].Distance < h.array[parentIdx].Distance { + h.swap(currentIdx, parentIdx) + currentIdx = parentIdx + parentIdx = (currentIdx - 1) / 2 + } +} From 396f535d74898f49dc488e2a6c002f45c7e6bb3f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Jul 2023 19:38:41 +0530 Subject: [PATCH 1659/1894] reformat --- Graphs/dijkstras_heap_based.go | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Graphs/dijkstras_heap_based.go b/Graphs/dijkstras_heap_based.go index aded2391..af9736a9 100644 --- a/Graphs/dijkstras_heap_based.go +++ b/Graphs/dijkstras_heap_based.go @@ -1,3 +1,51 @@ +/* + Dijkstras heap based + + Explanation: + The given code snippet implements Dijkstra's algorithm to find the shortest path from a given start vertex to all other + vertices in a weighted directed graph. Here's how the code works: + + 1. The `DijkstrasAlgorithm` function takes the start vertex and the edges of the graph as input and returns an array of + shortest distances from the start vertex to all other vertices. + + 2. First, it initializes the `minDistances` array with the maximum integer value except for the start vertex, which is + set to 0. This array will store the minimum distances from the start vertex to each vertex. + + 3. It creates a min-heap data structure called `minDistancesHeap` to keep track of the minimum distances. Each item in + the heap represents a vertex and its distance from the start vertex. + + 4. The algorithm starts by removing the vertex with the minimum distance from the `minDistancesHeap` and explores its + outgoing edges. + + 5. For each edge, it calculates the new path distance from the start vertex to the destination vertex through the + current vertex. If the new path distance is smaller than the current distance, it updates the `minDistances` array and the `minDistancesHeap` with the new distance. + + 6. The process continues until all vertices have been visited. + + 7. Finally, it constructs the final distances array (`finalDistances`) based on the `minDistances` array. If a vertex's + distance is still set to the maximum integer value, it means there is no path from the start vertex to that vertex, so -1 + is stored instead. + + 8. The `Item` struct represents a vertex and its distance in the min-heap. + + 9. The `MinHeap` struct represents the min-heap data structure. It contains an array of `Item` structs and a vertex-to-index + map to efficiently update and access items in the heap. + + 10. The `Remove` method removes the item with the minimum distance from the heap and returns its vertex and distance. + + 11. The `Update` method updates the distance of a vertex in the heap and maintains the heap property by performing sift-up + or sift-down operations. + + 12. The `siftDown` method performs the sift-down operation to maintain the heap property by comparing the distance of the + current item with its children and swapping if necessary. + + 13. The `siftUp` method performs the sift-up operation to maintain the heap property by comparing the distance of the + current item with its parent and swapping if necessary. + + The time complexity of Dijkstra's algorithm with a min-heap implementation is typically O((V + E) log V), where V is the + number of vertices and E is the number of edges in the graph. + The space complexity is O(V) for storing the `minDistances` array and the min-heap. +*/ package main import "math" From d42ca81f16a2e1cd25eb2392f2382162796ecaea Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Jul 2023 19:40:15 +0530 Subject: [PATCH 1660/1894] move to arrays --- four_sum.py => Arrays/four_sum.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename four_sum.py => Arrays/four_sum.py (100%) diff --git a/four_sum.py b/Arrays/four_sum.py similarity index 100% rename from four_sum.py rename to Arrays/four_sum.py From 0223cc3278944dee8dee1fad45d4dd4f93062077 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 18 Jul 2023 19:40:57 +0530 Subject: [PATCH 1661/1894] add underscore naming to files --- Tries/{PatternMatching.cpp => pattern_matching.cpp} | 0 Tries/{SearchInTries.cpp => search_in_tries.cpp} | 0 Tries/{TrieNodeClass.cpp => trie_node_class.cpp} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename Tries/{PatternMatching.cpp => pattern_matching.cpp} (100%) rename Tries/{SearchInTries.cpp => search_in_tries.cpp} (100%) rename Tries/{TrieNodeClass.cpp => trie_node_class.cpp} (100%) diff --git a/Tries/PatternMatching.cpp b/Tries/pattern_matching.cpp similarity index 100% rename from Tries/PatternMatching.cpp rename to Tries/pattern_matching.cpp diff --git a/Tries/SearchInTries.cpp b/Tries/search_in_tries.cpp similarity index 100% rename from Tries/SearchInTries.cpp rename to Tries/search_in_tries.cpp diff --git a/Tries/TrieNodeClass.cpp b/Tries/trie_node_class.cpp similarity index 100% rename from Tries/TrieNodeClass.cpp rename to Tries/trie_node_class.cpp From c8df101ac44caeff7d1d7f504237d3ced68f1ecb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:07:46 +0530 Subject: [PATCH 1662/1894] add topological sort in go --- Graphs/topological_sort.go | 88 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Graphs/topological_sort.go diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go new file mode 100644 index 00000000..fa7b7205 --- /dev/null +++ b/Graphs/topological_sort.go @@ -0,0 +1,88 @@ +package main + +type Dep struct { + Prereq int + Job int +} + +func TopologicalSort(jobs []int, deps []Dep) []int { + jobGraph := createJobGraph(jobs, deps) + return getOrderedJobs(jobGraph) +} + +func createJobGraph(jobs []int, deps []Dep) *JobGraph { + graph := NewJobGraph(jobs) + for _, dep := range deps { + graph.Addprereq(dep.Job, dep.Prereq) + } + return graph +} + +func getOrderedJobs(graph *JobGraph) []int { + orderedJobs := []int{} + nodes := graph.Nodes + for len(nodes) != 0 { + node := nodes[len(nodes) - 1] + nodes = nodes[:len(nodes) - 1] + containsCycle := depthFirstTraverse(node, &orderedJobs) + if containsCycle { + return []int{} + } + } + return orderedJobs +} + +func depthFirstTraverse(node *JobNode, orderedJobs *[]int) bool { + if node.Visited { + return false + } else if node.Visiting { + return true + } + node.Visiting = true + for _, prereqNode := range node.Prereqs { + containsCycle := depthFirstTraverse(prereqNode, orderedJobs) + if containsCycle { + return true + } + } + node.Visited = true + node.Visiting = false + *orderedJobs = append(*orderedJobs, node.Job) + return false +} + +type JobGraph struct { + Nodes []*JobNode + Graph map[int]*JobNode +} +func NewJobGraph(jobs []int) *JobGraph { + g := &JobGraph{ + Graph: map[int]*JobNode{}, + } + for _, job := range jobs { + g.AddNode(job) + } + return g +} +func (g *JobGraph) Addprereq(job, prereq int) { + jobNode := g.GetNode(job) + prereqNode := g.GetNode(prereq) + jobNode.Prereqs = append(jobNode.Prereqs, prereqNode) +} +func (g *JobGraph) AddNode(job int) { + g.Graph[job] = &JobNode{Job: job} + g.Nodes = append(g.Nodes, g.Graph[job]) +} +func (g *JobGraph) GetNode(job int) *JobNode { + if _, found := g.Graph[job]; !found { + g.AddNode(job) + } + return g.Graph[job] +} + +type JobNode struct { + Job int + Prereqs []*JobNode + Visited bool + Visiting bool +} \ No newline at end of file From b9df617e072f80297cd94bbaac3d5b1bd539ad97 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:09:04 +0530 Subject: [PATCH 1663/1894] add question --- Graphs/topological_sort.go | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go index fa7b7205..cd493570 100644 --- a/Graphs/topological_sort.go +++ b/Graphs/topological_sort.go @@ -1,3 +1,14 @@ +/* + You're given a list of arbitrary jobs that need to be completed; these jobs + are represented by distinct integers. You're also given a list of dependencies. A + dependency is represented as a pair of jobs where the first job is a + prerequisite of the second one. In other words, the second job depends on the + first one; it can only be completed once the first job is completed. + + Write a function that takes in a list of jobs and a list of dependencies and + returns a list containing a valid order in which the given jobs can be + completed. If no such order exists, the function should return an empty array. +*/ package main type Dep struct { From cd3643d3326fc85cf00b49b3dcb9e1f7602f037d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:10:06 +0530 Subject: [PATCH 1664/1894] add sample io --- Graphs/topological_sort.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go index cd493570..4254ac6f 100644 --- a/Graphs/topological_sort.go +++ b/Graphs/topological_sort.go @@ -1,4 +1,4 @@ -/* +/* You're given a list of arbitrary jobs that need to be completed; these jobs are represented by distinct integers. You're also given a list of dependencies. A dependency is represented as a pair of jobs where the first job is a @@ -8,6 +8,11 @@ Write a function that takes in a list of jobs and a list of dependencies and returns a list containing a valid order in which the given jobs can be completed. If no such order exists, the function should return an empty array. + + Sample INput: + jobs: [1, 2, 3, 4] + deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] + Output: [1, 4, 3, 2] or [4, 1, 3, 2] */ package main From 31ca93de7cec5ace9c4df7a52ba4d57ce9a036d0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:10:34 +0530 Subject: [PATCH 1665/1894] add comments --- Graphs/topological_sort.go | 155 +++++++++++++++++++++++-------------- 1 file changed, 99 insertions(+), 56 deletions(-) diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go index 4254ac6f..0fa4e8d4 100644 --- a/Graphs/topological_sort.go +++ b/Graphs/topological_sort.go @@ -21,84 +21,127 @@ type Dep struct { Job int } +// TopologicalSort performs topological sorting of jobs given their dependencies. func TopologicalSort(jobs []int, deps []Dep) []int { + // Create a job graph from the list of jobs and dependencies. jobGraph := createJobGraph(jobs, deps) - return getOrderedJobs(jobGraph) + + // Get the ordered jobs using depth-first traversal. + return getOrderedJobs(jobGraph) } +// createJobGraph creates a job graph from the list of jobs and dependencies. func createJobGraph(jobs []int, deps []Dep) *JobGraph { - graph := NewJobGraph(jobs) - for _, dep := range deps { - graph.Addprereq(dep.Job, dep.Prereq) - } - return graph + graph := NewJobGraph(jobs) + for _, dep := range deps { + // Add each dependency as a prerequisite to the corresponding job node in the graph. + graph.Addprereq(dep.Job, dep.Prereq) + } + return graph } +// getOrderedJobs performs a depth-first traversal of the job graph to get the ordered jobs. func getOrderedJobs(graph *JobGraph) []int { - orderedJobs := []int{} - nodes := graph.Nodes - for len(nodes) != 0 { - node := nodes[len(nodes) - 1] - nodes = nodes[:len(nodes) - 1] - containsCycle := depthFirstTraverse(node, &orderedJobs) - if containsCycle { - return []int{} - } - } - return orderedJobs + orderedJobs := []int{} + nodes := graph.Nodes + + // Continue the traversal until all nodes have been visited. + for len(nodes) != 0 { + // Get the last node from the list of nodes and remove it from the list. + node := nodes[len(nodes)-1] + nodes = nodes[:len(nodes)-1] + + // Perform depth-first traversal starting from the current node. + // If a cycle is detected, return an empty list. + containsCycle := depthFirstTraverse(node, &orderedJobs) + if containsCycle { + return []int{} + } + } + return orderedJobs } +// depthFirstTraverse performs depth-first traversal starting from the given node. +// It returns true if a cycle is detected, otherwise, it returns false. func depthFirstTraverse(node *JobNode, orderedJobs *[]int) bool { - if node.Visited { - return false - } else if node.Visiting { - return true - } - node.Visiting = true - for _, prereqNode := range node.Prereqs { - containsCycle := depthFirstTraverse(prereqNode, orderedJobs) - if containsCycle { - return true - } - } - node.Visited = true - node.Visiting = false - *orderedJobs = append(*orderedJobs, node.Job) - return false + // If the node has been visited, it means it is not part of any cycle, so return false. + if node.Visited { + return false + } + // If the node is currently being visited it means there is a cycle, so return true. + if node.Visiting { + return true + } + + // Mark the node as currently being visited. + node.Visiting = true + + // Recursively traverse through each prerequisite of the current node. + for _, prereqNode := range node.Prereqs { + // If a cycle is detected during the traversal, return true. + containsCycle := depthFirstTraverse(prereqNode, orderedJobs) + if containsCycle { + return true + } + } + + // Mark the node as visited and no longer being visited. + node.Visited = true + node.Visiting = false + + // Append the job to the orderedJobs list in the correct order. + *orderedJobs = append(*orderedJobs, node.Job) + + // Return false, as no cycle was detected during the traversal. + return false } +// JobGraph represents the job graph. type JobGraph struct { - Nodes []*JobNode - Graph map[int]*JobNode + Nodes []*JobNode + Graph map[int]*JobNode } + +// NewJobGraph creates a new instance of the JobGraph and initializes its Graph field. func NewJobGraph(jobs []int) *JobGraph { - g := &JobGraph{ - Graph: map[int]*JobNode{}, - } - for _, job := range jobs { - g.AddNode(job) - } - return g + g := &JobGraph{ + Graph: map[int]*JobNode{}, + } + for _, job := range jobs { + // Add individual job nodes to the Nodes list. + g.AddNode(job) + } + return g } + +// Addprereq adds a prerequisite to a job in the job graph. func (g *JobGraph) Addprereq(job, prereq int) { - jobNode := g.GetNode(job) - prereqNode := g.GetNode(prereq) - jobNode.Prereqs = append(jobNode.Prereqs, prereqNode) + jobNode := g.GetNode(job) + prereqNode := g.GetNode(prereq) + // Add the prerequisite node to the list of prerequisites for the job node. + jobNode.Prereqs = append(jobNode.Prereqs, prereqNode) } + +// AddNode adds a new job node to the job graph. func (g *JobGraph) AddNode(job int) { - g.Graph[job] = &JobNode{Job: job} - g.Nodes = append(g.Nodes, g.Graph[job]) + // Create a new job node and add it to the graph and nodes list. + g.Graph[job] = &JobNode{Job: job} + g.Nodes = append(g.Nodes, g.Graph[job]) } + +// GetNode gets an existing job node from the job graph. func (g *JobGraph) GetNode(job int) *JobNode { - if _, found := g.Graph[job]; !found { - g.AddNode(job) - } - return g.Graph[job] + // If the node does not exist in the graph, create a new node and add it to the graph. + if _, found := g.Graph[job]; !found { + g.AddNode(job) + } + return g.Graph[job] } +// JobNode represents a node in the job graph. type JobNode struct { - Job int - Prereqs []*JobNode - Visited bool - Visiting bool -} \ No newline at end of file + Job int + Prereqs []*JobNode + Visited bool + Visiting bool +} From b1d9c748184652523509ecbcd5fb8ef0708688b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:11:14 +0530 Subject: [PATCH 1666/1894] add explanation --- Graphs/topological_sort.go | 81 +++++++++++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 14 deletions(-) diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go index 0fa4e8d4..cfbfd0e2 100644 --- a/Graphs/topological_sort.go +++ b/Graphs/topological_sort.go @@ -1,18 +1,71 @@ /* - You're given a list of arbitrary jobs that need to be completed; these jobs - are represented by distinct integers. You're also given a list of dependencies. A - dependency is represented as a pair of jobs where the first job is a - prerequisite of the second one. In other words, the second job depends on the - first one; it can only be completed once the first job is completed. - - Write a function that takes in a list of jobs and a list of dependencies and - returns a list containing a valid order in which the given jobs can be - completed. If no such order exists, the function should return an empty array. - - Sample INput: - jobs: [1, 2, 3, 4] - deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] - Output: [1, 4, 3, 2] or [4, 1, 3, 2] + You're given a list of arbitrary jobs that need to be completed; these jobs + are represented by distinct integers. You're also given a list of dependencies. A + dependency is represented as a pair of jobs where the first job is a + prerequisite of the second one. In other words, the second job depends on the + first one; it can only be completed once the first job is completed. + + Write a function that takes in a list of jobs and a list of dependencies and + returns a list containing a valid order in which the given jobs can be + completed. If no such order exists, the function should return an empty array. + + Sample INput: + jobs: [1, 2, 3, 4] + deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] + Output: [1, 4, 3, 2] or [4, 1, 3, 2] + + Explanation: + The provided code implements a topological sorting algorithm to find the order in which jobs can be executed given their dependencies. It uses a directed acyclic graph (DAG) representation to represent the jobs and their dependencies. + + Let's go through each part of the code in detail: + + 1. `Dep` struct: + - This is a simple struct that represents a dependency between two jobs. + - `Prereq` field indicates the prerequisite job. + - `Job` field indicates the job that depends on the prerequisite. + + 2. `TopologicalSort` function: + - This is the main function that performs the topological sorting of jobs. + - It takes two input parameters: `jobs`, a list of job IDs, and `deps`, a list of dependencies. + - It first creates a job graph using the `createJobGraph` function and then gets the ordered jobs using the `getOrderedJobs` function. + + 3. `createJobGraph` function: + - This function creates a job graph from the list of jobs and dependencies. + - It creates a new instance of the `JobGraph` struct and iterates through the dependencies. + - For each dependency, it adds the prerequisite job to the dependent job's list of prerequisites in the job graph. + + 4. `getOrderedJobs` function: + - This function performs a depth-first traversal of the job graph to get the ordered jobs. + - It iterates through the nodes of the graph until all nodes have been visited. + - For each node, it calls the `depthFirstTraverse` function to perform the depth-first traversal and get the ordered jobs. + - If a cycle is detected in the graph during the traversal, it means that there is a circular dependency, and the function returns an empty list. + + 5. `depthFirstTraverse` function: + - This function performs the depth-first traversal of the graph starting from a given node. + - It checks if the current node has been visited (i.e., it is not part of any cycle). + - If the node is currently being visited (marked as `Visiting`), it means that there is a cycle, and the function returns `true`. + - Otherwise, it marks the node as `Visiting`, recursively traverses through its prerequisites, and marks it as `Visited` after the traversal. + - It appends the job to the `orderedJobs` list in the correct order. + + 6. `JobGraph` struct: + - This struct represents the job graph. + - `Nodes` is a list of all the job nodes in the graph. + - `Graph` is a map where the key is the job ID, and the value is a pointer to the corresponding `JobNode` in the graph. + + 7. `NewJobGraph` function: + - This function creates a new instance of the `JobGraph` struct and initializes its `Graph` field with an empty map. + - It also adds individual job nodes to the `Nodes` list. + + 8. `Addprereq`, `AddNode`, and `GetNode` functions: + - These are helper functions to add prerequisites to a job, add a new job node to the graph, and get an existing job node, respectively. + + 9. `JobNode` struct: + - This struct represents a node in the job graph. + - `Job` is the job ID. + - `Prereqs` is a list of pointers to other job nodes that are prerequisites for the current job. + - `Visited` and `Visiting` are boolean flags used during the depth-first traversal to track the traversal status of each node. + + Overall, the code implements the topological sorting algorithm using depth-first traversal to find the order in which jobs can be executed without violating their dependencies. It efficiently handles circular dependencies and returns the ordered jobs or an empty list if a circular dependency is detected. */ package main From 36521680f0bb14d1cb1fc9d5835bcf811b02f183 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 19 Jul 2023 23:11:35 +0530 Subject: [PATCH 1667/1894] add time and space complexity --- Graphs/topological_sort.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Graphs/topological_sort.go b/Graphs/topological_sort.go index cfbfd0e2..b88bed00 100644 --- a/Graphs/topological_sort.go +++ b/Graphs/topological_sort.go @@ -66,6 +66,8 @@ - `Visited` and `Visiting` are boolean flags used during the depth-first traversal to track the traversal status of each node. Overall, the code implements the topological sorting algorithm using depth-first traversal to find the order in which jobs can be executed without violating their dependencies. It efficiently handles circular dependencies and returns the ordered jobs or an empty list if a circular dependency is detected. + + O(j + d) time | O(j + d) space - where j is the number of jobs and d is the number of dependencies */ package main From 12748c3fee278c1e1633d85e8c9b205af3eb0abf Mon Sep 17 00:00:00 2001 From: "ASHWIN A.R" Date: Thu, 20 Jul 2023 01:42:19 +0530 Subject: [PATCH 1668/1894] create non-overlapping intervals.cpp non-overlapping intervals --- non-overlapping intervals.cpp | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 non-overlapping intervals.cpp diff --git a/non-overlapping intervals.cpp b/non-overlapping intervals.cpp new file mode 100644 index 00000000..6f99e68a --- /dev/null +++ b/non-overlapping intervals.cpp @@ -0,0 +1,50 @@ +Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. +Example 1: + +Input: intervals = [[1,2],[2,3],[3,4],[1,3]] +Output: 1 +Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. +Example 2: + +Input: intervals = [[1,2],[1,2],[1,2]] +Output: 2 +Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. +Example 3: + +Input: intervals = [[1,2],[2,3]] +Output: 0 +Explanation: You don't need to remove any of the intervals since they're already non-overlapping. + + +Constraints: +1 <= intervals.length <= 105 +intervals[i].length == 2 +-5 * 104 <= starti < endi <= 5 * 104 + + CODE: + + class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + sort(intervals.begin(),intervals.end()); + int previous = 0; + int n = intervals.size(); + int ans = 0; + for(int current = 1;current Date: Thu, 20 Jul 2023 23:11:50 +0530 Subject: [PATCH 1669/1894] add cpp version of topo sort --- Graphs/topological_sort.cpp | 213 ++++++++++++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 Graphs/topological_sort.cpp diff --git a/Graphs/topological_sort.cpp b/Graphs/topological_sort.cpp new file mode 100644 index 00000000..95115b3f --- /dev/null +++ b/Graphs/topological_sort.cpp @@ -0,0 +1,213 @@ +/* + You're given a list of arbitrary jobs that need to be completed; these jobs + are represented by distinct integers. You're also given a list of dependencies. A + dependency is represented as a pair of jobs where the first job is a + prerequisite of the second one. In other words, the second job depends on the + first one; it can only be completed once the first job is completed. + + Write a function that takes in a list of jobs and a list of dependencies and + returns a list containing a valid order in which the given jobs can be + completed. If no such order exists, the function should return an empty array. + + Sample INput: + jobs: [1, 2, 3, 4] + deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] + Output: [1, 4, 3, 2] or [4, 1, 3, 2] + + Explanation: + The provided code implements a topological sorting algorithm to find the order in which jobs can be executed given their dependencies. It uses a directed acyclic graph (DAG) representation to represent the jobs and their dependencies. + + Let's go through each part of the code in detail: + + 1. `Dep` struct: + - This is a simple struct that represents a dependency between two jobs. + - `Prereq` field indicates the prerequisite job. + - `Job` field indicates the job that depends on the prerequisite. + + 2. `TopologicalSort` function: + - This is the main function that performs the topological sorting of jobs. + - It takes two input parameters: `jobs`, a list of job IDs, and `deps`, a list of dependencies. + - It first creates a job graph using the `createJobGraph` function and then gets the ordered jobs using the `getOrderedJobs` function. + + 3. `createJobGraph` function: + - This function creates a job graph from the list of jobs and dependencies. + - It creates a new instance of the `JobGraph` struct and iterates through the dependencies. + - For each dependency, it adds the prerequisite job to the dependent job's list of prerequisites in the job graph. + + 4. `getOrderedJobs` function: + - This function performs a depth-first traversal of the job graph to get the ordered jobs. + - It iterates through the nodes of the graph until all nodes have been visited. + - For each node, it calls the `depthFirstTraverse` function to perform the depth-first traversal and get the ordered jobs. + - If a cycle is detected in the graph during the traversal, it means that there is a circular dependency, and the function returns an empty list. + + 5. `depthFirstTraverse` function: + - This function performs the depth-first traversal of the graph starting from a given node. + - It checks if the current node has been visited (i.e., it is not part of any cycle). + - If the node is currently being visited (marked as `Visiting`), it means that there is a cycle, and the function returns `true`. + - Otherwise, it marks the node as `Visiting`, recursively traverses through its prerequisites, and marks it as `Visited` after the traversal. + - It appends the job to the `orderedJobs` list in the correct order. + + 6. `JobGraph` struct: + - This struct represents the job graph. + - `Nodes` is a list of all the job nodes in the graph. + - `Graph` is a map where the key is the job ID, and the value is a pointer to the corresponding `JobNode` in the graph. + + 7. `NewJobGraph` function: + - This function creates a new instance of the `JobGraph` struct and initializes its `Graph` field with an empty map. + - It also adds individual job nodes to the `Nodes` list. + + 8. `Addprereq`, `AddNode`, and `GetNode` functions: + - These are helper functions to add prerequisites to a job, add a new job node to the graph, and get an existing job node, respectively. + + 9. `JobNode` struct: + - This struct represents a node in the job graph. + - `Job` is the job ID. + - `Prereqs` is a list of pointers to other job nodes that are prerequisites for the current job. + - `Visited` and `Visiting` are boolean flags used during the depth-first traversal to track the traversal status of each node. + + Overall, the code implements the topological sorting algorithm using depth-first traversal to find the order in which jobs can be executed without violating their dependencies. It efficiently handles circular dependencies and returns the ordered jobs or an empty list if a circular dependency is detected. + + O(j + d) time | O(j + d) space - where j is the number of jobs and d is the number of dependencies +*/ +#include +#include + +using namespace std; + +struct Dep { + int Prereq; + int Job; +}; + +class JobGraph; + +// Function prototypes +JobGraph createJobGraph(vector& jobs, vector& deps); +vector getOrderedJobs(JobGraph& graph); +bool depthFirstTraverse(JobGraph& graph, int jobId, vector& orderedJobs); + +class JobGraph { +public: + // Constructor to create a job graph from a list of jobs + JobGraph(vector& jobs) { + for (int job : jobs) { + // Add each job as a node to the graph + addNode(job); + } + } + + // Function to add a prerequisite to a job node + void addPrereq(int job, int prereq) { + JobNode* jobNode = getNode(job); + JobNode* prereqNode = getNode(prereq); + // Add the prerequisite node to the list of prerequisites for the job node + jobNode->prereqs.push_back(prereqNode); + } + + // Function to add a new job node to the graph + void addNode(int job) { + // Create a new job node and add it to the graph and nodes list + graph[job] = new JobNode(job); + nodes.push_back(graph[job]); + } + + // Function to get a job node from the graph by its ID + JobNode* getNode(int job) { + // If the node does not exist in the graph, create a new node and add it to the graph + if (graph.find(job) == graph.end()) { + addNode(job); + } + return graph[job]; + } + + // Data members + vector nodes; // List of all job nodes in the graph + unordered_map graph; // Map to store the job nodes by their IDs +}; + +// Function to perform topological sorting and return the ordered jobs +vector TopologicalSort(vector& jobs, vector& deps) { + // Create a job graph from the list of jobs and dependencies + JobGraph graph = createJobGraph(jobs, deps); + // Get the ordered jobs using depth-first traversal + return getOrderedJobs(graph); +} + +// Function to create a job graph from a list of jobs and dependencies +JobGraph createJobGraph(vector& jobs, vector& deps) { + // Initialize an empty graph + JobGraph graph(jobs); + // Add each dependency as a prerequisite to the corresponding job node in the graph + for (Dep dep : deps) { + graph.addPrereq(dep.Job, dep.Prereq); + } + return graph; +} + +// Function to perform depth-first traversal and get the ordered jobs +vector getOrderedJobs(JobGraph& graph) { + vector orderedJobs; + vector& nodes = graph.nodes; + + // Continue the traversal until all nodes have been visited + while (!nodes.empty()) { + // Get the last node from the list of nodes and remove it from the list + JobNode* node = nodes.back(); + nodes.pop_back(); + + // Perform depth-first traversal starting from the current node + if (!depthFirstTraverse(graph, node->job, orderedJobs)) { + return {}; // If a cycle is detected during traversal, return an empty list + } + } + return orderedJobs; +} + +// Function to perform depth-first traversal starting from a specific job node +bool depthFirstTraverse(JobGraph& graph, int jobId, vector& orderedJobs) { + // Get the job node from the graph + JobNode* node = graph.getNode(jobId); + + // If the node has been visited, it means it is not part of any cycle, so return false + if (node->visited) { + return false; + } + + // If the node is currently being visited, it means there is a cycle, so return true + if (node->visiting) { + return true; + } + + // Mark the node as currently being visited + node->visiting = true; + + // Recursively traverse through each prerequisite of the current node + for (JobNode* prereqNode : node->prereqs) { + // If a cycle is detected during the traversal, return true + if (depthFirstTraverse(graph, prereqNode->job, orderedJobs)) { + return true; + } + } + + // Mark the node as visited and no longer being visited + node->visited = true; + node->visiting = false; + + // Append the job to the orderedJobs list in the correct order + orderedJobs.push_back(node->job); + + // Return false, as no cycle was detected during the traversal + return false; +} + +// Definition of the JobNode class +class JobNode { +public: + int job; // Job ID + vector prereqs; // List of prerequisite job nodes + bool visited; // Flag to mark if the node has been visited + bool visiting; // Flag to mark if the node is currently being visited + + // Constructor to initialize a job node + JobNode(int jobId) : job(jobId), visited(false), visiting(false) {} +}; From 5e6e21bd05c22cf9117a2019a429952d1f929d73 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Jul 2023 23:21:10 +0530 Subject: [PATCH 1670/1894] add java version of topo sort --- Graphs/topological_sort.java | 204 +++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 Graphs/topological_sort.java diff --git a/Graphs/topological_sort.java b/Graphs/topological_sort.java new file mode 100644 index 00000000..350e54e3 --- /dev/null +++ b/Graphs/topological_sort.java @@ -0,0 +1,204 @@ +/* + You're given a list of arbitrary jobs that need to be completed; these jobs + are represented by distinct integers. You're also given a list of dependencies. A + dependency is represented as a pair of jobs where the first job is a + prerequisite of the second one. In other words, the second job depends on the + first one; it can only be completed once the first job is completed. + + Write a function that takes in a list of jobs and a list of dependencies and + returns a list containing a valid order in which the given jobs can be + completed. If no such order exists, the function should return an empty array. + + Sample INput: + jobs: [1, 2, 3, 4] + deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] + Output: [1, 4, 3, 2] or [4, 1, 3, 2] + + Explanation: + The provided code implements a topological sorting algorithm to find the order in which jobs can be executed given their dependencies. It uses a directed acyclic graph (DAG) representation to represent the jobs and their dependencies. + + Let's go through each part of the code in detail: + + 1. `Dep` struct: + - This is a simple struct that represents a dependency between two jobs. + - `Prereq` field indicates the prerequisite job. + - `Job` field indicates the job that depends on the prerequisite. + + 2. `TopologicalSort` function: + - This is the main function that performs the topological sorting of jobs. + - It takes two input parameters: `jobs`, a list of job IDs, and `deps`, a list of dependencies. + - It first creates a job graph using the `createJobGraph` function and then gets the ordered jobs using the `getOrderedJobs` function. + + 3. `createJobGraph` function: + - This function creates a job graph from the list of jobs and dependencies. + - It creates a new instance of the `JobGraph` struct and iterates through the dependencies. + - For each dependency, it adds the prerequisite job to the dependent job's list of prerequisites in the job graph. + + 4. `getOrderedJobs` function: + - This function performs a depth-first traversal of the job graph to get the ordered jobs. + - It iterates through the nodes of the graph until all nodes have been visited. + - For each node, it calls the `depthFirstTraverse` function to perform the depth-first traversal and get the ordered jobs. + - If a cycle is detected in the graph during the traversal, it means that there is a circular dependency, and the function returns an empty list. + + 5. `depthFirstTraverse` function: + - This function performs the depth-first traversal of the graph starting from a given node. + - It checks if the current node has been visited (i.e., it is not part of any cycle). + - If the node is currently being visited (marked as `Visiting`), it means that there is a cycle, and the function returns `true`. + - Otherwise, it marks the node as `Visiting`, recursively traverses through its prerequisites, and marks it as `Visited` after the traversal. + - It appends the job to the `orderedJobs` list in the correct order. + + 6. `JobGraph` struct: + - This struct represents the job graph. + - `Nodes` is a list of all the job nodes in the graph. + - `Graph` is a map where the key is the job ID, and the value is a pointer to the corresponding `JobNode` in the graph. + + 7. `NewJobGraph` function: + - This function creates a new instance of the `JobGraph` struct and initializes its `Graph` field with an empty map. + - It also adds individual job nodes to the `Nodes` list. + + 8. `Addprereq`, `AddNode`, and `GetNode` functions: + - These are helper functions to add prerequisites to a job, add a new job node to the graph, and get an existing job node, respectively. + + 9. `JobNode` struct: + - This struct represents a node in the job graph. + - `Job` is the job ID. + - `Prereqs` is a list of pointers to other job nodes that are prerequisites for the current job. + - `Visited` and `Visiting` are boolean flags used during the depth-first traversal to track the traversal status of each node. + + Overall, the code implements the topological sorting algorithm using depth-first traversal to find the order in which jobs can be executed without violating their dependencies. It efficiently handles circular dependencies and returns the ordered jobs or an empty list if a circular dependency is detected. + + O(j + d) time | O(j + d) space - where j is the number of jobs and d is the number of dependencies +*/ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Dep { + int Prereq; + int Job; + + public Dep(int Prereq, int Job) { + this.Prereq = Prereq; + this.Job = Job; + } +} + +class JobGraph { + + // Inner class representing a job node + static class JobNode { + int job; // Job ID + List prereqs; // List of prerequisite job nodes + boolean visited; // Flag to mark if the node has been visited + boolean visiting; // Flag to mark if the node is currently being visited + + // Constructor to initialize a job node + public JobNode(int job) { + this.job = job; + this.prereqs = new ArrayList<>(); + this.visited = false; + this.visiting = false; + } + } + + List nodes; // List of all job nodes in the graph + Map graph; // Map to store the job nodes by their IDs + + // Constructor to create a job graph from a list of jobs + public JobGraph(List jobs) { + this.nodes = new ArrayList<>(); + this.graph = new HashMap<>(); + for (int job : jobs) { + // Add each job as a node to the graph + addNode(job); + } + } + + // Function to add a prerequisite to a job node + public void addPrereq(int job, int prereq) { + JobNode jobNode = getNode(job); + JobNode prereqNode = getNode(prereq); + // Add the prerequisite node to the list of prerequisites for the job node + jobNode.prereqs.add(prereqNode); + } + + // Function to add a new job node to the graph + public void addNode(int job) { + // Create a new job node and add it to the graph and nodes list + JobNode node = new JobNode(job); + graph.put(job, node); + nodes.add(node); + } + + // Function to get a job node from the graph by its ID + public JobNode getNode(int job) { + // If the node does not exist in the graph, create a new node and add it to the graph + if (!graph.containsKey(job)) { + addNode(job); + } + return graph.get(job); + } +} + +public class Main { + + // Function to perform topological sorting and return the ordered jobs + public static List TopologicalSort(List jobs, List deps) { + // Create a job graph from the list of jobs and dependencies + JobGraph graph = createJobGraph(jobs, deps); + // Get the ordered jobs using depth-first traversal + return getOrderedJobs(graph); + } + + // Function to create a job graph from a list of jobs and dependencies + public static JobGraph createJobGraph(List jobs, List deps) { + // Initialize an empty graph + JobGraph graph = new JobGraph(jobs); + // Add each dependency as a prerequisite to the corresponding job node in the graph + for (Dep dep : deps) { + graph.addPrereq(dep.Job, dep.Prereq); + } + return graph; + } + + // Function to perform depth-first traversal and get the ordered jobs + public static List getOrderedJobs(JobGraph graph) { + List orderedJobs = new ArrayList<>(); + List nodes = graph.nodes; + + // Continue the traversal until all nodes have been visited + while (!nodes.isEmpty()) { + // Get the last node from the list of nodes and remove it from the list + JobGraph.JobNode node = nodes.remove(nodes.size() - 1); + + // Perform depth-first traversal starting from the current node + if (!depthFirstTraverse(graph, node.job, orderedJobs)) { + return new ArrayList<>(); // If a cycle is detected during traversal, return an empty list + } + } + return orderedJobs; + } + + // Function to perform depth-first traversal starting from a specific job node + public static boolean depthFirstTraverse(JobGraph graph, int jobId, List orderedJobs) { + // Get the job node from the graph + JobGraph.JobNode node = graph.getNode(jobId); + + // If the node has been visited, it means it is not part of any cycle, so return false + if (node.visited) { + return false; + } + + // If the node is currently being visited, it means there is a cycle, so return true + if (node.visiting) { + return true; + } + + // Mark the node as currently being visited + node.visiting = true; + + // Recursively traverse through each prerequisite of the current node + for (JobGraph.JobNode prereqNode : node.prereqs) { + // If a cycle is detected during the traversal, return true + if (depth From 396f59cd88c417bfd905cbd335f69a7c7bf8e514 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 20 Jul 2023 23:32:09 +0530 Subject: [PATCH 1671/1894] add topo sort in js --- Graphs/topological_sort,js | 180 +++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 Graphs/topological_sort,js diff --git a/Graphs/topological_sort,js b/Graphs/topological_sort,js new file mode 100644 index 00000000..28398eb8 --- /dev/null +++ b/Graphs/topological_sort,js @@ -0,0 +1,180 @@ +/* + You're given a list of arbitrary jobs that need to be completed; these jobs + are represented by distinct integers. You're also given a list of dependencies. A + dependency is represented as a pair of jobs where the first job is a + prerequisite of the second one. In other words, the second job depends on the + first one; it can only be completed once the first job is completed. + + Write a function that takes in a list of jobs and a list of dependencies and + returns a list containing a valid order in which the given jobs can be + completed. If no such order exists, the function should return an empty array. + + Sample INput: + jobs: [1, 2, 3, 4] + deps: = [[1, 2], [1, 3], [3, 2], [4, 2], [4, 3]] + Output: [1, 4, 3, 2] or [4, 1, 3, 2] + + Explanation: + The provided code implements a topological sorting algorithm to find the order in which jobs can be executed given their dependencies. It uses a directed acyclic graph (DAG) representation to represent the jobs and their dependencies. + + Let's go through each part of the code in detail: + + 1. `Dep` struct: + - This is a simple struct that represents a dependency between two jobs. + - `Prereq` field indicates the prerequisite job. + - `Job` field indicates the job that depends on the prerequisite. + + 2. `TopologicalSort` function: + - This is the main function that performs the topological sorting of jobs. + - It takes two input parameters: `jobs`, a list of job IDs, and `deps`, a list of dependencies. + - It first creates a job graph using the `createJobGraph` function and then gets the ordered jobs using the `getOrderedJobs` function. + + 3. `createJobGraph` function: + - This function creates a job graph from the list of jobs and dependencies. + - It creates a new instance of the `JobGraph` struct and iterates through the dependencies. + - For each dependency, it adds the prerequisite job to the dependent job's list of prerequisites in the job graph. + + 4. `getOrderedJobs` function: + - This function performs a depth-first traversal of the job graph to get the ordered jobs. + - It iterates through the nodes of the graph until all nodes have been visited. + - For each node, it calls the `depthFirstTraverse` function to perform the depth-first traversal and get the ordered jobs. + - If a cycle is detected in the graph during the traversal, it means that there is a circular dependency, and the function returns an empty list. + + 5. `depthFirstTraverse` function: + - This function performs the depth-first traversal of the graph starting from a given node. + - It checks if the current node has been visited (i.e., it is not part of any cycle). + - If the node is currently being visited (marked as `Visiting`), it means that there is a cycle, and the function returns `true`. + - Otherwise, it marks the node as `Visiting`, recursively traverses through its prerequisites, and marks it as `Visited` after the traversal. + - It appends the job to the `orderedJobs` list in the correct order. + + 6. `JobGraph` struct: + - This struct represents the job graph. + - `Nodes` is a list of all the job nodes in the graph. + - `Graph` is a map where the key is the job ID, and the value is a pointer to the corresponding `JobNode` in the graph. + + 7. `NewJobGraph` function: + - This function creates a new instance of the `JobGraph` struct and initializes its `Graph` field with an empty map. + - It also adds individual job nodes to the `Nodes` list. + + 8. `Addprereq`, `AddNode`, and `GetNode` functions: + - These are helper functions to add prerequisites to a job, add a new job node to the graph, and get an existing job node, respectively. + + 9. `JobNode` struct: + - This struct represents a node in the job graph. + - `Job` is the job ID. + - `Prereqs` is a list of pointers to other job nodes that are prerequisites for the current job. + - `Visited` and `Visiting` are boolean flags used during the depth-first traversal to track the traversal status of each node. + + Overall, the code implements the topological sorting algorithm using depth-first traversal to find the order in which jobs can be executed without violating their dependencies. It efficiently handles circular dependencies and returns the ordered jobs or an empty list if a circular dependency is detected. + + O(j + d) time | O(j + d) space - where j is the number of jobs and d is the number of dependencies +*/ +class Dep { + constructor(Prereq, Job) { + this.Prereq = Prereq; + this.Job = Job; + } +} + +class JobGraph { + constructor(jobs) { + this.nodes = []; + this.graph = new Map(); + for (const job of jobs) { + // Add each job as a node to the graph + this.addNode(job); + } + } + + addPrereq(job, prereq) { + const jobNode = this.getNode(job); + const prereqNode = this.getNode(prereq); + // Add the prerequisite node to the list of prerequisites for the job node + jobNode.prereqs.push(prereqNode); + } + + addNode(job) { + // Create a new job node and add it to the graph and nodes list + const node = { job, prereqs: [], visited: false, visiting: false }; + this.graph.set(job, node); + this.nodes.push(node); + } + + getNode(job) { + // If the node does not exist in the graph, create a new node and add it to the graph + if (!this.graph.has(job)) { + this.addNode(job); + } + return this.graph.get(job); + } +} + +function TopologicalSort(jobs, deps) { + // Create a job graph from the list of jobs and dependencies + const graph = createJobGraph(jobs, deps); + // Get the ordered jobs using depth-first traversal + return getOrderedJobs(graph); +} + +function createJobGraph(jobs, deps) { + // Initialize an empty graph + const graph = new JobGraph(jobs); + // Add each dependency as a prerequisite to the corresponding job node in the graph + for (const dep of deps) { + graph.addPrereq(dep.Job, dep.Prereq); + } + return graph; +} + +function getOrderedJobs(graph) { + const orderedJobs = []; + const nodes = graph.nodes; + + // Continue the traversal until all nodes have been visited + while (nodes.length > 0) { + // Get the last node from the list of nodes and remove it from the list + const node = nodes.pop(); + + // Perform depth-first traversal starting from the current node + if (!depthFirstTraverse(graph, node.job, orderedJobs)) { + return []; // If a cycle is detected during traversal, return an empty list + } + } + return orderedJobs; +} + +function depthFirstTraverse(graph, jobId, orderedJobs) { + // Get the job node from the graph + const node = graph.getNode(jobId); + + // If the node has been visited, it means it is not part of any cycle, so return false + if (node.visited) { + return false; + } + + // If the node is currently being visited, it means there is a cycle, so return true + if (node.visiting) { + return true; + } + + // Mark the node as currently being visited + node.visiting = true; + + // Recursively traverse through each prerequisite of the current node + for (const prereqNode of node.prereqs) { + // If a cycle is detected during the traversal, return true + if (depthFirstTraverse(graph, prereqNode.job, orderedJobs)) { + return true; + } + } + + // Mark the node as visited and not currently being visited + node.visited = true; + node.visiting = false; + + // Add the job to the ordered jobs list + orderedJobs.push(jobId); + + // Return false to indicate that no cycle was detected + return false; +} From 01972d984e85769a7fa29dd4166d1323898442a6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Jul 2023 23:02:15 +0530 Subject: [PATCH 1672/1894] rename --- Graphs/{Snakes_and_Ladders.java => snakes_ladders.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Snakes_and_Ladders.java => snakes_ladders.java} (100%) diff --git a/Graphs/Snakes_and_Ladders.java b/Graphs/snakes_ladders.java similarity index 100% rename from Graphs/Snakes_and_Ladders.java rename to Graphs/snakes_ladders.java From a23eb372cb9e03650ce0c4795b0eeb726bc3d1db Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Jul 2023 23:06:56 +0530 Subject: [PATCH 1673/1894] add two colorable --- Graphs/two_colorable.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Graphs/two_colorable.go diff --git a/Graphs/two_colorable.go b/Graphs/two_colorable.go new file mode 100644 index 00000000..0d181d37 --- /dev/null +++ b/Graphs/two_colorable.go @@ -0,0 +1,22 @@ +package main + +func TwoColorable(edges [][]int) bool { + colors := map[int]bool{ + 0: true, + } + stack := []int{0} + + for len(stack) > 0 { + var node int + node, stack = stack[len(stack)-1], stack[:len(stack)-1] + for _, connection := range edges[node] { + if _, colorFound := colors[connection]; !colorFound { + colors[connection] = !colors[node] + stack = append(stack, connection) + } else if colors[connection] == colors[node] { + return false + } + } + } + return true +} From b4f750d400341aaac18dd4588dcb6cc723add403 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Jul 2023 23:10:17 +0530 Subject: [PATCH 1674/1894] add explanation and comments --- Graphs/two_colorable.go | 59 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/Graphs/two_colorable.go b/Graphs/two_colorable.go index 0d181d37..9fb48352 100644 --- a/Graphs/two_colorable.go +++ b/Graphs/two_colorable.go @@ -1,22 +1,73 @@ +/* + You're given a list of edges representing a connected, unweighted, undirected graph with at least one node. + Write a function that returns a boolean representing whether the given graph is two-colorable. + + Explanation: + The code snippet implements an algorithm to determine if a given graph is two-colorable or bipartite. A graph is two-colorable if its vertices can be divided into two groups such that no two adjacent vertices have the same color. + + The function `TwoColorable(edges [][]int) bool` takes a 2D array of integers `edges`, representing the edges of the graph. Each row `edges[i]` contains the list of vertices that are connected to vertex `i`. + + The algorithm uses a stack and a map to keep track of the colors assigned to the vertices. It starts by assigning the first vertex (vertex 0) to color true and pushing it onto the stack. + + Then, it performs a depth-first traversal of the graph using the stack. For each vertex popped from the stack, it explores its adjacent vertices. If an adjacent vertex has not been colored yet (not present in the colors map), it assigns the opposite color to it (i.e., `!colors[node]`) and pushes it onto the stack. If the adjacent vertex has already been colored and its color is the same as the current vertex's color, then the graph cannot be two-colorable, and the function returns false. + + If the traversal completes without any conflicts (i.e., no adjacent vertices have the same color), the function returns true, indicating that the graph is two-colorable. + + The algorithm relies on the fact that a graph is two-colorable if and only if it is bipartite, and the two colors represent the two disjoint sets of vertices in the bipartite graph. + + Here's a step-by-step explanation of the algorithm: + + 1. Initialize the `colors` map with the first vertex (0) assigned the color true (representing one group of vertices). + 2. Initialize an empty stack and push the first vertex (0) onto it. + 3. While the stack is not empty, repeat the following steps: + a. Pop the top vertex from the stack (denoted by `node`). + b. For each vertex `connection` connected to `node` (i.e., `edges[node]`), do the following: + i. If `connection` has not been colored yet (not present in the `colors` map), assign it the opposite color of + `node` (i.e., `!colors[node]`) and push it onto the stack. + ii. If `connection` has already been colored and its color is the same as `node`'s color, return false since the + graph is not two-colorable. + 4. If the traversal completes without conflicts, return true, indicating that the graph is two-colorable. + + Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. + If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + +*/ package main func TwoColorable(edges [][]int) bool { + // colors keeps track of the colors assigned to each vertex. + // We start by assigning the first vertex (0) the color true (denoted by 0: true). colors := map[int]bool{ 0: true, } + + // stack is used for depth-first traversal of the graph. stack := []int{0} for len(stack) > 0 { - var node int - node, stack = stack[len(stack)-1], stack[:len(stack)-1] + // Pop the top vertex from the stack (denoted by 'node'). + node := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + // Explore adjacent vertices (connections) of the current vertex 'node'. for _, connection := range edges[node] { + // If the adjacent vertex has not been colored yet (not present in the 'colors' map), + // assign it the opposite color of the current vertex (denoted by '!colors[node]'), + // and push it onto the stack. if _, colorFound := colors[connection]; !colorFound { colors[connection] = !colors[node] stack = append(stack, connection) - } else if colors[connection] == colors[node] { - return false + } else { + // If the adjacent vertex has already been colored and its color is the same as the current vertex's color, + // then the graph cannot be two-colorable, return false. + if colors[connection] == colors[node] { + return false + } } } } + + // If the traversal completes without any conflicts (no adjacent vertices have the same color), + // return true, indicating that the graph is two-colorable. return true } From 296d6e364f6b35e65eb28670f4dd546ca4c05400 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 21 Jul 2023 23:10:51 +0530 Subject: [PATCH 1675/1894] add time and space complexity --- Graphs/two_colorable.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Graphs/two_colorable.go b/Graphs/two_colorable.go index 9fb48352..9bac7e04 100644 --- a/Graphs/two_colorable.go +++ b/Graphs/two_colorable.go @@ -31,6 +31,8 @@ Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + O(v + e) time | O(v) space - where v is the number of vertices and e is the number of edges in the graph + */ package main From dc543bd478f2e8141750b95579da9a26d11e919c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Jul 2023 22:57:16 +0530 Subject: [PATCH 1676/1894] add zig zag traversal in go --- 2D Arrays (Matrix)/zigzag_traversal.go | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 2D Arrays (Matrix)/zigzag_traversal.go diff --git a/2D Arrays (Matrix)/zigzag_traversal.go b/2D Arrays (Matrix)/zigzag_traversal.go new file mode 100644 index 00000000..3a72efce --- /dev/null +++ b/2D Arrays (Matrix)/zigzag_traversal.go @@ -0,0 +1,42 @@ +package main + +func ZigzagTraverse(array [][]int) []int { + height := len(array) - 1 + width := len(array[0]) - 1 + row, col := 0, 0 + goingDown := true + result := []int{} + for !isOutOfBounds(row, col, height, width) { + result = append(result, array[row][col]) + if goingDown { + if col == 0 || row == height { + goingDown = false + if row == height { + col++ + } else { + row++ + } + } else { + row++ + col-- + } + } else { + if row == 0 || col == width { + goingDown = true + if col == width { + row++ + } else { + col++ + } + } else { + row-- + col++ + } + } + } + return result +} + +func isOutOfBounds(row, col, height, width int) bool { + return row < 0 || col < 0 || row > height || col > width +} \ No newline at end of file From c691b9c5c19fd74cb797b6226b3f8ad869adafef Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Jul 2023 22:57:32 +0530 Subject: [PATCH 1677/1894] add comments --- 2D Arrays (Matrix)/zigzag_traversal.go | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/2D Arrays (Matrix)/zigzag_traversal.go b/2D Arrays (Matrix)/zigzag_traversal.go index 3a72efce..34a0ee57 100644 --- a/2D Arrays (Matrix)/zigzag_traversal.go +++ b/2D Arrays (Matrix)/zigzag_traversal.go @@ -1,42 +1,66 @@ package main +// ZigzagTraverse traverses a 2D array in a zigzag pattern and returns the elements in a 1D array. func ZigzagTraverse(array [][]int) []int { + // Get the height and width of the 2D array. height := len(array) - 1 width := len(array[0]) - 1 + + // Initialize variables to keep track of the current position while traversing. row, col := 0, 0 + + // Initialize a boolean variable to determine the direction of traversal. goingDown := true + + // Initialize an array to store the elements traversed in zigzag order. result := []int{} + + // The main loop runs until the current position is within bounds (not out of the 2D array). for !isOutOfBounds(row, col, height, width) { + // Append the current element at position (row, col) to the result array. result = append(result, array[row][col]) + + // Traversal logic: Decide the next position for traversal based on the current position and the goingDown flag. if goingDown { if col == 0 || row == height { + // Change direction to upward if at the top-left or bottom-right corner. goingDown = false + + // Decide the next position based on whether we are at the bottom or right boundary. if row == height { col++ } else { row++ } } else { + // Continue diagonally downward. row++ col-- } } else { if row == 0 || col == width { + // Change direction to downward if at the top-right or bottom-left corner. goingDown = true + + // Decide the next position based on whether we are at the top or right boundary. if col == width { row++ } else { col++ } } else { + // Continue diagonally upward. row-- col++ } } } + + // Return the final result, which contains the elements of the 2D array in zigzag order. return result } +// isOutOfBounds checks if the current position (row, col) is out of bounds of the 2D array. func isOutOfBounds(row, col, height, width int) bool { return row < 0 || col < 0 || row > height || col > width -} \ No newline at end of file +} From 0a89c71b835b7ff00d3d85336d7c8d274c0c6dfd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Jul 2023 22:58:51 +0530 Subject: [PATCH 1678/1894] add explanation --- 2D Arrays (Matrix)/zigzag_traversal.go | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/2D Arrays (Matrix)/zigzag_traversal.go b/2D Arrays (Matrix)/zigzag_traversal.go index 34a0ee57..7ddd493f 100644 --- a/2D Arrays (Matrix)/zigzag_traversal.go +++ b/2D Arrays (Matrix)/zigzag_traversal.go @@ -1,3 +1,39 @@ +/* + Explanation: + The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and + returns the elements in a 1D array. + + Here's an explanation of the code: + + 1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing + the elements traversed in zigzag order. + + 2. `height` and `width`: These variables store the height and width of the 2D array, respectively. + The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing). + + 3. `row` and `col`: These variables keep track of the current position while traversing the 2D array. + + 4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal + is in the downward direction; otherwise, it is in the upward direction. + + 5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result. + + 6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array). + + 7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array. + + 8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag. + If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position). + + 9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the + 2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively). + + 10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of + the 2D array in zigzag order. + + The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches + the boundary or the corners of the array, allowing it to cover all elements in zigzag order. +*/ package main // ZigzagTraverse traverses a 2D array in a zigzag pattern and returns the elements in a 1D array. From f79e5733f5a4831bf16fc68a9d5a15f5d43a6b39 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Jul 2023 23:00:16 +0530 Subject: [PATCH 1679/1894] add sample io and question --- 2D Arrays (Matrix)/zigzag_traversal.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/2D Arrays (Matrix)/zigzag_traversal.go b/2D Arrays (Matrix)/zigzag_traversal.go index 7ddd493f..dffe96e3 100644 --- a/2D Arrays (Matrix)/zigzag_traversal.go +++ b/2D Arrays (Matrix)/zigzag_traversal.go @@ -1,4 +1,16 @@ /* + + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) + and returns a one-dimensional array of all the array's elements in zigzag order. + + Sample Input:= [ + [1, 3, 4, 10], + [2, 5, 9, 11], + [6, 8, 12, 15], + [7, 13, 14, 16], + ] + Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + Explanation: The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and returns the elements in a 1D array. From 1145a1716a48a3a266cde3d1e8e438d750f7e8a9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 22 Jul 2023 23:00:46 +0530 Subject: [PATCH 1680/1894] add time and space complexity --- 2D Arrays (Matrix)/zigzag_traversal.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/2D Arrays (Matrix)/zigzag_traversal.go b/2D Arrays (Matrix)/zigzag_traversal.go index dffe96e3..66106082 100644 --- a/2D Arrays (Matrix)/zigzag_traversal.go +++ b/2D Arrays (Matrix)/zigzag_traversal.go @@ -45,6 +45,8 @@ The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches the boundary or the corners of the array, allowing it to cover all elements in zigzag order. + + O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array */ package main From b2e9922ecbf9a194302b7759f6c498cea5f5aaee Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Jul 2023 19:25:52 +0530 Subject: [PATCH 1681/1894] add zig zag traversal in python --- 2D Arrays (Matrix)/zigzag_traversal.py | 108 +++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 2D Arrays (Matrix)/zigzag_traversal.py diff --git a/2D Arrays (Matrix)/zigzag_traversal.py b/2D Arrays (Matrix)/zigzag_traversal.py new file mode 100644 index 00000000..3a23c6f3 --- /dev/null +++ b/2D Arrays (Matrix)/zigzag_traversal.py @@ -0,0 +1,108 @@ +''' + + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) + and returns a one-dimensional array of all the array's elements in zigzag order. + + Sample Input:= [ + [1, 3, 4, 10], + [2, 5, 9, 11], + [6, 8, 12, 15], + [7, 13, 14, 16], + ] + Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + + Explanation: + The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and + returns the elements in a 1D array. + + Here's an explanation of the code: + + 1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing + the elements traversed in zigzag order. + + 2. `height` and `width`: These variables store the height and width of the 2D array, respectively. + The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing). + + 3. `row` and `col`: These variables keep track of the current position while traversing the 2D array. + + 4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal + is in the downward direction; otherwise, it is in the upward direction. + + 5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result. + + 6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array). + + 7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array. + + 8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag. + If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position). + + 9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the + 2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively). + + 10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of + the 2D array in zigzag order. + + The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches + the boundary or the corners of the array, allowing it to cover all elements in zigzag order. + + O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array +''' + +def ZigzagTraverse(array): + # Get the height (number of rows) and width (number of columns) of the array. + height = len(array) + width = len(array[0]) + + # Initialize the row and column pointers to start from the top-left element (0,0). + row, col = 0, 0 + + # Initialize a flag to track the direction of traversal (goingDown). + # True means moving down, False means moving up. + goingDown = True + + # Initialize a list to store the elements in zigzag order. + result = [] + + # Loop until the current position is within the bounds of the array. + while not isOutOfBounds(row, col, height, width): + # Append the current element to the result list. + result.append(array[row][col]) + + # If moving down, check if we reached the bottom row or leftmost column. + if goingDown: + if col == 0 or row == height - 1: + # Change direction if we reached the bottom row or leftmost column. + goingDown = False + if row == height - 1: + # Move right if we reached the bottom row. + col += 1 + else: + # Move down if we reached the leftmost column. + row += 1 + else: + # Move diagonally down-left. + row += 1 + col -= 1 + else: + # If moving up, check if we reached the top row or rightmost column. + if row == 0 or col == width - 1: + # Change direction if we reached the top row or rightmost column. + goingDown = True + if col == width - 1: + # Move down if we reached the rightmost column. + row += 1 + else: + # Move right if we reached the top row. + col += 1 + else: + # Move diagonally up-right. + row -= 1 + col += 1 + + # Return the list containing the elements in zigzag order. + return result + +def isOutOfBounds(row, col, height, width): + # Check if the current position is outside the bounds of the array. + return row < 0 or col < 0 or row >= height or col >= width From 2a240fe9e3da2b569164757da643e0667dd21ff5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Jul 2023 19:26:48 +0530 Subject: [PATCH 1682/1894] add zigzag traversal in c++ --- 2D Arrays (Matrix)/zigzag_traversal.cpp | 121 ++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 2D Arrays (Matrix)/zigzag_traversal.cpp diff --git a/2D Arrays (Matrix)/zigzag_traversal.cpp b/2D Arrays (Matrix)/zigzag_traversal.cpp new file mode 100644 index 00000000..bf7e944d --- /dev/null +++ b/2D Arrays (Matrix)/zigzag_traversal.cpp @@ -0,0 +1,121 @@ +/* + + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) + and returns a one-dimensional array of all the array's elements in zigzag order. + + Sample Input:= [ + [1, 3, 4, 10], + [2, 5, 9, 11], + [6, 8, 12, 15], + [7, 13, 14, 16], + ] + Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + + Explanation: + The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and + returns the elements in a 1D array. + + Here's an explanation of the code: + + 1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing + the elements traversed in zigzag order. + + 2. `height` and `width`: These variables store the height and width of the 2D array, respectively. + The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing). + + 3. `row` and `col`: These variables keep track of the current position while traversing the 2D array. + + 4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal + is in the downward direction; otherwise, it is in the upward direction. + + 5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result. + + 6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array). + + 7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array. + + 8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag. + If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position). + + 9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the + 2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively). + + 10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of + the 2D array in zigzag order. + + The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches + the boundary or the corners of the array, allowing it to cover all elements in zigzag order. + + O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array +*/ + +#include + +using namespace std; + +vector ZigzagTraverse(vector>& array) { + // Get the height (number of rows) and width (number of columns) of the array. + int height = array.size(); + int width = array[0].size(); + + // Initialize the row and column pointers to start from the top-left element (0,0). + int row = 0; + int col = 0; + + // Initialize a flag to track the direction of traversal (goingDown). + // true means moving down, false means moving up. + bool goingDown = true; + + // Initialize a vector to store the elements in zigzag order. + vector result; + + // Loop until the current position is within the bounds of the array. + while (!isOutOfBounds(row, col, height, width)) { + // Append the current element to the result vector. + result.push_back(array[row][col]); + + // If moving down, check if we reached the bottom row or leftmost column. + if (goingDown) { + if (col == 0 || row == height - 1) { + // Change direction if we reached the bottom row or leftmost column. + goingDown = false; + if (row == height - 1) { + // Move right if we reached the bottom row. + col++; + } else { + // Move down if we reached the leftmost column. + row++; + } + } else { + // Move diagonally down-left. + row++; + col--; + } + } else { + // If moving up, check if we reached the top row or rightmost column. + if (row == 0 || col == width - 1) { + // Change direction if we reached the top row or rightmost column. + goingDown = true; + if (col == width - 1) { + // Move down if we reached the rightmost column. + row++; + } else { + // Move right if we reached the top row. + col++; + } + } else { + // Move diagonally up-right. + row--; + col++; + } + } + } + + // Return the vector containing the elements in zigzag order. + return result; +} + +bool isOutOfBounds(int row, int col, int height, int width) { + // Check if the current position is outside the bounds of the array. + return row < 0 || col < 0 || row >= height || col >= width; +} From 0d0975eb575b1967b57f2bf804e87fd667faf8da Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Jul 2023 19:27:35 +0530 Subject: [PATCH 1683/1894] add zigzag traversal in js --- 2D Arrays (Matrix)/zigzag_traversal.js | 116 +++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 2D Arrays (Matrix)/zigzag_traversal.js diff --git a/2D Arrays (Matrix)/zigzag_traversal.js b/2D Arrays (Matrix)/zigzag_traversal.js new file mode 100644 index 00000000..e645a36c --- /dev/null +++ b/2D Arrays (Matrix)/zigzag_traversal.js @@ -0,0 +1,116 @@ +/* + + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) + and returns a one-dimensional array of all the array's elements in zigzag order. + + Sample Input:= [ + [1, 3, 4, 10], + [2, 5, 9, 11], + [6, 8, 12, 15], + [7, 13, 14, 16], + ] + Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + + Explanation: + The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and + returns the elements in a 1D array. + + Here's an explanation of the code: + + 1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing + the elements traversed in zigzag order. + + 2. `height` and `width`: These variables store the height and width of the 2D array, respectively. + The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing). + + 3. `row` and `col`: These variables keep track of the current position while traversing the 2D array. + + 4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal + is in the downward direction; otherwise, it is in the upward direction. + + 5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result. + + 6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array). + + 7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array. + + 8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag. + If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position). + + 9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the + 2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively). + + 10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of + the 2D array in zigzag order. + + The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches + the boundary or the corners of the array, allowing it to cover all elements in zigzag order. + + O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array +*/ +function ZigzagTraverse(array) { + // Get the height (number of rows) and width (number of columns) of the array. + const height = array.length; + const width = array[0].length; + + // Initialize the row and column pointers to start from the top-left element (0,0). + let row = 0; + let col = 0; + + // Initialize a flag to track the direction of traversal (goingDown). + // true means moving down, false means moving up. + let goingDown = true; + + // Initialize an array to store the elements in zigzag order. + const result = []; + + // Loop until the current position is within the bounds of the array. + while (!isOutOfBounds(row, col, height, width)) { + // Append the current element to the result array. + result.push(array[row][col]); + + // If moving down, check if we reached the bottom row or leftmost column. + if (goingDown) { + if (col === 0 || row === height - 1) { + // Change direction if we reached the bottom row or leftmost column. + goingDown = false; + if (row === height - 1) { + // Move right if we reached the bottom row. + col++; + } else { + // Move down if we reached the leftmost column. + row++; + } + } else { + // Move diagonally down-left. + row++; + col--; + } + } else { + // If moving up, check if we reached the top row or rightmost column. + if (row === 0 || col === width - 1) { + // Change direction if we reached the top row or rightmost column. + goingDown = true; + if (col === width - 1) { + // Move down if we reached the rightmost column. + row++; + } else { + // Move right if we reached the top row. + col++; + } + } else { + // Move diagonally up-right. + row--; + col++; + } + } + } + + // Return the array containing the elements in zigzag order. + return result; +} + +function isOutOfBounds(row, col, height, width) { + // Check if the current position is outside the bounds of the array. + return row < 0 || col < 0 || row >= height || col >= width; +} From 50179c28f4bc73c39cd604e9b9e896ea9639d909 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 23 Jul 2023 19:28:27 +0530 Subject: [PATCH 1684/1894] add zigzag traversal in java --- 2D Arrays (Matrix)/zigzag_traversal.java | 134 +++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 2D Arrays (Matrix)/zigzag_traversal.java diff --git a/2D Arrays (Matrix)/zigzag_traversal.java b/2D Arrays (Matrix)/zigzag_traversal.java new file mode 100644 index 00000000..70337d41 --- /dev/null +++ b/2D Arrays (Matrix)/zigzag_traversal.java @@ -0,0 +1,134 @@ +/* + + Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) + and returns a one-dimensional array of all the array's elements in zigzag order. + + Sample Input:= [ + [1, 3, 4, 10], + [2, 5, 9, 11], + [6, 8, 12, 15], + [7, 13, 14, 16], + ] + Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + + Explanation: + The given code snippet implements the ZigzagTraverse algorithm, which traverses a 2D array in a zigzag pattern and + returns the elements in a 1D array. + + Here's an explanation of the code: + + 1. `ZigzagTraverse`: This is the main function that takes a 2D array `array` as input and returns a 1D array containing + the elements traversed in zigzag order. + + 2. `height` and `width`: These variables store the height and width of the 2D array, respectively. + The `height` represents the number of rows (minus 1 as it is 0-based indexing), and the `width` represents the number of columns (minus 1 as it is 0-based indexing). + + 3. `row` and `col`: These variables keep track of the current position while traversing the 2D array. + + 4. `goingDown`: This boolean variable determines the direction of traversal. When `goingDown` is `true`, the traversal + is in the downward direction; otherwise, it is in the upward direction. + + 5. `result`: This array stores the elements of the 2D array in zigzag order, which will be returned as the final result. + + 6. The main loop: The loop runs until the current position is within bounds (not out of the 2D array). + + 7. Append element to result: The code appends the current element at position `(row, col)` to the `result` array. + + 8. Traversal logic: The algorithm decides the next position for traversal based on the current position and the `goingDown` flag. + If `goingDown` is `true`, it will traverse diagonally downwards (towards the bottom-right or the bottom-left corner, depending on the position). Otherwise, it will traverse diagonally upwards (towards the top-right or the top-left corner, depending on the position). + + 9. `isOutOfBounds`: This is a helper function that checks if the current position `(row, col)` is out of bounds of the + 2D array (i.e., if `row` or `col` is less than 0 or greater than the height or width, respectively). + + 10. Return result: After the traversal is complete, the function returns the `result` array, which contains the elements of + the 2D array in zigzag order. + + The ZigzagTraverse algorithm efficiently zigzags through the 2D array by changing the direction of traversal whenever it reaches + the boundary or the corners of the array, allowing it to cover all elements in zigzag order. + + O(n) time | O(n) space - where n is the total number of elements in the two-dimensional array +*/ +import java.util.ArrayList; +import java.util.List; + +public class Main { + + public static List ZigzagTraverse(int[][] array) { + // Get the height (number of rows) and width (number of columns) of the array. + int height = array.length; + int width = array[0].length; + + // Initialize the row and column pointers to start from the top-left element (0,0). + int row = 0; + int col = 0; + + // Initialize a flag to track the direction of traversal (goingDown). + // true means moving down, false means moving up. + boolean goingDown = true; + + // Initialize a list to store the elements in zigzag order. + List result = new ArrayList<>(); + + // Loop until the current position is within the bounds of the array. + while (!isOutOfBounds(row, col, height, width)) { + // Append the current element to the result list. + result.add(array[row][col]); + + // If moving down, check if we reached the bottom row or leftmost column. + if (goingDown) { + if (col == 0 || row == height - 1) { + // Change direction if we reached the bottom row or leftmost column. + goingDown = false; + if (row == height - 1) { + // Move right if we reached the bottom row. + col++; + } else { + // Move down if we reached the leftmost column. + row++; + } + } else { + // Move diagonally down-left. + row++; + col--; + } + } else { + // If moving up, check if we reached the top row or rightmost column. + if (row == 0 || col == width - 1) { + // Change direction if we reached the top row or rightmost column. + goingDown = true; + if (col == width - 1) { + // Move down if we reached the rightmost column. + row++; + } else { + // Move right if we reached the top row. + col++; + } + } else { + // Move diagonally up-right. + row--; + col++; + } + } + } + + // Return the list containing the elements in zigzag order. + return result; + } + + public static boolean isOutOfBounds(int row, int col, int height, int width) { + // Check if the current position is outside the bounds of the array. + return row < 0 || col < 0 || row >= height || col >= width; + } + + public static void main(String[] args) { + int[][] array = { + {1, 3, 4, 10}, + {2, 5, 9, 11}, + {6, 8, 12, 15}, + {7, 13, 14, 16} + }; + + List result = ZigzagTraverse(array); + System.out.println(result); + } +} From dd8ac50c34a987a9f7c1295c7a4853e333c3cb6d Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Mon, 24 Jul 2023 10:39:23 +0530 Subject: [PATCH 1685/1894] Create HollowPattern.py --- Patterns/HollowPattern.py | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Patterns/HollowPattern.py diff --git a/Patterns/HollowPattern.py b/Patterns/HollowPattern.py new file mode 100644 index 00000000..03a33b40 --- /dev/null +++ b/Patterns/HollowPattern.py @@ -0,0 +1,52 @@ +''' +Problem: Python program to generate a hollow pattern using asterisks ('*'). The program will take an integer 'n' as input, which represents the size of the pattern, and it will produce a hollow pattern of the given size. + +Approach: +1. We will iterate through rows and columns and print '*' at specific positions to form the hollow pattern. +2. For each row, we will check if it's the first row, last row, first column, or last column. If so, we will print a '*' character. Otherwise, we will print a space ' '. +3. This way, we will create the desired hollow pattern. + +Time Complexity: O(n^2) +- The program uses two nested loops to print the pattern, one for rows and one for columns. So, the time complexity is proportional to the square of 'n'. + +Space Complexity: O(1) +- The program uses a constant amount of extra space, as it only prints characters and does not use any additional data structures that depend on the input size 'n'. + +Sample Input: 8 +Sample Output: +``` +* * * * * * * * +* * +* * +* * +* * +* * +* * +* * * * * * * * +``` + +In this example, the input 'n' is 8, and the program generates a hollow pattern of size 8x8 using asterisks. +''' + +def print_hollow_pattern(n): + # Iterate through each row + for i in range(n): + # Iterate through each column in the row + for j in range(n): + # Check if it's the first row, last row, first column, or last column + if i == 0 or i == n - 1 or j == 0 or j == n - 1: + print('*', end=' ') + else: + print(' ', end=' ') + # Move to the next line after each row is printed + print() + +# Sample input: n = 5 +# Expected output: +# * * * * * +# * * +# * * +# * * +# * * * * * +print_hollow_pattern(5) + From cbb20f9cc0b560e8e39cd1400f31a03951203d28 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Mon, 24 Jul 2023 11:29:48 +0530 Subject: [PATCH 1686/1894] Create HollowPattern.java --- Patterns/HollowPattern.java | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Patterns/HollowPattern.java diff --git a/Patterns/HollowPattern.java b/Patterns/HollowPattern.java new file mode 100644 index 00000000..bcede112 --- /dev/null +++ b/Patterns/HollowPattern.java @@ -0,0 +1,53 @@ +/* +Program: To generate a hollow pattern using asterisks ('*'). The program will take an integer 'n' as input, which represents the size of the pattern, and it will produce a hollow pattern of the given size. + +Approach: +1. We will use nested loops to iterate through rows and columns and print '*' at specific positions to form the hollow pattern. +2. For each row, we will check if it's the first row, last row, first column, or last column. If so, we will print a '*' character. Otherwise, we will print a space ' '. +3. This way, we will create the desired hollow pattern. + +Time Complexity: O(n^2) +- The program uses two nested loops to print the pattern, one for rows and one for columns. So, the time complexity is proportional to the square of 'n'. + +Space Complexity: O(1) +- The program uses a constant amount of extra space, as it only prints characters and does not use any additional data structures that depend on the input size 'n'. + +Sample Input: 6 +Sample Output: +* * * * * * +* * +* * +* * +* * +* * * * * * + +*/ + +import java.util.Scanner; + +public class HollowPattern { + public static void printHollowPattern(int n) { + // Iterate through each row + for (int i = 0; i < n; i++) { + // Iterate through each column in the row + for (int j = 0; j < n; j++) { + // Check if it's the first row, last row, first column, or last column + if (i == 0 || i == n - 1 || j == 0 || j == n - 1) { + System.out.print("* "); + } else { + System.out.print(" "); + } + } + // Move to the next line after each row is printed + System.out.println(); + } + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.print("Enter the size of the pattern: "); + int size = scanner.nextInt(); + + printHollowPattern(size); + } +} From fa01dd3f1e00f844d7fed358bd9389282052842d Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Mon, 24 Jul 2023 11:31:41 +0530 Subject: [PATCH 1687/1894] Create HollowPattern.cpp --- Patterns/HollowPattern.cpp | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Patterns/HollowPattern.cpp diff --git a/Patterns/HollowPattern.cpp b/Patterns/HollowPattern.cpp new file mode 100644 index 00000000..a3ad90f3 --- /dev/null +++ b/Patterns/HollowPattern.cpp @@ -0,0 +1,53 @@ +Program: To generate a hollow pattern using asterisks ('*'). The program will take an integer 'n' as input, which represents the size of the pattern, and it will produce a hollow pattern of the given size. + +Approach: +1. We will use nested loops to iterate through rows and columns and print '*' at specific positions to form the hollow pattern. +2. For each row, we will check if it's the first row, last row, first column, or last column. If so, we will print a '*' character. Otherwise, we will print a space ' '. +3. This way, we will create the desired hollow pattern. + +Time Complexity: O(n^2) +- The program uses two nested loops to print the pattern, one for rows and one for columns. So, the time complexity is proportional to the square of 'n'. + +Space Complexity: O(1) +- The program uses a constant amount of extra space, as it only prints characters and does not use any additional data structures that depend on the input size 'n'. + +Sample Input: 5 +Sample Output: +* * * * * +* * +* * +* * +* * * * * + +In this example, the input 'n' is 5, and the program generates a hollow pattern of size 5x5 using asterisks. +*/ + +#include +using namespace std; + +void printHollowPattern(int n) { + // Iterate through each row + for (int i = 0; i < n; i++) { + // Iterate through each column in the row + for (int j = 0; j < n; j++) { + // Check if it's the first row, last row, first column, or last column + if (i == 0 || i == n - 1 || j == 0 || j == n - 1) { + cout << "* "; + } else { + cout << " "; + } + } + // Move to the next line after each row is printed + cout << endl; + } +} + +int main() { + int size; + cout << "Enter the size of the pattern: "; + cin >> size; + + printHollowPattern(size); + return 0; +} + From 16c86cf15f6863e5772a48c1119853c236960820 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Mon, 24 Jul 2023 11:33:54 +0530 Subject: [PATCH 1688/1894] Create HollowPattern.go --- Patterns/HollowPattern.go | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Patterns/HollowPattern.go diff --git a/Patterns/HollowPattern.go b/Patterns/HollowPattern.go new file mode 100644 index 00000000..d6fd1d24 --- /dev/null +++ b/Patterns/HollowPattern.go @@ -0,0 +1,54 @@ +/* +Program: To generate a hollow pattern using asterisks ('*'). The program will take an integer 'n' as input, which represents the size of the pattern, and it will produce a hollow pattern of the given size. + +Approach: +1. We will use nested loops to iterate through rows and columns and print '*' at specific positions to form the hollow pattern. +2. For each row, we will check if it's the first row, last row, first column, or last column. If so, we will print a '*' character. Otherwise, we will print a space ' '. +3. This way, we will create the desired hollow pattern. + +Time Complexity: O(n^2) +- The program uses two nested loops to print the pattern, one for rows and one for columns. So, the time complexity is proportional to the square of 'n'. + +Space Complexity: O(1) +- The program uses a constant amount of extra space, as it only prints characters and does not use any additional data structures that depend on the input size 'n'. + +Sample Input: 5 +Sample Output: +* * * * * +* * +* * +* * +* * * * * + +In this example, the input 'n' is 5, and the program generates a hollow pattern of size 5x5 using asterisks. +*/ + +package main + +import "fmt" + +func printHollowPattern(n int) { + // Iterate through each row + for i := 0; i < n; i++ { + // Iterate through each column in the row + for j := 0; j < n; j++ { + // Check if it's the first row, last row, first column, or last column + if i == 0 || i == n-1 || j == 0 || j == n-1 { + fmt.Print("* ") + } else { + fmt.Print(" ") + } + } + // Move to the next line after each row is printed + fmt.Println() + } +} + +func main() { + var size int + fmt.Print("Enter the size of the pattern: ") + fmt.Scan(&size) + + printHollowPattern(size) +} + From eff9b3b63d8638632be9f5fc7f4b23c8ec788e39 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:27:03 +0530 Subject: [PATCH 1689/1894] add max sum increasing subsequence in go --- .../max_sum_increasing_subsequence.go | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Dynamic Programming/max_sum_increasing_subsequence.go diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go new file mode 100644 index 00000000..659e59db --- /dev/null +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -0,0 +1,44 @@ +package main + +import "math" + +func MaxSumIncreasingSubsequence(array []int) (int, []int) { + sums := make([]int, len(array)) + sequences := make([]int, len(array)) + for i := range sequences { + sequences[i] = math.MinInt32 + sums[i] = array[i] + } + maxSumIndex := 0 + for i, currNum := range array { + for j := 0; j < i; j++ { + otherNum := array[j] + if otherNum < currNum && currNum + sums[j] >= sums[i] { + sums[i] = currNum + sums[j] + sequences[i] = j + } + } + if sums[i] > sums[maxSumIndex] { + maxSumIndex = i + } + } + sum := sums[maxSumIndex] + sequence := buildSequence(array, sequences, maxSumIndex) + return sum, sequence +} + +func buildSequence(array []int, sequences []int, index int) []int { + sequence := []int{} + for index != math.MinInt32 { + sequence = append(sequence, array[index]) + index = sequences[index] + } + reverse(sequence) + return sequence +} + +func reverse(numbers []int) { + for i, j := 0, len(numbers) - 1; i < j; i, j = i+1, j-1 { + numbers[i], numbers[j] = numbers[j], numbers[i] + } +} \ No newline at end of file From 804d8840859e95de16b02857d07be20d21b8f824 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:27:42 +0530 Subject: [PATCH 1690/1894] add comments --- .../max_sum_increasing_subsequence.go | 90 ++++++++++++------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go index 659e59db..f3297bee 100644 --- a/Dynamic Programming/max_sum_increasing_subsequence.go +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -2,43 +2,67 @@ package main import "math" +// MaxSumIncreasingSubsequence finds the maximum sum increasing subsequence in the given array of integers. func MaxSumIncreasingSubsequence(array []int) (int, []int) { - sums := make([]int, len(array)) - sequences := make([]int, len(array)) - for i := range sequences { - sequences[i] = math.MinInt32 - sums[i] = array[i] - } - maxSumIndex := 0 - for i, currNum := range array { - for j := 0; j < i; j++ { - otherNum := array[j] - if otherNum < currNum && currNum + sums[j] >= sums[i] { - sums[i] = currNum + sums[j] - sequences[i] = j - } - } - if sums[i] > sums[maxSumIndex] { - maxSumIndex = i - } - } - sum := sums[maxSumIndex] - sequence := buildSequence(array, sequences, maxSumIndex) - return sum, sequence + // Initialize two arrays to store maximum sums and the previous elements contributing to the sums. + sums := make([]int, len(array)) + sequences := make([]int, len(array)) + + // Initialize each element in 'sums' array to its corresponding element in the input array. + // Also, initialize each element in 'sequences' array to a sentinel value 'math.MinInt32'. + for i := range sequences { + sequences[i] = math.MinInt32 + sums[i] = array[i] + } + + // Variable to keep track of the index with the maximum sum. + maxSumIndex := 0 + + // Iterate through the input array and calculate the maximum sum increasing subsequences. + for i, currNum := range array { + for j := 0; j < i; j++ { + otherNum := array[j] + if otherNum < currNum && currNum+sums[j] >= sums[i] { + // If the current element can extend the increasing subsequence with a better sum, + // update the 'sums' and 'sequences' arrays accordingly. + sums[i] = currNum + sums[j] + sequences[i] = j + } + } + + // Update the index with the maximum sum if the current sum is greater. + if sums[i] > sums[maxSumIndex] { + maxSumIndex = i + } + } + + // Get the maximum sum from the 'sums' array and the increasing subsequence from the 'sequences' array. + sum := sums[maxSumIndex] + sequence := buildSequence(array, sequences, maxSumIndex) + return sum, sequence } +// buildSequence reconstructs the increasing subsequence from the 'sequences' array. func buildSequence(array []int, sequences []int, index int) []int { - sequence := []int{} - for index != math.MinInt32 { - sequence = append(sequence, array[index]) - index = sequences[index] - } - reverse(sequence) - return sequence + sequence := []int{} + + // Traverse the 'sequences' array starting from the 'index' until reaching the sentinel value 'math.MinInt32'. + for index != math.MinInt32 { + // Add the element at the current index to the 'sequence' array. + sequence = append(sequence, array[index]) + + // Move to the previous index using 'sequences' array. + index = sequences[index] + } + + // Reverse the 'sequence' array since it was built backward. + reverse(sequence) + return sequence } +// reverse is a helper function used to reverse the elements in the 'sequence' array. func reverse(numbers []int) { - for i, j := 0, len(numbers) - 1; i < j; i, j = i+1, j-1 { - numbers[i], numbers[j] = numbers[j], numbers[i] - } -} \ No newline at end of file + for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 { + numbers[i], numbers[j] = numbers[j], numbers[i] + } +} From c846d6bf432d4b124e324dd44e625d34ec32bb41 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:28:27 +0530 Subject: [PATCH 1691/1894] add question --- Dynamic Programming/max_sum_increasing_subsequence.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go index f3297bee..d7150f7b 100644 --- a/Dynamic Programming/max_sum_increasing_subsequence.go +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -1,3 +1,8 @@ +/* + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + +*/ package main import "math" From 6293dd4df5ad65a077283daaca0ada0bc181c518 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:28:52 +0530 Subject: [PATCH 1692/1894] add explanation --- .../max_sum_increasing_subsequence.go | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go index d7150f7b..d5de4f51 100644 --- a/Dynamic Programming/max_sum_increasing_subsequence.go +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -1,7 +1,27 @@ /* - Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. - + + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + + Here's a step-by-step explanation of the code: + + 1. The function `MaxSumIncreasingSubsequence` takes an input array of integers called `array`. + + 2. Two arrays `sums` and `sequences` are initialized with the same length as the input array. The `sums` array stores the maximum sum of increasing subsequences ending at the corresponding index, and the `sequences` array stores the previous index that contributes to the maximum sum at the current index. + + 3. The `maxSumIndex` variable is used to keep track of the index with the maximum sum of an increasing subsequence. + + 4. The code uses a dynamic programming approach to calculate the maximum sum of increasing subsequences. It iterates through the input array from left to right and, for each element, checks all the previous elements to find the ones that are less than the current element and can form an increasing subsequence with it. If a better sum is found for the current element, it updates the `sums` and `sequences` arrays. + + 5. After iterating through the entire array, the `maxSumIndex` stores the index with the maximum sum of an increasing subsequence. + + 6. The function `buildSequence` is used to reconstruct the actual increasing subsequence from the `sequences` array, starting from the `maxSumIndex` and going backward until it reaches an element with a value of `math.MinInt32`, which is used as a sentinel value to indicate the end of the sequence. + + 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. + + 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). */ package main From bb1ae44341823cfce46568f03877395791da24ec Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:29:14 +0530 Subject: [PATCH 1693/1894] add time and space complexity --- Dynamic Programming/max_sum_increasing_subsequence.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go index d5de4f51..188e0548 100644 --- a/Dynamic Programming/max_sum_increasing_subsequence.go +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -1,9 +1,9 @@ /* - Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated - from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. - Explanation: - The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. Here's a step-by-step explanation of the code: @@ -22,6 +22,8 @@ 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). + + O(n^2) time | O(n) space - where n is the length of the input array */ package main From 26b978a25ef65147aab49c5e446027bf48cdb42c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 25 Jul 2023 22:29:57 +0530 Subject: [PATCH 1694/1894] add sample io --- Dynamic Programming/max_sum_increasing_subsequence.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Dynamic Programming/max_sum_increasing_subsequence.go b/Dynamic Programming/max_sum_increasing_subsequence.go index 188e0548..6e0cb129 100644 --- a/Dynamic Programming/max_sum_increasing_subsequence.go +++ b/Dynamic Programming/max_sum_increasing_subsequence.go @@ -2,6 +2,9 @@ Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + Sample Input: = [10, 70, 20, 30, 50, 11, 30] + Output : [110, [10, 20, 30, 50]] + Explanation: The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. From ffd72431f820459e5f7cc1e5c58473c9093352a8 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 26 Jul 2023 19:38:28 +0530 Subject: [PATCH 1695/1894] Create Min_palindrome.js --- Strings/Min_palindrome.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Strings/Min_palindrome.js diff --git a/Strings/Min_palindrome.js b/Strings/Min_palindrome.js new file mode 100644 index 00000000..543bd29d --- /dev/null +++ b/Strings/Min_palindrome.js @@ -0,0 +1,31 @@ +function minInsertionStepsToPalindrome(str) { + const n = str.length; + // Create a 2D array to store the minimum steps needed to make substrings palindrome + const dp = Array.from({ length: n }, () => Array(n).fill(0)); + + // Base case: single characters are palindromes, so dp[i][i] = 0 + for (let i = 0; i < n; i++) { + dp[i][i] = 0; + } + + // Fill the dp table in bottom-up manner + for (let len = 2; len <= n; len++) { + for (let i = 0; i < n - len + 1; i++) { + const j = i + len - 1; + if (str[i] === str[j]) { + // If the characters at the ends are the same, no additional insertion is needed + dp[i][j] = dp[i + 1][j - 1]; + } else { + // Otherwise, choose the minimum between inserting character at i or j + dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]); + } + } + } + + return dp[0][n - 1]; +} + +// Example usage: +const str = "abcd"; +const minInsertions = minInsertionStepsToPalindrome(str); +console.log("Minimum insertion steps:", minInsertions); // Output: 3 (abcd -> dabcbad) From 439f3ea9e742260d14842b959c10968f5b36dbaf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Jul 2023 22:06:57 +0530 Subject: [PATCH 1696/1894] add max sum increasing subsequence in cpp --- .../max_sum_increasing_subsequence.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Dynamic Programming/max_sum_increasing_subsequence.cpp diff --git a/Dynamic Programming/max_sum_increasing_subsequence.cpp b/Dynamic Programming/max_sum_increasing_subsequence.cpp new file mode 100644 index 00000000..3a093b0f --- /dev/null +++ b/Dynamic Programming/max_sum_increasing_subsequence.cpp @@ -0,0 +1,63 @@ +/* + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + + Sample Input: = [10, 70, 20, 30, 50, 11, 30] + Output : [110, [10, 20, 30, 50]] + + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + + Here's a step-by-step explanation of the code: + + 1. The function `MaxSumIncreasingSubsequence` takes an input array of integers called `array`. + + 2. Two arrays `sums` and `sequences` are initialized with the same length as the input array. The `sums` array stores the maximum sum of increasing subsequences ending at the corresponding index, and the `sequences` array stores the previous index that contributes to the maximum sum at the current index. + + 3. The `maxSumIndex` variable is used to keep track of the index with the maximum sum of an increasing subsequence. + + 4. The code uses a dynamic programming approach to calculate the maximum sum of increasing subsequences. It iterates through the input array from left to right and, for each element, checks all the previous elements to find the ones that are less than the current element and can form an increasing subsequence with it. If a better sum is found for the current element, it updates the `sums` and `sequences` arrays. + + 5. After iterating through the entire array, the `maxSumIndex` stores the index with the maximum sum of an increasing subsequence. + + 6. The function `buildSequence` is used to reconstruct the actual increasing subsequence from the `sequences` array, starting from the `maxSumIndex` and going backward until it reaches an element with a value of `math.MinInt32`, which is used as a sentinel value to indicate the end of the sequence. + + 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. + + 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). + + O(n^2) time | O(n) space - where n is the length of the input array +*/ + +#include +#include + +std::pair> MaxSumIncreasingSubsequence(std::vector& array) { + int n = array.size(); + std::vector sums(n); // Store the maximum increasing sum up to index i. + std::vector sequences(n, -1); // Store the previous index of the increasing subsequence. + + for (int i = 0; i < n; i++) { + sums[i] = array[i]; + for (int j = 0; j < i; j++) { + if (array[i] > array[j] && sums[j] + array[i] > sums[i]) { + sums[i] = sums[j] + array[i]; + sequences[i] = j; + } + } + } + + // Find the index of the maximum sum in 'sums'. + int maxSumIndex = std::max_element(sums.begin(), sums.end()) - sums.begin(); + int maxSum = sums[maxSumIndex]; + + // Build the increasing subsequence using the 'sequences' array. + std::vector sequence; + while (maxSumIndex != -1) { + sequence.push_back(array[maxSumIndex]); + maxSumIndex = sequences[maxSumIndex]; + } + std::reverse(sequence.begin(), sequence.end()); + + return std::make_pair(maxSum, sequence); +} From 51e1ea8d64d9f3a824f32add54fbd909b31d688c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Jul 2023 22:07:54 +0530 Subject: [PATCH 1697/1894] add max sum increasing subsequence in python --- .../max_sum_increasing_subsequence.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Dynamic Programming/max_sum_increasing_subsequence.py diff --git a/Dynamic Programming/max_sum_increasing_subsequence.py b/Dynamic Programming/max_sum_increasing_subsequence.py new file mode 100644 index 00000000..bc3868c0 --- /dev/null +++ b/Dynamic Programming/max_sum_increasing_subsequence.py @@ -0,0 +1,53 @@ +''' + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + + Sample Input: = [10, 70, 20, 30, 50, 11, 30] + Output : [110, [10, 20, 30, 50]] + + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + + Here's a step-by-step explanation of the code: + + 1. The function `MaxSumIncreasingSubsequence` takes an input array of integers called `array`. + + 2. Two arrays `sums` and `sequences` are initialized with the same length as the input array. The `sums` array stores the maximum sum of increasing subsequences ending at the corresponding index, and the `sequences` array stores the previous index that contributes to the maximum sum at the current index. + + 3. The `maxSumIndex` variable is used to keep track of the index with the maximum sum of an increasing subsequence. + + 4. The code uses a dynamic programming approach to calculate the maximum sum of increasing subsequences. It iterates through the input array from left to right and, for each element, checks all the previous elements to find the ones that are less than the current element and can form an increasing subsequence with it. If a better sum is found for the current element, it updates the `sums` and `sequences` arrays. + + 5. After iterating through the entire array, the `maxSumIndex` stores the index with the maximum sum of an increasing subsequence. + + 6. The function `buildSequence` is used to reconstruct the actual increasing subsequence from the `sequences` array, starting from the `maxSumIndex` and going backward until it reaches an element with a value of `math.MinInt32`, which is used as a sentinel value to indicate the end of the sequence. + + 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. + + 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). + + O(n^2) time | O(n) space - where n is the length of the input array +''' +def max_sum_increasing_subsequence(array): + n = len(array) + sums = [num for num in array] # Store the maximum increasing sum up to index i. + sequences = [-1] * n # Store the previous index of the increasing subsequence. + + for i in range(n): + for j in range(i): + if array[i] > array[j] and sums[j] + array[i] > sums[i]: + sums[i] = sums[j] + array[i] + sequences[i] = j + + # Find the index of the maximum sum in 'sums'. + max_sum_index = max(range(n), key=lambda i: sums[i]) + max_sum = sums[max_sum_index] + + # Build the increasing subsequence using the 'sequences' array. + sequence = [] + while max_sum_index != -1: + sequence.append(array[max_sum_index]) + max_sum_index = sequences[max_sum_index] + sequence.reverse() + + return max_sum, sequence From 2523bfc716f7e3a31ad5648acd303d8ede58fd28 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Jul 2023 22:09:43 +0530 Subject: [PATCH 1698/1894] add max sum increasing subsequence in java --- .../max_sum_increasing_subsequence.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Dynamic Programming/max_sum_increasing_subsequence.java diff --git a/Dynamic Programming/max_sum_increasing_subsequence.java b/Dynamic Programming/max_sum_increasing_subsequence.java new file mode 100644 index 00000000..bbdeaedc --- /dev/null +++ b/Dynamic Programming/max_sum_increasing_subsequence.java @@ -0,0 +1,82 @@ +/* + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + + Sample Input: = [10, 70, 20, 30, 50, 11, 30] + Output : [110, [10, 20, 30, 50]] + + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + + Here's a step-by-step explanation of the code: + + 1. The function `MaxSumIncreasingSubsequence` takes an input array of integers called `array`. + + 2. Two arrays `sums` and `sequences` are initialized with the same length as the input array. The `sums` array stores the maximum sum of increasing subsequences ending at the corresponding index, and the `sequences` array stores the previous index that contributes to the maximum sum at the current index. + + 3. The `maxSumIndex` variable is used to keep track of the index with the maximum sum of an increasing subsequence. + + 4. The code uses a dynamic programming approach to calculate the maximum sum of increasing subsequences. It iterates through the input array from left to right and, for each element, checks all the previous elements to find the ones that are less than the current element and can form an increasing subsequence with it. If a better sum is found for the current element, it updates the `sums` and `sequences` arrays. + + 5. After iterating through the entire array, the `maxSumIndex` stores the index with the maximum sum of an increasing subsequence. + + 6. The function `buildSequence` is used to reconstruct the actual increasing subsequence from the `sequences` array, starting from the `maxSumIndex` and going backward until it reaches an element with a value of `math.MinInt32`, which is used as a sentinel value to indicate the end of the sequence. + + 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. + + 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). + + O(n^2) time | O(n) space - where n is the length of the input array +*/ +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; + +public class Main { + public static int[] maxSumIncreasingSubsequence(int[] array) { + int n = array.length; + int[] sums = Arrays.copyOf(array, n); // Store the maximum increasing sum up to index i. + int[] sequences = new int[n]; + Arrays.fill(sequences, -1); // Store the previous index of the increasing subsequence. + + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + if (array[i] > array[j] && sums[j] + array[i] > sums[i]) { + sums[i] = sums[j] + array[i]; + sequences[i] = j; + } + } + } + + // Find the index of the maximum sum in 'sums'. + int maxSumIndex = 0; + for (int i = 1; i < n; i++) { + if (sums[i] > sums[maxSumIndex]) { + maxSumIndex = i; + } + } + int maxSum = sums[maxSumIndex]; + + // Build the increasing subsequence using the 'sequences' array. + List sequenceList = new ArrayList<>(); + while (maxSumIndex != -1) { + sequenceList.add(array[maxSumIndex]); + maxSumIndex = sequences[maxSumIndex]; + } + + // Convert the list to an array and reverse it to get the correct order. + int[] sequence = new int[sequenceList.size()]; + for (int i = 0; i < sequence.length; i++) { + sequence[i] = sequenceList.get(sequenceList.size() - i - 1); + } + + return new int[]{maxSum, sequence}; + } + + public static void main(String[] args) { + int[] array = {4, 6, 1, 3, 8, 4, 6}; + int[] result = maxSumIncreasingSubsequence(array); + System.out.println("Max Sum: " + result[0]); + System.out.println("Increasing Subsequence: " + Arrays.toString(result[1])); + } +} From ab25d0f935e1974e7150c4ce5d8ec23481b95009 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 26 Jul 2023 22:09:59 +0530 Subject: [PATCH 1699/1894] add max sum increasing subsequence in js --- .../max_sum_increasing_subsequence.js | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Dynamic Programming/max_sum_increasing_subsequence.js diff --git a/Dynamic Programming/max_sum_increasing_subsequence.js b/Dynamic Programming/max_sum_increasing_subsequence.js new file mode 100644 index 00000000..2ffb0342 --- /dev/null +++ b/Dynamic Programming/max_sum_increasing_subsequence.js @@ -0,0 +1,64 @@ +/* + Write a function that takes in a non-empty array of integers and returns the greatest sum that can be generated + from a strictly-increasing subsequence in the array as well as an array of the numbers in that subsequence. + + Sample Input: = [10, 70, 20, 30, 50, 11, 30] + Output : [110, [10, 20, 30, 50]] + + Explanation: + The given code snippet implements a function called `MaxSumIncreasingSubsequence`, which finds the maximum sum increasing subsequence in a given array of integers. An increasing subsequence is a sequence of array elements where each element is strictly greater than the previous element. + + Here's a step-by-step explanation of the code: + + 1. The function `MaxSumIncreasingSubsequence` takes an input array of integers called `array`. + + 2. Two arrays `sums` and `sequences` are initialized with the same length as the input array. The `sums` array stores the maximum sum of increasing subsequences ending at the corresponding index, and the `sequences` array stores the previous index that contributes to the maximum sum at the current index. + + 3. The `maxSumIndex` variable is used to keep track of the index with the maximum sum of an increasing subsequence. + + 4. The code uses a dynamic programming approach to calculate the maximum sum of increasing subsequences. It iterates through the input array from left to right and, for each element, checks all the previous elements to find the ones that are less than the current element and can form an increasing subsequence with it. If a better sum is found for the current element, it updates the `sums` and `sequences` arrays. + + 5. After iterating through the entire array, the `maxSumIndex` stores the index with the maximum sum of an increasing subsequence. + + 6. The function `buildSequence` is used to reconstruct the actual increasing subsequence from the `sequences` array, starting from the `maxSumIndex` and going backward until it reaches an element with a value of `math.MinInt32`, which is used as a sentinel value to indicate the end of the sequence. + + 7. The `reverse` function is a helper function used to reverse the elements in the `sequence` array since the subsequence was built backward. + + 8. The function returns the maximum sum of the increasing subsequence (`sum`) and the subsequence itself (`sequence`). + + O(n^2) time | O(n) space - where n is the length of the input array +*/ + +function maxSumIncreasingSubsequence(array) { + const n = array.length; + const sums = [...array]; // Store the maximum increasing sum up to index i. + const sequences = new Array(n).fill(-1); // Store the previous index of the increasing subsequence. + + for (let i = 0; i < n; i++) { + for (let j = 0; j < i; j++) { + if (array[i] > array[j] && sums[j] + array[i] > sums[i]) { + sums[i] = sums[j] + array[i]; + sequences[i] = j; + } + } + } + + // Find the index of the maximum sum in 'sums'. + let maxSumIndex = 0; + for (let i = 1; i < n; i++) { + if (sums[i] > sums[maxSumIndex]) { + maxSumIndex = i; + } + } + const maxSum = sums[maxSumIndex]; + + // Build the increasing subsequence using the 'sequences' array. + const sequence = []; + while (maxSumIndex !== -1) { + sequence.push(array[maxSumIndex]); + maxSumIndex = sequences[maxSumIndex]; + } + sequence.reverse(); + + return [maxSum, sequence]; +} From 773608728f0fb1c07c6b4fa9f45d1dd1c9e150b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Jul 2023 21:46:37 +0530 Subject: [PATCH 1700/1894] add min number of jumps in go --- Dynamic Programming/min_number_of_jumps.go | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Dynamic Programming/min_number_of_jumps.go diff --git a/Dynamic Programming/min_number_of_jumps.go b/Dynamic Programming/min_number_of_jumps.go new file mode 100644 index 00000000..e69de29b From 17574c3bd37f19d320d5b6594db6241895c09580 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Jul 2023 21:46:52 +0530 Subject: [PATCH 1701/1894] add min number of jumps in go --- Dynamic Programming/min_number_of_jumps.go | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/Dynamic Programming/min_number_of_jumps.go b/Dynamic Programming/min_number_of_jumps.go index e69de29b..d6ab4f61 100644 --- a/Dynamic Programming/min_number_of_jumps.go +++ b/Dynamic Programming/min_number_of_jumps.go @@ -0,0 +1,39 @@ +package main + +import "math" + +// MinNumberOfJumps calculates the minimum number of jumps required to reach the last element of the `array`. +func MinNumberOfJumps(array []int) int { + // Create an array to store the minimum number of jumps required to reach each position in the `array`. + ways := make([]int, len(array)) + + // Initialize the `ways` array with maximum integer values representing an unreachable state. + for i := range ways { + ways[i] = math.MaxInt32 + } + + // Base case: The first element requires 0 jumps to reach itself. + ways[0] = 0 + + // Iterate through the array starting from the second element. + for i := 1; i < len(array); i++ { + // Check all previous elements to see if a jump from j to i is possible. + for j := 0; j < i; j++ { + // If it is possible to jump from j to i, update the `ways[i]` value. + if array[j] + j >= i { + ways[i] = min(ways[i], ways[j]+1) + } + } + } + + // The value at `ways[len(ways) - 1]` will contain the minimum number of jumps required to reach the last element. + return ways[len(ways)-1] +} + +// min returns the minimum of two integers. +func min(a, b int) int { + if a < b { + return a + } + return b +} From cd20fb9f3aa5e50f96ae2cc3a58e799b8d692fad Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Jul 2023 21:47:15 +0530 Subject: [PATCH 1702/1894] add optimal sol --- Dynamic Programming/min_number_of_jumps.go | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Dynamic Programming/min_number_of_jumps.go b/Dynamic Programming/min_number_of_jumps.go index d6ab4f61..b504631c 100644 --- a/Dynamic Programming/min_number_of_jumps.go +++ b/Dynamic Programming/min_number_of_jumps.go @@ -37,3 +37,40 @@ func min(a, b int) int { } return b } + + +func MinNumberOfJumpsOptimal(array []int) int { + // If the array has only one element, no jumps are needed. + if len(array) == 1 { + return 0 + } + + // Initialize variables to keep track of jumps, maximum reachable position, and remaining steps in a jump. + jumps := 0 + maxreach, steps := array[0], array[0] + + // Iterate through the array to calculate the minimum number of jumps. + // We stop at the second-to-last element as we don't need an additional jump from there. + for i := 1; i < len(array)-1; i++ { + // Update the maximum reachable position if the current position plus the value at that index is greater. + if i+array[i] > maxreach { + maxreach = i + array[i] + } + + // Decrement the remaining steps in the current jump. + steps-- + + // If the current jump is completed (steps becomes 0), calculate the new jump. + if steps == 0 { + // Increment jumps to count the completed jump. + jumps++ + + // Update steps to the number of steps required to reach the farthest position. + steps = maxreach - i + } + } + + // The minimum number of jumps to reach the last element is the total number of jumps taken plus one + // because the loop doesn't consider the last element (as we don't need an additional jump from there). + return jumps + 1 +} From 6014bfce7a205ea8fc595ed956293a35560a615b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Jul 2023 21:48:04 +0530 Subject: [PATCH 1703/1894] add explanation --- Dynamic Programming/min_number_of_jumps.go | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Dynamic Programming/min_number_of_jumps.go b/Dynamic Programming/min_number_of_jumps.go index b504631c..fac1cc60 100644 --- a/Dynamic Programming/min_number_of_jumps.go +++ b/Dynamic Programming/min_number_of_jumps.go @@ -1,3 +1,35 @@ +/* + This Go code snippet implements the `MinNumberOfJumps` function, which calculates the minimum number of jumps required to reach the + last element of the `array` by starting from the first element. Each element of the array represents the maximum number of steps that + can be taken from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an array `array` as input and returns the minimum number of jumps required. + + 2. The `ways` array is initialized to store the minimum number of jumps required to reach each position in the input array. The length of + the `ways` array is the same as the input array, and all values are initialized to `math.MaxInt32`, which represents an unreachable state. + + 3. The base case is set for the first element of the `ways` array. Since we are already at the first element, the minimum number of jumps + required is 0. So, `ways[0]` is set to 0. + + 4. Starting from the second element (i = 1) to the last element (i = len(array) - 1), the function iterates through the `array`. + + 5. For each element, it iterates through all previous elements (j) up to the current position (i) to check if it is possible to jump from j to i. + + 6. If `array[j] + j >= i`, it means we can jump from position `j` to position `i`. + + 7. The `ways[i]` value is then updated using the minimum between the current `ways[i]` value and `ways[j] + 1`. The `ways[j] + 1` represents + the minimum number of jumps required to reach position `j`, and then from position `j` to position `i`. + + 8. After all iterations, `ways[len(ways) - 1]` will contain the minimum number of jumps required to reach the last element of the array. + + 9. The `min` function is a helper function that returns the minimum of two integers. + + The `MinNumberOfJumps` function uses dynamic programming to find the minimum number of jumps efficiently by keeping track of the minimum number + of jumps required to reach each position from the previous positions. The time complexity of this function is O(n^2), where n is the length of + the input array. The space complexity is O(n), as the `ways` array is used to store the minimum jumps for each position in the array. +*/ package main import "math" From f3270762d2dcd7040a8ea950fce47837fe3b1016 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 27 Jul 2023 21:49:01 +0530 Subject: [PATCH 1704/1894] add explanation --- Dynamic Programming/min_number_of_jumps.go | 38 ++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Dynamic Programming/min_number_of_jumps.go b/Dynamic Programming/min_number_of_jumps.go index fac1cc60..4eed365e 100644 --- a/Dynamic Programming/min_number_of_jumps.go +++ b/Dynamic Programming/min_number_of_jumps.go @@ -71,6 +71,44 @@ func min(a, b int) int { } +/* + The given code snippet calculates the minimum number of jumps required to reach the end of an array of integers. + Each element in the array represents the maximum distance you can jump from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an integer array `array` as input and returns the minimum number of jumps + required to reach the last element. + + 2. The code first checks if the length of the `array` is 1. If so, it means there's only one element, and we don't + need any jumps to reach the end. In this case, the function returns 0. + + 3. If the array has more than one element, the code proceeds with the jump calculation. + + 4. The variables `jumps`, `maxreach`, and `steps` are initialized. `jumps` keeps track of the total number of jumps + taken, `maxreach` represents the farthest position that can be reached in a single jump, and `steps` represents the + remaining steps until a new jump is required. + + 5. The loop starts from the second element (index 1) and iterates until the second-to-last element (index `len(array) - 1`). + The reason for stopping at the second-to-last element is that we don't need to take any additional jumps from there, as + we are already at the end. + + 6. For each iteration, the code checks if the current index plus the value at that index (`i + array[i]`) is greater + than the current `maxreach`. If so, it updates `maxreach` to the new value, representing the farthest position that + can be reached in a single jump. + + 7. It then decrements `steps` by 1, representing the steps taken in the current jump. + + 8. If `steps` becomes 0, it means the current jump is completed, and a new jump is required. So, it increments `jumps` + by 1 and updates `steps` with the number of steps required to reach the farthest position (i.e., `maxreach - i`). + + 9. After the loop completes, the function returns `jumps + 1`. The `+1` is added because the loop doesn't consider the + last element in the array (as we don't need an additional jump from there), so we need to add one more jump to reach the last element. + + In summary, the code efficiently calculates the minimum number of jumps required to reach the last element in the array + by simulating the jumps and keeping track of the farthest position that can be reached in each jump. The final result + is the total number of jumps taken to reach the end. +*/ func MinNumberOfJumpsOptimal(array []int) int { // If the array has only one element, no jumps are needed. if len(array) == 1 { From 9330d9c0084b88f606bb222d13d3defb8baba0a3 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 28 Jul 2023 12:39:11 +0530 Subject: [PATCH 1705/1894] Create Dp_plaindrome.py --- Strings/Dp_plaindrome.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Strings/Dp_plaindrome.py diff --git a/Strings/Dp_plaindrome.py b/Strings/Dp_plaindrome.py new file mode 100644 index 00000000..ce9b8fda --- /dev/null +++ b/Strings/Dp_plaindrome.py @@ -0,0 +1,17 @@ +def find_min_insertion_steps(s): + n = len(s) + dp = [[0] * n for _ in range(n)] + + for length in range(2, n + 1): + for i in range(n - length + 1): + j = i + length - 1 + if s[i] == s[j]: + dp[i][j] = dp[i + 1][j - 1] + else: + dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1 + + return dp[0][n - 1] + +# Test the function +string = "abcd" +print("Minimum Insertion Steps:", find_min_insertion_steps(string)) From 3ae664bf05b92d4e6d5d6a7fd498de035553f4b0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Jul 2023 22:12:45 +0530 Subject: [PATCH 1706/1894] add knapsack in go --- Dynamic Programming/knapsack.go | 53 +++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Dynamic Programming/knapsack.go diff --git a/Dynamic Programming/knapsack.go b/Dynamic Programming/knapsack.go new file mode 100644 index 00000000..7f748603 --- /dev/null +++ b/Dynamic Programming/knapsack.go @@ -0,0 +1,53 @@ +package main + +func KnapsackProblem(items [][]int, capacity int) []interface{} { + values := make([][]int, len(items)+1) + for i := range values { + values[i] = make([]int, capacity+1) + } + for i := 1; i < len(items)+1; i++ { + currentValue := items[i-1][0] + currentWeight := items[i-1][1] + for c := 0; c < capacity+1; c++ { + if currentWeight > c { + values[i][c] = values[i-1][c] + } else { + values[i][c] = max(values[i-1][c], values[i-1][c-currentWeight]+currentValue) + } + } + } + value := values[len(items)][capacity] + sequence := getKnapSackItems(values, items) + return []interface{}{value, sequence} +} + +func getKnapSackItems(values [][]int, items [][]int) []int { + sequence := []int{} + i, c := len(values)-1, len(values[0])-1 + for i > 0 { + if values[i][c] == values[i-1][c] { + i-- + } else { + sequence = append(sequence, i-1) + c -= items[i-1][1] + i-- + } + if c == 0 { + break + } + } + reverse(sequence) + return sequence +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +func reverse(numbers []int) { + for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 { + numbers[i], numbers[j] = numbers[j], numbers[i] + } +} \ No newline at end of file From ad5533bef909508d584437134d320744d79346cc Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Jul 2023 22:14:19 +0530 Subject: [PATCH 1707/1894] add question --- Dynamic Programming/knapsack.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Dynamic Programming/knapsack.go b/Dynamic Programming/knapsack.go index 7f748603..b0a325ed 100644 --- a/Dynamic Programming/knapsack.go +++ b/Dynamic Programming/knapsack.go @@ -1,3 +1,15 @@ +/* + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. + + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. + +*/ package main func KnapsackProblem(items [][]int, capacity int) []interface{} { From c193919137d3a36dcc1e2c92cf5ef935e7b38709 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Jul 2023 22:15:34 +0530 Subject: [PATCH 1708/1894] add comments --- Dynamic Programming/knapsack.go | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Dynamic Programming/knapsack.go b/Dynamic Programming/knapsack.go index b0a325ed..a7cc2076 100644 --- a/Dynamic Programming/knapsack.go +++ b/Dynamic Programming/knapsack.go @@ -9,57 +9,89 @@ Write a function that returns the maximized combined value of the items that you should pick as well as an array of the indices of each item picked. + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] */ package main func KnapsackProblem(items [][]int, capacity int) []interface{} { + // Create a 2D array to store the values of different knapsack configurations. values := make([][]int, len(items)+1) for i := range values { values[i] = make([]int, capacity+1) } + + // Iterate through the items and fill the values array. for i := 1; i < len(items)+1; i++ { currentValue := items[i-1][0] currentWeight := items[i-1][1] + for c := 0; c < capacity+1; c++ { + // If the current item's weight is more than the current capacity (c), + // then we cannot include it, so we use the value from the previous row (i - 1). if currentWeight > c { values[i][c] = values[i-1][c] } else { + // If we can include the current item, we have two choices: + // 1. Not include the current item, so the value remains the same as the previous row. + // 2. Include the current item, which adds its value to the value of the knapsack at capacity (c - currentWeight). + // We choose the maximum of these two options. values[i][c] = max(values[i-1][c], values[i-1][c-currentWeight]+currentValue) } } } + + // The value at the bottom-right corner of the values array represents the maximum achievable value for the knapsack problem. value := values[len(items)][capacity] + + // Call the getKnapSackItems function to find the items that were included in the knapsack to achieve the maximum value. sequence := getKnapSackItems(values, items) + + // Return the maximum value and the sequence of items included in the knapsack as an interface slice. return []interface{}{value, sequence} } +// getKnapSackItems is a helper function to find the sequence of items included in the knapsack. func getKnapSackItems(values [][]int, items [][]int) []int { sequence := []int{} i, c := len(values)-1, len(values[0])-1 + + // Starting from the bottom-right corner of the values array, + // we traverse back to find the items included in the knapsack. for i > 0 { if values[i][c] == values[i-1][c] { + // If the value is the same as in the previous row, it means the current item was not included. + // So, we move to the previous row without adding the item to the sequence. i-- } else { + // If the value is greater than the value in the previous row, it means the current item was included. + // So, we add the index of the current item (i-1) to the sequence and update the capacity (c) accordingly. sequence = append(sequence, i-1) c -= items[i-1][1] i-- } + // If the capacity becomes 0, it means we have included all the items needed to achieve the maximum value. if c == 0 { break } } + + // The sequence of items is built in reverse order, so we need to reverse it to get the correct order. reverse(sequence) return sequence } +// max returns the maximum of two integers. func max(a, b int) int { if a > b { return a } return b } + +// reverse reverses the order of elements in the given slice. func reverse(numbers []int) { for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 { numbers[i], numbers[j] = numbers[j], numbers[i] } -} \ No newline at end of file +} From 7860c316fc458188921f5be417303c8229572d8d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 28 Jul 2023 22:18:18 +0530 Subject: [PATCH 1709/1894] add explanation --- Dynamic Programming/knapsack.go | 73 +++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 9 deletions(-) diff --git a/Dynamic Programming/knapsack.go b/Dynamic Programming/knapsack.go index a7cc2076..9eadad72 100644 --- a/Dynamic Programming/knapsack.go +++ b/Dynamic Programming/knapsack.go @@ -1,16 +1,71 @@ /* - You're given an array of arrays where each subarray holds two integer values and represents an item; - the first integer is the item's value, and the second integer is the item's weight. - You're also given an integer representing the maximum capacity of a knapsack that you have. + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. - Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's - capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. - Write a function that returns the maximized combined value of the items that you should pick as well as an array of - the indices of each item picked. + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. - Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] - Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + + Explanation: + + Sure! Let's break down the code step by step: + + 1. `KnapsackProblem` function: This function takes in two arguments - `items`, a 2D slice representing the + list of items with their values and weights, and `capacity`, an integer representing the maximum weight + capacity of the knapsack. It returns an interface slice containing the maximum value that can be achieved + and the sequence of items included in the knapsack to achieve that maximum value. + + 2. Initializing the `values` array: The function creates a 2D slice called `values` to store the maximum + achievable values for different knapsack configurations. The size of this array is `(len(items)+1) x (capacity+1)`, + where `(len(items)+1)` represents the number of items, and `(capacity+1)` represents the weight capacity of the knapsack. + The `values` array will be filled during the dynamic programming process. + + 3. Filling the `values` array: The function iterates through the `items` array and fills the `values` + array using dynamic programming. For each item at index `i`, the function calculates the maximum achievable + value for all possible capacities from `0` to `capacity`. + + 4. Inner loop: The inner loop iterates from `0` to `capacity` and calculates the maximum achievable value for + the current item at index `i` and the current capacity `c`. + + 5. Updating the `values` array: There are two possibilities for each item: + a. If the weight of the current item `items[i-1][1]` is greater than the current capacity `c`, we cannot + include the item in the knapsack at this capacity. So, we use the value from the previous row `values[i-1][c]` + for the current cell `values[i][c]`. + b. If we can include the current item, we have two choices: + i. Not include the current item, so the value remains the same as in the previous row `values[i-1][c]`. + ii. Include the current item, which adds its value `items[i-1][0]` to the value of the knapsack at capacity `c - items[i-1][1]`. + We choose the maximum of these two options and update the current cell `values[i][c]`. + + 6. Finding the maximum value: Once the `values` array is filled, the maximum achievable value for the knapsack is stored in the + bottom-right cell `values[len(items)][capacity]`. + + 7. Calling `getKnapSackItems` function: The function calls the `getKnapSackItems` function to find the sequence of items included in + the knapsack to achieve the maximum value. + + 8. `getKnapSackItems` function: This function takes in the `values` array and the `items` array as input and returns a slice containing + the indices of the items included in the knapsack. + + 9. Traversing back to find the items: Starting from the bottom-right cell of the `values` array, the function traverses back to find the + items included in the knapsack. It does this by comparing the value in the current cell `values[i][c]` with the value in the cell above + `values[i-1][c]`. If the values are the same, it means the current item was not included, so it moves to the previous row. Otherwise, + it means the current item was included, so it adds the index of the current item `(i-1)` to the `sequence` slice and updates the capacity `c` accordingly. + + 10. Reversing the `sequence`: The sequence of items is built in reverse order, so the function uses the `reverse` helper function to + reverse the order of elements in the `sequence` slice. + + 11. Returning the result: The function returns the maximum value and the sequence of items included in the knapsack as an interface slice. + + 12. Helper functions: The `max` function is a simple helper function that returns the maximum of two integers, and the `reverse` + function is used to reverse the order of elements in a slice. + + Time and Space complexity: + O(nc) time | O(nc) space - where n is the number of items and c is the capacity */ package main From eda04227b92cefb67d30db19d81555ff099895cd Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sat, 29 Jul 2023 16:47:35 +0530 Subject: [PATCH 1710/1894] Create Factorial.cpp --- Math/Factorial.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/Factorial.cpp diff --git a/Math/Factorial.cpp b/Math/Factorial.cpp new file mode 100644 index 00000000..ac6a0445 --- /dev/null +++ b/Math/Factorial.cpp @@ -0,0 +1,43 @@ +/* +Explanation: +- The `factorial` function takes an integer `num` as input and calculates its factorial. The factorial of a non-negative integer N is the product of all positive integers less than or equal to N. +- In the function, we have a base case that handles the special case when `num` is 0. The factorial of 0 is defined as 1, so we return 1 for `num` equal to 0. +- For non-zero `num`, we use recursion to calculate the factorial. We call the `factorial` function with `num - 1`, and then multiply the result by `num`. +- The recursion continues until we reach the base case when `num` becomes 0, and the recursive calls start to return their values and calculate the final factorial. + +Time Complexity: The time complexity of the `factorial` function is O(N), where N is the value of the input number. This is because the function makes N recursive calls to calculate the factorial. + +Space Complexity: The space complexity is O(N) due to the recursion stack space used during the recursive calls. Each recursive call adds a new stack frame, and in the worst case, there will be N stack frames corresponding to the N recursive calls. + +Sample Input: +Number: 5 + +Sample Output: +Factorial of 5 is 120 +*/ + +#include + +// Function to calculate factorial +unsigned long long factorial(int num) { + // Base case: factorial of 0 is 1 + if (num == 0) { + return 1; + } + + // Recursive case: calculate factorial using recursion + return num * factorial(num - 1); +} + +int main() { + // Sample input + int num = 5; + + // Calculate the factorial of the number + unsigned long long result = factorial(num); + + // Print the result + std::cout << "Factorial of " << num << " is " << result << std::endl; + + return 0; +} From 3a5f961167d8d67ddbae4461e807e8c78784f42b Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sat, 29 Jul 2023 16:48:28 +0530 Subject: [PATCH 1711/1894] Create Factorial.py --- Math/Factorial.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Math/Factorial.py diff --git a/Math/Factorial.py b/Math/Factorial.py new file mode 100644 index 00000000..b82e846e --- /dev/null +++ b/Math/Factorial.py @@ -0,0 +1,31 @@ +''' +Approach: +We will take the number as input from the user and calculate its factorial. +To calculate the factorial, we will start from 1 and multiply it with all the numbers from 1 to n. +Finally, we will return the factorial. + +Time Complexity: O(n) +Space Complexity: O(1) +''' + +# Initializing the factorial to 1 +fact = 1 +def factorial(num): + # If the number is 0 or 1, then the factorial is 1. + if num == 0 or num == 1: + return 1 + # Calculating factorial by multiplying every number from 1 to num + for i in range(1, num+1): + fact *= i + return fact + +#Taking input from user +num = int(input("Enter a number: ")) +#Calculating and printing the factorial of the number +print("Factorial of", num, "is", factorial(num)) + + +''' +Sample Input: 5 +Sample Output: Factorial of 5 is 120 +''' From 026eb0320008a3907859c8acff3ec0199087e9a6 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sat, 29 Jul 2023 16:50:59 +0530 Subject: [PATCH 1712/1894] Create Factorial.go --- Math/Factorial.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Math/Factorial.go diff --git a/Math/Factorial.go b/Math/Factorial.go new file mode 100644 index 00000000..a3617fce --- /dev/null +++ b/Math/Factorial.go @@ -0,0 +1,43 @@ +/* +Approach and Explanation: +The factorial of a non-negative integer `n` is given by the product of all positive integers less than or equal to `n`. The factorial function is typically implemented using recursion. In this implementation, we check the base case where the input `n` is less than or equal to 1, and in that case, we return 1. Otherwise, we recursively call the factorial function with `n-1` and multiply it with `n`. This process continues until the base case is reached. + +The code prompts the user to enter a number, reads the input, and then calls the `factorial` function to calculate the factorial of the entered number. The result is then printed on the console. + +Time and Space Complexity: +The time complexity of this implementation is O(n) because the recursive function is called once for each integer from `n` to 1. + +The space complexity is O(n) as well since each recursive call adds a new frame to the call stack. + +Sample Input and Output: +Enter a number: 5 +The factorial of 5 is: 120 +*/ + + +package main + +import ( + "fmt" +) + +// Function to calculate the factorial of a number +func factorial(n int) int { + if n <= 1 { + return 1 + } + return n * factorial(n-1) +} + +func main() { + // Getting user input + var number int + fmt.Print("Enter a number: ") + fmt.Scanln(&number) + + // Calculating and printing the factorial + result := factorial(number) + fmt.Printf("The factorial of %d is: %d\n", number, result) +} + + From a18a777d21b8af6d0ef787312fff2db16caf02f9 Mon Sep 17 00:00:00 2001 From: Avantika Chauhan <101965370+avantikachauhann@users.noreply.github.com> Date: Sat, 29 Jul 2023 23:54:26 +0530 Subject: [PATCH 1713/1894] Update Factorial.py --- Math/Factorial.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Math/Factorial.py b/Math/Factorial.py index b82e846e..7f1a64b3 100644 --- a/Math/Factorial.py +++ b/Math/Factorial.py @@ -6,6 +6,9 @@ Time Complexity: O(n) Space Complexity: O(1) + +Sample Input: 5 +Sample Output: Factorial of 5 is 120 ''' # Initializing the factorial to 1 @@ -25,7 +28,3 @@ def factorial(num): print("Factorial of", num, "is", factorial(num)) -''' -Sample Input: 5 -Sample Output: Factorial of 5 is 120 -''' From d973f1b511a78282988eb5c7718a480cecc11556 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Jul 2023 11:16:17 +0530 Subject: [PATCH 1714/1894] add disk stacking in go --- Dynamic Programming/disk_stacking.go | 66 ++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Dynamic Programming/disk_stacking.go diff --git a/Dynamic Programming/disk_stacking.go b/Dynamic Programming/disk_stacking.go new file mode 100644 index 00000000..5c7f06eb --- /dev/null +++ b/Dynamic Programming/disk_stacking.go @@ -0,0 +1,66 @@ +package main + +import "sort" +type Disk []int +type Disks []Disk + +func (disks Disks) Len() int { return len(disks) } +func (disks Disks) Swap(i, j int) { disks[i], disks[j] = disks[j], disks[i] } +func (disks Disks) Less(i, j int) bool { return disks[i][2] < disks[j][2]} + +func DiskStacking(input [][]int) [][]int { + disks := make(Disks, len(input)) + for i, disk := range input { + disks[i] = disk + } + + sort.Sort(disks) + heights := make([]int, len(disks)) + sequences := make([]int, len(disks)) + + for i := range disks { + heights[i] = disks[i][2] + sequences[i] = -1 + } + + for i := 1; i < len(disks); i++ { + currentDisk := disks[i] + for j := 0; j < i; j++ { + other := disks[j] + // conditions met + if areValidDimensions(other, currentDisk) { + if heights[i] <= currentDisk[2] + heights[j] { + heights[i] = currentDisk[2] + heights[j] + sequences[i] = j + } + } + } + } + maxIndex := 0 + for i, height := range heights { + if height > heights[maxIndex] { + maxIndex = i + } + } + sequence := buildSequence(disks, sequences, maxIndex) + return sequence +} + +func areValidDimensions(o Disk, c Disk) bool { + return o[0] < c[0] && o[1] < c[1] && o[2] < c[2] +} + +func buildSequence(disks []Disk, sequences []int, index int) [][]int { + sequence := [][]int{} + for index != -1 { + sequence = append(sequence, disks[index]) + index = sequences[index] + } + reverse(sequence) + return sequence +} +func reverse(numbers [][]int) { + for i, j := 0, len(numbers) - 1; i < j; i, j = i + 1, j - 1 { + numbers[i], numbers[j] = numbers[j], numbers[i] + } +} \ No newline at end of file From aa919b7fd957c3e30d7be685b6939a204dbbbd9c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Jul 2023 11:18:42 +0530 Subject: [PATCH 1715/1894] add question --- Dynamic Programming/disk_stacking.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Dynamic Programming/disk_stacking.go b/Dynamic Programming/disk_stacking.go index 5c7f06eb..550ea764 100644 --- a/Dynamic Programming/disk_stacking.go +++ b/Dynamic Programming/disk_stacking.go @@ -1,3 +1,16 @@ +/* + You're given a non-empty array of arrays where each subarray holds three integers and represents a disk. + These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the + disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, + and height than any other disk below it. + + Write a function that returns an array of the disks in the final stack, starting with the top disk and + ending with the bottom disk. Note that you can't rotate disks; in other words, the integers in each subarray must + represent [width, depth, height] at all times + + Sample input : = [[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]] + Output: [[2, 1, 2], [3, 2, 3], [4, 4, 5]] // 10 (2 + 3 + 5) is the tallest height we can get by +*/ package main import "sort" From 586479bf7da1685a06eefac5ecee26922dc295c0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Jul 2023 11:20:10 +0530 Subject: [PATCH 1716/1894] add explanation --- Dynamic Programming/disk_stacking.go | 66 ++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 9 deletions(-) diff --git a/Dynamic Programming/disk_stacking.go b/Dynamic Programming/disk_stacking.go index 550ea764..d306848c 100644 --- a/Dynamic Programming/disk_stacking.go +++ b/Dynamic Programming/disk_stacking.go @@ -1,15 +1,63 @@ /* - You're given a non-empty array of arrays where each subarray holds three integers and represents a disk. - These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the - disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, - and height than any other disk below it. + You're given a non-empty array of arrays where each subarray holds three integers and represents a disk. + These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the + disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, + and height than any other disk below it. - Write a function that returns an array of the disks in the final stack, starting with the top disk and - ending with the bottom disk. Note that you can't rotate disks; in other words, the integers in each subarray must - represent [width, depth, height] at all times + Write a function that returns an array of the disks in the final stack, starting with the top disk and + ending with the bottom disk. Note that you can't rotate disks; in other words, the integers in each subarray must + represent [width, depth, height] at all times - Sample input : = [[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]] - Output: [[2, 1, 2], [3, 2, 3], [4, 4, 5]] // 10 (2 + 3 + 5) is the tallest height we can get by + Sample input : = [[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]] + Output: [[2, 1, 2], [3, 2, 3], [4, 4, 5]] // 10 (2 + 3 + 5) is the tallest height we can get by + + Explanation: + This code snippet implements the "Disk Stacking" problem, which is a classic dynamic programming problem. The goal is to + find the maximum height that can be achieved by stacking disks on top of each other while adhering to certain conditions. + + The problem is defined as follows: + Given a list of disks represented by their dimensions (width, depth, height), you need to find a stack of disks with the + maximum height. You can only stack a disk on top of another if its width, depth, and height are all strictly smaller than + those of the disk below it. + + Now, let's go through the code step by step: + + 1. `Disk` and `Disks` types: These are custom types defined to simplify the code and make it more readable. `Disk` represents + a single disk's dimensions, and `Disks` is a slice of `Disk`, representing a collection of disks. + + 2. Implementing sort interface for `Disks`: The `Disks` type is provided with three methods - `Len`, `Swap`, and `Less`. + These methods are part of the `sort.Interface`, which allows us to sort the disks based on their height (the third dimension). + + 3. `DiskStacking` function: This is the main function that solves the disk stacking problem. It takes a 2D slice `input`, + representing the dimensions of the disks, and returns a 2D slice representing the sequence of disks to stack to achieve + the maximum height. + + 4. Creating `disks` slice and sorting: The function first converts the input to a `Disks` slice and then sorts it based on + the third dimension (height) in increasing order. Sorting will allow us to consider disks in a specific order while building + the stack. + + 5. Initializing `heights` and `sequences` slices: The function initializes two slices, `heights` and `sequences`, both with + the same length as the number of disks. `heights` will keep track of the maximum height achievable with the current disk at + each position, and `sequences` will store the index of the previous disk that contributes to the current disk's maximum height. + + 6. Dynamic programming loop: The function iterates over each disk and calculates the maximum height that can be achieved by + considering the current disk and all the disks before it. It checks if the conditions (`areValidDimensions`) for placing the + current disk on top of another are met, and if so, it updates the maximum height and the contributing disk index in `heights` + and `sequences`. + + 7. Finding the maximum height and the sequence: After the dynamic programming loop, it finds the index with the maximum + height in the `heights` slice. This index represents the topmost disk in the stack, which contributes to the maximum height. + + 8. Building the sequence: The function calls the `buildSequence` function to create the sequence of disks contributing to + the maximum height. It starts from the topmost disk (found in the previous step) and follows the sequence of disks using the + `sequences` slice. + + 9. Reversing the sequence: The sequence is built in reverse order, starting from the topmost disk. Since the problem requires + the disks to be stacked from bottom to top, the `reverse` function is used to reverse the order of elements in the sequence. + + 10. Returning the result: Finally, the function returns the sequence of disks that should be stacked to achieve the maximum height. + + O(n^2) time | O(n) space - where n is the number of disks */ package main From 780a8fa8025208a27aae0aeb73f0352014ee9563 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 30 Jul 2023 11:20:36 +0530 Subject: [PATCH 1717/1894] add comments in the code --- Dynamic Programming/disk_stacking.go | 35 ++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/Dynamic Programming/disk_stacking.go b/Dynamic Programming/disk_stacking.go index d306848c..1e9414cd 100644 --- a/Dynamic Programming/disk_stacking.go +++ b/Dynamic Programming/disk_stacking.go @@ -62,66 +62,87 @@ package main import "sort" + +// Custom type for representing a single disk's dimensions (width, depth, height) type Disk []int + +// Custom type for representing a collection of disks type Disks []Disk +// Implementing sort.Interface for Disks to allow sorting based on height (third dimension) func (disks Disks) Len() int { return len(disks) } func (disks Disks) Swap(i, j int) { disks[i], disks[j] = disks[j], disks[i] } -func (disks Disks) Less(i, j int) bool { return disks[i][2] < disks[j][2]} +func (disks Disks) Less(i, j int) bool { return disks[i][2] < disks[j][2] } +// Main function to solve the Disk Stacking problem func DiskStacking(input [][]int) [][]int { + // Convert input to Disks slice and sort it based on height in increasing order disks := make(Disks, len(input)) for i, disk := range input { disks[i] = disk } - sort.Sort(disks) + + // Initialize slices to store the maximum height and the sequence of disks heights := make([]int, len(disks)) sequences := make([]int, len(disks)) - for i := range disks { heights[i] = disks[i][2] sequences[i] = -1 } + // Dynamic programming loop to find the maximum height and contributing disks for i := 1; i < len(disks); i++ { currentDisk := disks[i] for j := 0; j < i; j++ { other := disks[j] - // conditions met + + // Check if conditions are met to stack currentDisk on top of other if areValidDimensions(other, currentDisk) { - if heights[i] <= currentDisk[2] + heights[j] { + // Update maximum height and contributing disk index if needed + if heights[i] <= currentDisk[2]+heights[j] { heights[i] = currentDisk[2] + heights[j] sequences[i] = j } } } } + + // Find the index with the maximum height (topmost disk in the stack) maxIndex := 0 for i, height := range heights { if height > heights[maxIndex] { maxIndex = i } } + + // Build the sequence of disks contributing to the maximum height sequence := buildSequence(disks, sequences, maxIndex) + + // Return the sequence of disks that should be stacked to achieve the maximum height return sequence } +// Function to check if the conditions are met for placing current disk on top of other func areValidDimensions(o Disk, c Disk) bool { return o[0] < c[0] && o[1] < c[1] && o[2] < c[2] } +// Function to build the sequence of disks contributing to the maximum height func buildSequence(disks []Disk, sequences []int, index int) [][]int { sequence := [][]int{} for index != -1 { sequence = append(sequence, disks[index]) index = sequences[index] } + // Since the sequence is built in reverse order (top to bottom), reverse it to get correct order reverse(sequence) return sequence } + +// Function to reverse the order of elements in a 2D slice func reverse(numbers [][]int) { - for i, j := 0, len(numbers) - 1; i < j; i, j = i + 1, j - 1 { + for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 { numbers[i], numbers[j] = numbers[j], numbers[i] } -} \ No newline at end of file +} From f62f46e968a4cf8b5189ef66ba5c344913d690fa Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 31 Jul 2023 22:32:18 +0530 Subject: [PATCH 1718/1894] add numbers in pi --- Dynamic Programming/numbers_in_pi.go | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Dynamic Programming/numbers_in_pi.go diff --git a/Dynamic Programming/numbers_in_pi.go b/Dynamic Programming/numbers_in_pi.go new file mode 100644 index 00000000..04024483 --- /dev/null +++ b/Dynamic Programming/numbers_in_pi.go @@ -0,0 +1,42 @@ +package main + +import ( + "math" +) +func NumbersInPi(pi string, numbers []string) int { + numbersTable := map[string]bool{} + for _, number := range numbers { + numbersTable[number] = true + } + minSpaces := getMinSpaces(pi, numbersTable, map[int]int{}, 0) + if minSpaces == math.MaxInt32 { + return -1 + } + return minSpaces +} + +func getMinSpaces(pi string, numbersTable map[string]bool, cache map[int]int, idx int) int { + if idx == len(pi) { + return -1 + } else if val, found := cache[idx]; found { + return val + } + minSpaces := math.MaxInt32 + for i := idx; i < len(pi); i++ { + prefix := pi[idx : i + 1] + if _, found := numbersTable[prefix]; found { + minSpacesInSuffix := getMinSpaces(pi, numbersTable, cache, i + 1) + minSpaces = min(minSpaces, minSpacesInSuffix + 1) + } + } + cache[idx] = minSpaces + return cache[idx] + +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} From 66bf3dddef27ebb9212fb0a73571808a94c8db26 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 31 Jul 2023 22:33:11 +0530 Subject: [PATCH 1719/1894] add explanation --- Dynamic Programming/numbers_in_pi.go | 31 ++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Dynamic Programming/numbers_in_pi.go b/Dynamic Programming/numbers_in_pi.go index 04024483..0d38ce89 100644 --- a/Dynamic Programming/numbers_in_pi.go +++ b/Dynamic Programming/numbers_in_pi.go @@ -1,3 +1,34 @@ +/* + The given code snippet is for solving the "Numbers in Pi" problem using a recursive approach with memoization (dynamic programming) to find the minimum number of spaces required to divide the given string representation of pi into valid numbers from a list of given numbers. + + The problem is as follows: Given a string representation of the irrational number pi and a list of numbers, find the minimum number of spaces required to divide the string into valid numbers such that each number is present in the given list. + + Let's go through the code step by step: + + 1. `NumbersInPi` function: + - This is the main function that takes the string representation of pi and a list of numbers as input and returns the minimum number of spaces required. It initializes a `numbersTable` to store the numbers from the input list for quick lookup and then calls the `getMinSpaces` function with initial parameters. + + 2. `getMinSpaces` function: + - This is a recursive function with memoization. It takes the string representation of pi, the `numbersTable`, a `cache` (a map to store previously calculated values to avoid redundant calculations), and the current `idx` (position in the pi string) as input. + - It first checks if the base case has been reached by comparing `idx` with the length of the pi string. If so, it returns -1. + - Next, it checks if the result for the current `idx` is already present in the cache. If yes, it returns the cached result. + - If the base case is not reached and the result is not in the cache, it initializes a variable `minSpaces` to store the minimum spaces required for the current `idx`. It sets `minSpaces` to a large value (initialized as `math.MaxInt32`) to ensure correct comparisons later. + - Then, it iterates from the current `idx` to the end of the pi string and forms a prefix string from `idx` to the current iteration index (`i`). + - If the prefix string is found in the `numbersTable`, it means it is a valid number from the given list. The function then recursively calls itself with the suffix (remaining part) of the pi string starting from index `i+1`. + - The result of the recursive call is stored in `minSpacesInSuffix`. + - The minimum of `minSpaces` and `minSpacesInSuffix + 1` is computed and assigned back to `minSpaces`. The "+1" indicates the current valid number prefix, which requires one space. + - The loop continues, trying all possible valid prefixes from the current index. + - Finally, the `minSpaces` value is stored in the `cache` to avoid redundant calculations and returned as the result for the current `idx`. + + 3. `min` function: + - A simple utility function to return the minimum of two integers. + + The `NumbersInPi` function is the entry point, and the `getMinSpaces` function handles the recursive computation with memoization. + By using memoization, the code optimizes and reduces redundant calculations, making it more efficient than a pure + recursive solution. The result returned by `NumbersInPi` is the minimum number of spaces required to divide the pi string + into valid numbers from the given list. If it is not possible to form valid numbers using the given list, + the function returns -1. +*/ package main import ( From 841a389458e25c67204696228d2794f2a62280f3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 31 Jul 2023 22:34:53 +0530 Subject: [PATCH 1720/1894] add question and sample io --- Dynamic Programming/numbers_in_pi.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Dynamic Programming/numbers_in_pi.go b/Dynamic Programming/numbers_in_pi.go index 0d38ce89..e37fc548 100644 --- a/Dynamic Programming/numbers_in_pi.go +++ b/Dynamic Programming/numbers_in_pi.go @@ -1,4 +1,16 @@ /* + + Given a string representation of the first n digits of Pi and a list of positive integers (all in string format), write a function that returns the + smallest number of spaces that can be added to the n digits of Pi such that all resulting numbers are found in the list of integers. + + Sample Input pi = "3141592653589793238462643383279" + numbers : ["314159265358979323846", "26433", "8", "3279", "314159265", "35897932384626433832", "79"] + + Output: 2 + + + Explanation: + The given code snippet is for solving the "Numbers in Pi" problem using a recursive approach with memoization (dynamic programming) to find the minimum number of spaces required to divide the given string representation of pi into valid numbers from a list of given numbers. The problem is as follows: Given a string representation of the irrational number pi and a list of numbers, find the minimum number of spaces required to divide the string into valid numbers such that each number is present in the given list. From f3278246b1a86032151de8ccf83d105888ce3ef7 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 31 Jul 2023 22:35:24 +0530 Subject: [PATCH 1721/1894] add comments --- Dynamic Programming/numbers_in_pi.go | 80 +++++++++++++++++----------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/Dynamic Programming/numbers_in_pi.go b/Dynamic Programming/numbers_in_pi.go index e37fc548..98ac432d 100644 --- a/Dynamic Programming/numbers_in_pi.go +++ b/Dynamic Programming/numbers_in_pi.go @@ -43,43 +43,61 @@ */ package main -import ( - "math" -) +import "math" + +// NumbersInPi finds the minimum number of spaces needed to divide the pi string +// into valid numbers from the given list of numbers. func NumbersInPi(pi string, numbers []string) int { numbersTable := map[string]bool{} - for _, number := range numbers { - numbersTable[number] = true - } - minSpaces := getMinSpaces(pi, numbersTable, map[int]int{}, 0) - if minSpaces == math.MaxInt32 { - return -1 - } - return minSpaces + for _, number := range numbers { + numbersTable[number] = true + } + + // Cache to store results of subproblems to avoid redundant calculations + cache := map[int]int{} + minSpaces := getMinSpaces(pi, numbersTable, cache, 0) + + if minSpaces == math.MaxInt32 { + return -1 + } + return minSpaces } +// getMinSpaces calculates the minimum number of spaces needed to divide the remaining +// suffix of the pi string into valid numbers from the numbersTable. func getMinSpaces(pi string, numbersTable map[string]bool, cache map[int]int, idx int) int { - if idx == len(pi) { - return -1 - } else if val, found := cache[idx]; found { - return val - } - minSpaces := math.MaxInt32 - for i := idx; i < len(pi); i++ { - prefix := pi[idx : i + 1] - if _, found := numbersTable[prefix]; found { - minSpacesInSuffix := getMinSpaces(pi, numbersTable, cache, i + 1) - minSpaces = min(minSpaces, minSpacesInSuffix + 1) - } - } - cache[idx] = minSpaces - return cache[idx] - + // Base case: If the end of the pi string is reached, return -1. + // This indicates that the suffix of the pi string cannot be divided into valid numbers. + if idx == len(pi) { + return -1 + } else if val, found := cache[idx]; found { + // If the result for the current index is already in the cache, return it. + return val + } + + minSpaces := math.MaxInt32 + // Iterate over possible prefixes starting from the current index. + for i := idx; i < len(pi); i++ { + prefix := pi[idx : i+1] + + // If the prefix is found in the numbersTable, it is a valid number prefix. + if _, found := numbersTable[prefix]; found { + // Recursively calculate the minimum number of spaces in the suffix. + minSpacesInSuffix := getMinSpaces(pi, numbersTable, cache, i+1) + // Update the minimum spaces with the current prefix if it leads to a valid number. + minSpaces = min(minSpaces, minSpacesInSuffix+1) + } + } + + // Cache the result for the current index to avoid redundant calculations. + cache[idx] = minSpaces + return cache[idx] } +// min returns the minimum of two integers. func min(a, b int) int { - if a < b { - return a - } - return b + if a < b { + return a + } + return b } From 95b13b69da0e8c26ba1c2ae396badb6777000925 Mon Sep 17 00:00:00 2001 From: ashmitha mohan Date: Tue, 1 Aug 2023 23:29:46 +0530 Subject: [PATCH 1722/1894] /Users/ashmithamohan/data-structures-and-algorithms/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp --- .../best_time_to_buy_and_sell_stock.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp index 147d4c5b..1bd13c62 100644 --- a/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp +++ b/Dynamic Programming/best_time_to_buy_and_sell_stock.cpp @@ -15,20 +15,17 @@ */ #include #include -#include // for INT_MIN +#include using namespace std; int maxProfit(vector& prices) { int minPrice = INT_MAX; // initialize to maximum value to start with - int maxProfit = 0; // initialize to 0 - - for (int i = 0; i < prices.size(); i++) { - if (prices[i] < minPrice) { - minPrice = prices[i]; // update minimum price seen so far - } else if (prices[i] - minPrice > maxProfit) { - maxProfit = prices[i] - minPrice; // update maximum profit seen so far - } + int maxProfit = 0;// initialize to 0 + + for (int price : prices) { + minPrice = min(minPrice, price); // update minimum price seen so far + maxProfit = max(maxProfit, price - minPrice); // update maximum profit seen so far } return maxProfit; @@ -42,3 +39,4 @@ int main() { return 0; } + From 806f25e79e2bf8a16ef94414d91bd64065921937 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 2 Aug 2023 22:54:50 +0530 Subject: [PATCH 1723/1894] add dice throws --- Dynamic Programming/dice_throws.go | 37 ++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic Programming/dice_throws.go diff --git a/Dynamic Programming/dice_throws.go b/Dynamic Programming/dice_throws.go new file mode 100644 index 00000000..f4ee49ba --- /dev/null +++ b/Dynamic Programming/dice_throws.go @@ -0,0 +1,37 @@ +package main + +func DiceThrows(numDice int, numSides int, target int) int { + storedResults := make([][]int, numDice + 1) + for i := range storedResults { + storedResults[i] = make([]int, target + 1) + for j := range storedResults[i] { + storedResults[i][j] = -1 + } + } + return diceThrowsHelper(numDice, numSides, target, storedResults) +} + +func diceThrowsHelper(numDice, numSides, target int, storedResults [][]int) int { + if numDice == 0 { + if target == 0 { + return 1 + } + return 0 + } + if storedResults[numDice][target] > -1 { + return storedResults[numDice][target] + } + numWaysToReachTarget := 0 + for currentTarget := max(0, target - numSides); currentTarget < target; currentTarget++ { + numWaysToReachTarget += diceThrowsHelper(numDice - 1, numSides, currentTarget, storedResults) + } + storedResults[numDice][target] = numWaysToReachTarget + return numWaysToReachTarget +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} From 8144822cae63f993bf444f7113ef3b03276b2a3c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 2 Aug 2023 22:55:15 +0530 Subject: [PATCH 1724/1894] add comments --- Dynamic Programming/dice_throws.go | 76 +++++++++++++++++++----------- 1 file changed, 49 insertions(+), 27 deletions(-) diff --git a/Dynamic Programming/dice_throws.go b/Dynamic Programming/dice_throws.go index f4ee49ba..0d53c8ab 100644 --- a/Dynamic Programming/dice_throws.go +++ b/Dynamic Programming/dice_throws.go @@ -1,37 +1,59 @@ package main +// DiceThrows calculates the number of ways to obtain a specific target sum +// by rolling a given number of dice with a certain number of sides. +// It calls the helper function diceThrowsHelper for recursive calculations. func DiceThrows(numDice int, numSides int, target int) int { - storedResults := make([][]int, numDice + 1) - for i := range storedResults { - storedResults[i] = make([]int, target + 1) - for j := range storedResults[i] { - storedResults[i][j] = -1 - } - } - return diceThrowsHelper(numDice, numSides, target, storedResults) + // Create a 2D slice to store intermediate results of recursive calls. + storedResults := make([][]int, numDice+1) + for i := range storedResults { + storedResults[i] = make([]int, target+1) + for j := range storedResults[i] { + // Initialize all values to -1 to indicate that they have not been computed yet. + storedResults[i][j] = -1 + } + } + // Call the helper function to perform the actual calculations. + return diceThrowsHelper(numDice, numSides, target, storedResults) } +// diceThrowsHelper is a recursive helper function that calculates the number +// of ways to reach the target sum using a specific number of dice. func diceThrowsHelper(numDice, numSides, target int, storedResults [][]int) int { - if numDice == 0 { - if target == 0 { - return 1 - } - return 0 - } - if storedResults[numDice][target] > -1 { - return storedResults[numDice][target] - } - numWaysToReachTarget := 0 - for currentTarget := max(0, target - numSides); currentTarget < target; currentTarget++ { - numWaysToReachTarget += diceThrowsHelper(numDice - 1, numSides, currentTarget, storedResults) - } - storedResults[numDice][target] = numWaysToReachTarget - return numWaysToReachTarget + // Base case: If there are no dice left, check if the target sum is also 0. + if numDice == 0 { + if target == 0 { + // Return 1 if the target sum is 0 (a valid way to reach the target sum using no dice). + return 1 + } + // Return 0 if the target sum is not 0 (no valid way to reach the target sum). + return 0 + } + + // Memoization: Check if the result is already computed and stored in storedResults. + if storedResults[numDice][target] > -1 { + // If the result is already stored, return it to avoid redundant calculations. + return storedResults[numDice][target] + } + + // Recursive calculation: Find the number of ways to reach the target sum using numDice dice. + numWaysToReachTarget := 0 + for currentTarget := max(0, target-numSides); currentTarget < target; currentTarget++ { + // Recursively calculate the number of ways to reach the currentTarget using numDice-1 dice. + numWaysToReachTarget += diceThrowsHelper(numDice-1, numSides, currentTarget, storedResults) + } + + // Store the result in storedResults for future use. + storedResults[numDice][target] = numWaysToReachTarget + + // Return the total number of ways to reach the target sum. + return numWaysToReachTarget } +// max is a helper function to find the maximum of two integers. func max(a, b int) int { - if a > b { - return a - } - return b + if a > b { + return a + } + return b } From 82cb382cceebddc75681aad90f7e9dc56c08f7e1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 2 Aug 2023 22:57:55 +0530 Subject: [PATCH 1725/1894] add explanation --- Dynamic Programming/dice_throws.go | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Dynamic Programming/dice_throws.go b/Dynamic Programming/dice_throws.go index 0d53c8ab..6516bf8a 100644 --- a/Dynamic Programming/dice_throws.go +++ b/Dynamic Programming/dice_throws.go @@ -1,3 +1,49 @@ +/* + + You're given a set of numDice dice, each with numSides sides, and a target integer, which represents a target sum to obtain when + rolling all of the dice and summing their values. Write a function that returns the total number of dice-roll permutations that sum + up to exactly that target value. All three input values will always be positive integers. Each of the dice has an equal probability + of landing on any number from 1 to numSides . Identical total dice rolls obtained from different individual dice rolls (for example, + [2, 3] vs [3, 2] ) count as different dice-roll permutations. If there's no possible dice-roll combination that sums up to the target + given the input dice, your function should return 0. + + + + + + Explanation: + + The provided code is a Go implementation of a function called `DiceThrows`, which calculates the number of possible ways to obtain a specific target sum by rolling a given number of dice with a certain number of sides. + + Let's walk through the code: + + 1. `DiceThrows` function: This is the main function that initiates the process of calculating the number of ways to reach the target sum. + + - `numDice`: The number of dice available. + - `numSides`: The number of sides on each die. + - `target`: The target sum to achieve. + + 2. `storedResults`: This is a 2D slice used to store the intermediate results of the recursive calls to avoid redundant calculations. It stores the number of ways to reach the target sum for a specific number of dice and target. + + 3. `diceThrowsHelper` function: This is a helper function that performs the recursive calculations to find the number of ways to reach the target sum. + + - `numDice`, `numSides`, and `target`: The same variables as in the main function. + - `storedResults`: The 2D slice to store the intermediate results. + + 4. Base case: The function checks if `numDice` is 0. If so, it means there are no dice left, and it checks if the `target` is also 0. If yes, it returns 1 (a valid way to reach the target sum using no dice). Otherwise, it returns 0 (no valid way to reach the target sum). + + 5. Memoization: Before starting the actual calculations, the function checks if the result for the current number of dice and target sum is already calculated and stored in `storedResults`. If so, it directly returns the stored value, avoiding redundant calculations. + + 6. Recursive calculation: If the result is not stored, the function proceeds to calculate the number of ways to reach the target sum using the current number of dice. + + - It iterates over all the possible target sums for the current number of dice (`numDice`) based on the possible outcomes from rolling one die (`max(0, target-numSides)` to `target-1`). + - For each possible target sum (`currentTarget`), it makes a recursive call to `diceThrowsHelper` with `numDice-1` dice, `numSides` sides, and `currentTarget` as the new target sum. + - It adds up the number of ways to reach `currentTarget` using `numDice-1` dice. + + 7. Storing and returning the result: After calculating the total number of ways to reach the target sum, it stores the result in `storedResults` for future use and returns the result. + + 8. `max` function: A helper function to find the maximum of two integers. +*/ package main // DiceThrows calculates the number of ways to obtain a specific target sum From d54f6f1e081ca577695fce4af4ce591e3d0d95b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 2 Aug 2023 22:59:07 +0530 Subject: [PATCH 1726/1894] add sample io --- Dynamic Programming/dice_throws.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Dynamic Programming/dice_throws.go b/Dynamic Programming/dice_throws.go index 6516bf8a..d5886cc0 100644 --- a/Dynamic Programming/dice_throws.go +++ b/Dynamic Programming/dice_throws.go @@ -7,9 +7,8 @@ [2, 3] vs [3, 2] ) count as different dice-roll permutations. If there's no possible dice-roll combination that sums up to the target given the input dice, your function should return 0. - - - + Sample Input : numDice = 2 numSides = 6 target = 7 + Output: 6 [1, 6], [2, 5], [3, 4], [4, 3], [5, 2], [6, 1] Explanation: From 9a0bd9fed23c502911821971fa8b56b37f6e90af Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 3 Aug 2023 23:02:01 +0530 Subject: [PATCH 1727/1894] rename file --- Backtracking/{N-queens.java => n_queens.java} | 0 ...orithm.js => Graphs_kruskals_algorithm.js} | 0 ...entation.cpp => graphs_adjacency_list.cpp} | 84 +++++++++---------- ....cpp => graphs_adjacency_list_generic.cpp} | 78 ++++++++--------- 4 files changed, 81 insertions(+), 81 deletions(-) rename Backtracking/{N-queens.java => n_queens.java} (100%) rename Graphs/{Graphs_kruskalsAlgorithm.js => Graphs_kruskals_algorithm.js} (100%) rename Graphs/{Graphs_adjacency_list_implementation.cpp => graphs_adjacency_list.cpp} (96%) rename Graphs/{Graphs_adjacency_list_implementation_generic.cpp => graphs_adjacency_list_generic.cpp} (96%) diff --git a/Backtracking/N-queens.java b/Backtracking/n_queens.java similarity index 100% rename from Backtracking/N-queens.java rename to Backtracking/n_queens.java diff --git a/Graphs/Graphs_kruskalsAlgorithm.js b/Graphs/Graphs_kruskals_algorithm.js similarity index 100% rename from Graphs/Graphs_kruskalsAlgorithm.js rename to Graphs/Graphs_kruskals_algorithm.js diff --git a/Graphs/Graphs_adjacency_list_implementation.cpp b/Graphs/graphs_adjacency_list.cpp similarity index 96% rename from Graphs/Graphs_adjacency_list_implementation.cpp rename to Graphs/graphs_adjacency_list.cpp index 2fefe15c..216b5f4f 100644 --- a/Graphs/Graphs_adjacency_list_implementation.cpp +++ b/Graphs/graphs_adjacency_list.cpp @@ -1,43 +1,43 @@ -// Graphs Adjacency List implementation -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; - -class Graph{ -public: - int V; - list *L; // a pointer to an array of linkedlist - Graph(int v){ - V = v; - L = new list[V]; // Array of LL - // there is a pointer to an array whose size is v and every object is list of integer - } - void addEdge(int u, int v, bool bidir = true){ - L[u].push_back(v); - if(bidir){ - L[v].push_back(u); - } - } - void printAdjacencyList(){ - for(int i = 0; i < V; i++){ - cout << i << "-> "; - for(auto vertex : L[i]){ - cout << vertex << ", "; - } - cout << endl; - } - } -}; -int main(){ - //graph has 5 vertices numbered from 0-4 - Graph g(5); - g.addEdge(0, 1); - g.addEdge(0, 4); - g.addEdge(1, 4); - g.addEdge(1, 3); - g.addEdge(1, 2); - g.addEdge(2, 3); - g.addEdge(4, 3); - g.printAdjacencyList(); - return 0; +// Graphs Adjacency List implementation +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; + +class Graph{ +public: + int V; + list *L; // a pointer to an array of linkedlist + Graph(int v){ + V = v; + L = new list[V]; // Array of LL + // there is a pointer to an array whose size is v and every object is list of integer + } + void addEdge(int u, int v, bool bidir = true){ + L[u].push_back(v); + if(bidir){ + L[v].push_back(u); + } + } + void printAdjacencyList(){ + for(int i = 0; i < V; i++){ + cout << i << "-> "; + for(auto vertex : L[i]){ + cout << vertex << ", "; + } + cout << endl; + } + } +}; +int main(){ + //graph has 5 vertices numbered from 0-4 + Graph g(5); + g.addEdge(0, 1); + g.addEdge(0, 4); + g.addEdge(1, 4); + g.addEdge(1, 3); + g.addEdge(1, 2); + g.addEdge(2, 3); + g.addEdge(4, 3); + g.printAdjacencyList(); + return 0; } \ No newline at end of file diff --git a/Graphs/Graphs_adjacency_list_implementation_generic.cpp b/Graphs/graphs_adjacency_list_generic.cpp similarity index 96% rename from Graphs/Graphs_adjacency_list_implementation_generic.cpp rename to Graphs/graphs_adjacency_list_generic.cpp index 1ba71bfe..2dd0efd2 100644 --- a/Graphs/Graphs_adjacency_list_implementation_generic.cpp +++ b/Graphs/graphs_adjacency_list_generic.cpp @@ -1,40 +1,40 @@ -// Graphs Adjacency List implementation for Generic Data -// Program Author : Abhisek Kumar Gupta -#include -using namespace std; - -template -class Graph{ - map > adjList; - public: - Graph(){ - - } - void addEdge(T u, T v, bool bidir = true){ - adjList[u].push_back(v); - if(bidir){ - adjList[v].push_back(u); - } - } - void printAdjList(){ - for(auto obj : adjList){ - cout << obj.first << "->"; - for(auto element : obj.second){ - cout << element << ","; - } - cout << endl; - } - } -}; -int main(){ - Graph g; - g.addEdge("Ashish", "Asif", false); - g.addEdge("Ashish", "Abhisek", false); - g.addEdge("Ashish", "Amir", false); - g.addEdge("Abhisek", "Asif", true); - g.addEdge("Abhisek", "Anvesh", true); - g.addEdge("Anvesh", "Sai", false); - g.addEdge("Sai", "Abhisek", false); - g.printAdjList(); - return 0; +// Graphs Adjacency List implementation for Generic Data +// Program Author : Abhisek Kumar Gupta +#include +using namespace std; + +template +class Graph{ + map > adjList; + public: + Graph(){ + + } + void addEdge(T u, T v, bool bidir = true){ + adjList[u].push_back(v); + if(bidir){ + adjList[v].push_back(u); + } + } + void printAdjList(){ + for(auto obj : adjList){ + cout << obj.first << "->"; + for(auto element : obj.second){ + cout << element << ","; + } + cout << endl; + } + } +}; +int main(){ + Graph g; + g.addEdge("Ashish", "Asif", false); + g.addEdge("Ashish", "Abhisek", false); + g.addEdge("Ashish", "Amir", false); + g.addEdge("Abhisek", "Asif", true); + g.addEdge("Abhisek", "Anvesh", true); + g.addEdge("Anvesh", "Sai", false); + g.addEdge("Sai", "Abhisek", false); + g.printAdjList(); + return 0; } \ No newline at end of file From f7085e5ff8e39b9479a98f4eebcbbd9cab1bcdca Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 4 Aug 2023 22:42:44 +0530 Subject: [PATCH 1728/1894] add disk stacking in python --- Dynamic Programming/disk_stacking.py | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Dynamic Programming/disk_stacking.py diff --git a/Dynamic Programming/disk_stacking.py b/Dynamic Programming/disk_stacking.py new file mode 100644 index 00000000..27331e3d --- /dev/null +++ b/Dynamic Programming/disk_stacking.py @@ -0,0 +1,39 @@ +def DiskStacking(disks): + # Sort the disks based on their height + disks.sort(key=lambda x: x[2]) + + # Initialize arrays to store heights and sequences + heights = [disk[2] for disk in disks] # Heights of each disk + sequences = [-1 for _ in disks] # Index sequence for each disk + + # Loop through each disk and calculate the maximum height + for i in range(1, len(disks)): + current_disk = disks[i] + for j in range(i): + other_disk = disks[j] + # Check if the dimensions of the other_disk are valid for stacking + if are_valid_dimensions(other_disk, current_disk): + # Update the height and sequence if the condition is met + if heights[i] <= current_disk[2] + heights[j]: + heights[i] = current_disk[2] + heights[j] + sequences[i] = j + + # Find the index of the maximum height + max_index = heights.index(max(heights)) + + # Build and return the sequence of disks for the maximum height + sequence = build_sequence(disks, sequences, max_index) + return sequence + +def are_valid_dimensions(other_disk, current_disk): + # Check if the dimensions of other_disk allow current_disk to be stacked on top + return other_disk[0] < current_disk[0] and other_disk[1] < current_disk[1] and other_disk[2] < current_disk[2] + +def build_sequence(disks, sequences, index): + sequence = [] + # Build the sequence of disks for the maximum height + while index != -1: + sequence.append(disks[index]) + index = sequences[index] + sequence.reverse() # Reverse the sequence to maintain the correct order + return sequence From 3860f92e7523a30c074b9215858256f10ac86ac6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 4 Aug 2023 22:43:16 +0530 Subject: [PATCH 1729/1894] add question and explanation --- Dynamic Programming/disk_stacking.py | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/Dynamic Programming/disk_stacking.py b/Dynamic Programming/disk_stacking.py index 27331e3d..b6523abc 100644 --- a/Dynamic Programming/disk_stacking.py +++ b/Dynamic Programming/disk_stacking.py @@ -1,3 +1,64 @@ +''' + You're given a non-empty array of arrays where each subarray holds three integers and represents a disk. + These integers denote each disk's width, depth, and height, respectively. Your goal is to stack up the + disks and to maximize the total height of the stack. A disk must have a strictly smaller width, depth, + and height than any other disk below it. + + Write a function that returns an array of the disks in the final stack, starting with the top disk and + ending with the bottom disk. Note that you can't rotate disks; in other words, the integers in each subarray must + represent [width, depth, height] at all times + + Sample input : = [[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]] + Output: [[2, 1, 2], [3, 2, 3], [4, 4, 5]] // 10 (2 + 3 + 5) is the tallest height we can get by + + Explanation: + This code snippet implements the "Disk Stacking" problem, which is a classic dynamic programming problem. The goal is to + find the maximum height that can be achieved by stacking disks on top of each other while adhering to certain conditions. + + The problem is defined as follows: + Given a list of disks represented by their dimensions (width, depth, height), you need to find a stack of disks with the + maximum height. You can only stack a disk on top of another if its width, depth, and height are all strictly smaller than + those of the disk below it. + + Now, let's go through the code step by step: + + 1. `Disk` and `Disks` types: These are custom types defined to simplify the code and make it more readable. `Disk` represents + a single disk's dimensions, and `Disks` is a slice of `Disk`, representing a collection of disks. + + 2. Implementing sort interface for `Disks`: The `Disks` type is provided with three methods - `Len`, `Swap`, and `Less`. + These methods are part of the `sort.Interface`, which allows us to sort the disks based on their height (the third dimension). + + 3. `DiskStacking` function: This is the main function that solves the disk stacking problem. It takes a 2D slice `input`, + representing the dimensions of the disks, and returns a 2D slice representing the sequence of disks to stack to achieve + the maximum height. + + 4. Creating `disks` slice and sorting: The function first converts the input to a `Disks` slice and then sorts it based on + the third dimension (height) in increasing order. Sorting will allow us to consider disks in a specific order while building + the stack. + + 5. Initializing `heights` and `sequences` slices: The function initializes two slices, `heights` and `sequences`, both with + the same length as the number of disks. `heights` will keep track of the maximum height achievable with the current disk at + each position, and `sequences` will store the index of the previous disk that contributes to the current disk's maximum height. + + 6. Dynamic programming loop: The function iterates over each disk and calculates the maximum height that can be achieved by + considering the current disk and all the disks before it. It checks if the conditions (`areValidDimensions`) for placing the + current disk on top of another are met, and if so, it updates the maximum height and the contributing disk index in `heights` + and `sequences`. + + 7. Finding the maximum height and the sequence: After the dynamic programming loop, it finds the index with the maximum + height in the `heights` slice. This index represents the topmost disk in the stack, which contributes to the maximum height. + + 8. Building the sequence: The function calls the `buildSequence` function to create the sequence of disks contributing to + the maximum height. It starts from the topmost disk (found in the previous step) and follows the sequence of disks using the + `sequences` slice. + + 9. Reversing the sequence: The sequence is built in reverse order, starting from the topmost disk. Since the problem requires + the disks to be stacked from bottom to top, the `reverse` function is used to reverse the order of elements in the sequence. + + 10. Returning the result: Finally, the function returns the sequence of disks that should be stacked to achieve the maximum height. + + O(n^2) time | O(n) space - where n is the number of disks +''' def DiskStacking(disks): # Sort the disks based on their height disks.sort(key=lambda x: x[2]) From 5d5632e59f03d9fe68aec039addc78d958ede18f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 5 Aug 2023 12:24:51 +0530 Subject: [PATCH 1730/1894] add juice bottling --- Dynamic Programming/juice_bottling.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Dynamic Programming/juice_bottling.go diff --git a/Dynamic Programming/juice_bottling.go b/Dynamic Programming/juice_bottling.go new file mode 100644 index 00000000..32b0d00e --- /dev/null +++ b/Dynamic Programming/juice_bottling.go @@ -0,0 +1,25 @@ +package main + +func JuiceBottling(prices []int) []int { + numSizes := len(prices) + maxProfit := make([]int, numSizes) + dividingPoints := make([]int, numSizes) + + for size := 0; size < numSizes; size++ { + for dividingPoint := 0; dividingPoint < size+1; dividingPoint++ { + possibleProfit := maxProfit[size-dividingPoint] + prices[dividingPoint] + + if possibleProfit > maxProfit[size] { + maxProfit[size] = possibleProfit + dividingPoints[size] = dividingPoint + } + } + } + solution := []int{} + currentDividingPoint := numSizes - 1 + for currentDividingPoint > 0 { + solution = append(solution, dividingPoints[currentDividingPoint]) + currentDividingPoint -= dividingPoints[currentDividingPoint] + } + return solution +} From 4bd4e217bdd860c79bc39c0159d4a76612d896a9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 5 Aug 2023 12:25:16 +0530 Subject: [PATCH 1731/1894] add comments --- Dynamic Programming/juice_bottling.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Dynamic Programming/juice_bottling.go b/Dynamic Programming/juice_bottling.go index 32b0d00e..30f14b5f 100644 --- a/Dynamic Programming/juice_bottling.go +++ b/Dynamic Programming/juice_bottling.go @@ -2,21 +2,29 @@ package main func JuiceBottling(prices []int) []int { numSizes := len(prices) - maxProfit := make([]int, numSizes) - dividingPoints := make([]int, numSizes) + maxProfit := make([]int, numSizes) // Array to store the maximum profit for each bottle size + dividingPoints := make([]int, numSizes) // Array to store the dividing points that maximize profit + // Loop through each bottle size for size := 0; size < numSizes; size++ { + // Loop through possible dividing points for the current size for dividingPoint := 0; dividingPoint < size+1; dividingPoint++ { + // Calculate the possible profit by combining the previous maximum profit + // with the price at the current dividing point possibleProfit := maxProfit[size-dividingPoint] + prices[dividingPoint] + // Update maxProfit and dividingPoints if the new possible profit is greater if possibleProfit > maxProfit[size] { maxProfit[size] = possibleProfit dividingPoints[size] = dividingPoint } } } + solution := []int{} currentDividingPoint := numSizes - 1 + // Reconstruct the solution by tracing back from the end + // using the dividing points information for currentDividingPoint > 0 { solution = append(solution, dividingPoints[currentDividingPoint]) currentDividingPoint -= dividingPoints[currentDividingPoint] From daa09a5204d816710004fcef737496ded921ab7f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 5 Aug 2023 12:27:22 +0530 Subject: [PATCH 1732/1894] add explanation --- Dynamic Programming/juice_bottling.go | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Dynamic Programming/juice_bottling.go b/Dynamic Programming/juice_bottling.go index 30f14b5f..d8426376 100644 --- a/Dynamic Programming/juice_bottling.go +++ b/Dynamic Programming/juice_bottling.go @@ -1,3 +1,31 @@ +/* + + +Explanation: + +1. The function `JuiceBottling` takes an array `prices` as input, where `prices[i]` represents the price of a juice bottle of size `i`. + +2. It initializes two arrays, `maxProfit` and `dividingPoints`, both of size `numSizes` (the number of bottle sizes). +These arrays will be used to store information about maximum profit and dividing points. + +3. The outer loop iterates through each possible bottle size, from 0 to `numSizes - 1`. + +4. The inner loop iterates through possible dividing points for the current bottle size. For each combination of bottle size +and dividing point, it calculates the possible profit by adding the maximum profit from the previous bottle sizes and the +price of the bottle at the current dividing point. + +5. If the calculated possible profit is greater than the current maximum profit for the bottle size, it updates both `maxProfit` +and `dividingPoints` arrays. + +6. After completing the loops, the function reconstructs the solution by backtracking from the last bottle size to the first. +It appends the recorded dividing points to the `solution` array, which represents the optimal way to divide the bottles. + +7. The function returns the `solution` array, which contains the indices of the dividing points that maximize profit. + +In summary, the code uses dynamic programming to determine the optimal division of juice bottles to maximize profit. +It calculates the maximum profit for each bottle size and keeps track of the dividing points that lead to the maximum profit. +The solution is then reconstructed by backtracking from the end using the recorded dividing points. +*/ package main func JuiceBottling(prices []int) []int { From b1336b0ba76851d4579ae2bb922b63bca0ad0bd7 Mon Sep 17 00:00:00 2001 From: Anand Date: Sun, 6 Aug 2023 19:04:02 +0530 Subject: [PATCH 1733/1894] Add ReverseRightTrianglePattern in java Update Pattern Repo with java pattern code --- Patterns/ReverseRightTrianglePattern.java | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Patterns/ReverseRightTrianglePattern.java diff --git a/Patterns/ReverseRightTrianglePattern.java b/Patterns/ReverseRightTrianglePattern.java new file mode 100644 index 00000000..5b63df1d --- /dev/null +++ b/Patterns/ReverseRightTrianglePattern.java @@ -0,0 +1,34 @@ +/* + Reverse Right Triangular Pattern + Approach: + 1) Identify the numbers of rows for the outer for loop + 2) Identify the relation of column with respect to row. + In this case col = size-row+1 + 3) for each loop , print the respective element. + + TIME COMPLEXITY: O(N^2) + SPACE COMPLEXITY: O(1) + Eg: For size = 5, + OUTPUT: + * * * * * + * * * * + * * * + * * + * + */ +public class ReverseRightTrianglePattern { + + public static void main(String[] args) { + int size = 5; + pattern(size); + } + + public static void pattern(int size) { + for(int row=1;row<=size;row++) { + for(int col=1;col<=size-row+1;col++) { + System.out.print("* "); + } + System.out.println(); + } + } +} \ No newline at end of file From 949df71cd2360bac2bb33ea06c028bdd9309f440 Mon Sep 17 00:00:00 2001 From: Anand Date: Mon, 7 Aug 2023 17:09:56 +0530 Subject: [PATCH 1734/1894] Add RightPascalTrianglePattern in java Update Patterns repo with Java RightPascalTriangle --- Patterns/RightPascalTriangle.java | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Patterns/RightPascalTriangle.java diff --git a/Patterns/RightPascalTriangle.java b/Patterns/RightPascalTriangle.java new file mode 100644 index 00000000..06c02079 --- /dev/null +++ b/Patterns/RightPascalTriangle.java @@ -0,0 +1,38 @@ +/* + Right Pascal Triangle pattern in java + Approach: + 1) Identify the numbers of rows for the outer for loop + 2) Identify the relation of column with respect to row. + In this case col = size-row+1 + 3) for each loop , print the respective element. + + TIME COMPLEXITY: O(N^2) + SPACE COMPLEXITY: O(1) + Eg: For size = 5, + OUTPUT: + * + * * + * * * + * * * * + * * * + * * + * + */ +public class RightPascalTriangle { + + public static void main(String[] args) { + int size = 4; + pattern(size); + } + + public static void pattern(int size) { + for(int row=0;row< 2*size-1;row++){ + int totalcol = row < size?row:2*size-row-2; + for(int col =0;col <=totalcol;col++){ + System.out.print("* "); + } + System.out.println(); + } + } +} + From 5aabd75e7e519441c0f27f9b0777c2a545962728 Mon Sep 17 00:00:00 2001 From: Anand Date: Tue, 8 Aug 2023 17:00:30 +0530 Subject: [PATCH 1735/1894] Add StarDiamond Pattern in java Update Patterns repo with StarDiamond --- Patterns/StarDiamond.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Patterns/StarDiamond.java diff --git a/Patterns/StarDiamond.java b/Patterns/StarDiamond.java new file mode 100644 index 00000000..487b8252 --- /dev/null +++ b/Patterns/StarDiamond.java @@ -0,0 +1,38 @@ +/* + DIAMOND PATTERN + * + * * + * * * + * * * * + * * * + * * + * + + APPROACH: + 1) Identify the numbers of rows for the outer for loop + 2) Identify the relation of column with respect to row. + 3) for each loop , print the respective element. + */ +public class StarDiamond { + + public static void main(String[] args) { + int size = 5; + pattern(size); + } + + public static void pattern(int size) { + for (int row=1;row< 2*size;row++) { + int totalcolsinrow = row <= size ? row:2*size-row; + int spaces = size-totalcolsinrow; + + for(int i =1;i<=spaces;i++) { + System.out.print(" "); + } + for(int col =1;col<=totalcolsinrow;col++) { + System.out.print("* "); + } + System.out.println(); + } + } +} + From a1b3116cc2a4f81427ff6efa98cd7ced8dde4433 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Tue, 8 Aug 2023 18:11:50 +0530 Subject: [PATCH 1736/1894] Create Intersection_LL.cpp --- Linked List/Intersection_LL.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Linked List/Intersection_LL.cpp diff --git a/Linked List/Intersection_LL.cpp b/Linked List/Intersection_LL.cpp new file mode 100644 index 00000000..708f0541 --- /dev/null +++ b/Linked List/Intersection_LL.cpp @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode *pA = headA; + ListNode *pB = headB; + + // Traverse both linked lists until they meet or reach the end (NULL) + while (pA != pB) { + // Move pointers to the next node + pA = (pA != nullptr) ? pA->next : headB; + pB = (pB != nullptr) ? pB->next : headA; + } + + // Return the intersection node (or NULL if no intersection) + return pA; + } +}; + +/* +Explanation: +The provided code implements the solution to find the intersection point of two singly-linked lists headA and headB. The getIntersectionNode function takes two ListNode pointers as parameters and returns the intersection node if one exists, or NULL if there is no intersection. + +The approach used here is based on the concept of "runner pointers." The pointers pA and pB start from the heads of the two linked lists and traverse through the lists. When a pointer reaches the end of its list, it is redirected to the head of the other list. This ensures that the pointers will meet at the intersection point if it exists, or they will both reach the end of the lists (NULL) simultaneously if there is no intersection. + */ From bebe048f0a087cb6399bd2db97f6406ab10fb9d9 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 10 Aug 2023 22:27:21 +0530 Subject: [PATCH 1737/1894] move to arrays --- Arrays/non-overlapping intervals.cpp | 50 ++++++++++++++++++++++++++++ Math/factorial.py | 10 ++---- non-overlapping intervals.cpp | 50 ---------------------------- 3 files changed, 52 insertions(+), 58 deletions(-) create mode 100644 Arrays/non-overlapping intervals.cpp delete mode 100644 non-overlapping intervals.cpp diff --git a/Arrays/non-overlapping intervals.cpp b/Arrays/non-overlapping intervals.cpp new file mode 100644 index 00000000..b17b8d88 --- /dev/null +++ b/Arrays/non-overlapping intervals.cpp @@ -0,0 +1,50 @@ +// Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. +// Example 1: + +// Input: intervals = [[1,2],[2,3],[3,4],[1,3]] +// Output: 1 +// Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. +// Example 2: + +// Input: intervals = [[1,2],[1,2],[1,2]] +// Output: 2 +// Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. +// Example 3: + +// Input: intervals = [[1,2],[2,3]] +// Output: 0 +// Explanation: You don't need to remove any of the intervals since they're already non-overlapping. + + +// Constraints: +// 1 <= intervals.length <= 105 +// intervals[i].length == 2 +// -5 * 104 <= starti < endi <= 5 * 104 + +// CODE: + + class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + sort(intervals.begin(),intervals.end()); + int previous = 0; + int n = intervals.size(); + int ans = 0; + for(int current = 1;current>& intervals) { - sort(intervals.begin(),intervals.end()); - int previous = 0; - int n = intervals.size(); - int ans = 0; - for(int current = 1;current Date: Sat, 12 Aug 2023 18:56:08 +0530 Subject: [PATCH 1738/1894] Add CompleteSquare pattern in java Update Pattern repo with normal square pattern --- Patterns/CompleteSquare.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Patterns/CompleteSquare.java diff --git a/Patterns/CompleteSquare.java b/Patterns/CompleteSquare.java new file mode 100644 index 00000000..9bae7b0f --- /dev/null +++ b/Patterns/CompleteSquare.java @@ -0,0 +1,27 @@ +/* + pattern to print: +for input:5 + * * * * * + * * * * * + * * * * * + * * * * * + * * * * * + + APPROACH: + 1) Identify the numbers of rows for the outer for loop + 2) Identify the relation of column with respect to row. + 3) for each loop , print the respective element. + */ +public class CompleteSquare { + + public static void main(String[] args) { + int size = 5; + for(int row=1;row <= size;row++) { + for (int col = 1;col<=size;col++) { + System.out.print("* "); + } + System.out.println(); + } + } +} + From 4d745e9e9a1e1a605102d0defa0156cfa08602cd Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 12 Aug 2023 23:05:19 +0530 Subject: [PATCH 1739/1894] Create Partition.java --- Hash Table/Partition.java | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Hash Table/Partition.java diff --git a/Hash Table/Partition.java b/Hash Table/Partition.java new file mode 100644 index 00000000..d042442a --- /dev/null +++ b/Hash Table/Partition.java @@ -0,0 +1,46 @@ +import java.util.ArrayList; +import java.util.List; + +public class PalindromePartitioning { + public static List> partition(String s) { + List> result = new ArrayList<>(); + List current = new ArrayList<>(); + backtrack(result, current, s, 0); + return result; + } + + private static void backtrack(List> result, List current, String s, int start) { + if (start == s.length()) { + result.add(new ArrayList<>(current)); + return; + } + + for (int end = start; end < s.length(); end++) { + if (isPalindrome(s, start, end)) { + current.add(s.substring(start, end + 1)); + backtrack(result, current, s, end + 1); + current.remove(current.size() - 1); + } + } + } + + private static boolean isPalindrome(String s, int start, int end) { + while (start < end) { + if (s.charAt(start) != s.charAt(end)) { + return false; + } + start++; + end--; + } + return true; + } + + public static void main(String[] args) { + String input = "aab"; + List> partitions = partition(input); + + for (List partition : partitions) { + System.out.println(partition); + } + } +} From f39012dbb1e941a3a78689cf3fc884056b9db554 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Tue, 15 Aug 2023 09:15:54 +0530 Subject: [PATCH 1740/1894] Create A*.js --- Graphs/A*.js | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Graphs/A*.js diff --git a/Graphs/A*.js b/Graphs/A*.js new file mode 100644 index 00000000..91f7e499 --- /dev/null +++ b/Graphs/A*.js @@ -0,0 +1,98 @@ +class Node { + constructor(x, y) { + this.x = x; + this.y = y; + this.g = 0; // Cost from start node to this node + this.h = 0; // Heuristic cost from this node to target node + this.f = 0; // Total cost (g + h) + this.parent = null; // Parent node in the path + } +} + +function euclideanDistance(node1, node2) { + const dx = node2.x - node1.x; + const dy = node2.y - node1.y; + return Math.sqrt(dx * dx + dy * dy); +} + +function aStar(start, target, grid) { + const openList = [start]; + const closedList = []; + + while (openList.length > 0) { + let currentNode = openList[0]; + let currentIndex = 0; + + for (let i = 1; i < openList.length; i++) { + if (openList[i].f < currentNode.f) { + currentNode = openList[i]; + currentIndex = i; + } + } + + openList.splice(currentIndex, 1); + closedList.push(currentNode); + + if (currentNode === target) { + const path = []; + let current = currentNode; + while (current !== null) { + path.unshift(current); + current = current.parent; + } + return path; + } + + const neighbors = getNeighbors(currentNode, grid); + for (let neighbor of neighbors) { + if (closedList.some(node => node === neighbor)) { + continue; + } + + const tentativeG = currentNode.g + euclideanDistance(currentNode, neighbor); + let newPath = false; + + if (!openList.some(node => node === neighbor)) { + openList.push(neighbor); + newPath = true; + } else if (tentativeG < neighbor.g) { + newPath = true; + } + + if (newPath) { + neighbor.parent = currentNode; + neighbor.g = tentativeG; + neighbor.h = euclideanDistance(neighbor, target); + neighbor.f = neighbor.g + neighbor.h; + } + } + } + + return []; // No path found +} + +function getNeighbors(node, grid) { + const neighbors = []; + const x = node.x; + const y = node.y; + + if (x > 0) neighbors.push(grid[x - 1][y]); + if (x < grid.length - 1) neighbors.push(grid[x + 1][y]); + if (y > 0) neighbors.push(grid[x][y - 1]); + if (y < grid[0].length - 1) neighbors.push(grid[x][y + 1]); + + return neighbors; +} + +// Example usage +const grid = [ + [new Node(0, 0), new Node(1, 0), new Node(2, 0)], + [new Node(0, 1), new Node(1, 1), new Node(2, 1)], + [new Node(0, 2), new Node(1, 2), new Node(2, 2)] +]; + +const startNode = grid[0][0]; +const targetNode = grid[2][2]; + +const path = aStar(startNode, targetNode, grid); +console.log(path); From 3a9a8625f8e7d42bde6b784d42325a4fe4f6e77e Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 16 Aug 2023 23:22:27 +0530 Subject: [PATCH 1741/1894] Create KMP.go --- Strings/KMP.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Strings/KMP.go diff --git a/Strings/KMP.go b/Strings/KMP.go new file mode 100644 index 00000000..527b6c76 --- /dev/null +++ b/Strings/KMP.go @@ -0,0 +1,74 @@ +package main + +import ( + "fmt" +) + +// computeLPSArray computes the Longest Prefix Suffix (LPS) array for the given pattern. +func computeLPSArray(pattern string) []int { + length := len(pattern) + lps := make([]int, length) + lps[0] = 0 + j := 0 + + for i := 1; i < length; { + if pattern[i] == pattern[j] { + j++ + lps[i] = j + i++ + } else { + if j != 0 { + j = lps[j-1] + } else { + lps[i] = 0 + i++ + } + } + } + + return lps +} + +// KMPSearch searches for occurrences of the pattern within the given text using the KMP algorithm. +func KMPSearch(text, pattern string) []int { + n := len(text) + m := len(pattern) + lps := computeLPSArray(pattern) + + i := 0 // Index for text + j := 0 // Index for pattern + + positions := make([]int, 0) + + for i < n { + if pattern[j] == text[i] { + i++ + j++ + } + + if j == m { + positions = append(positions, i-j) + j = lps[j-1] + } else if i < n && pattern[j] != text[i] { + if j != 0 { + j = lps[j-1] + } else { + i++ + } + } + } + + return positions +} + +func main() { + text := "ABABDABACDABABCABAB" + pattern := "ABABCABAB" + positions := KMPSearch(text, pattern) + + if len(positions) == 0 { + fmt.Println("Pattern not found in the text.") + } else { + fmt.Printf("Pattern found at positions: %v\n", positions) + } +} From 8a8ff651b6b05a77c84c6c06118aee472bbca767 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 18 Aug 2023 08:12:41 +0530 Subject: [PATCH 1742/1894] Create Sorted_rotate_arr.go --- Binary Search/Sorted_rotate_arr.go | 53 ++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Binary Search/Sorted_rotate_arr.go diff --git a/Binary Search/Sorted_rotate_arr.go b/Binary Search/Sorted_rotate_arr.go new file mode 100644 index 00000000..7e59497d --- /dev/null +++ b/Binary Search/Sorted_rotate_arr.go @@ -0,0 +1,53 @@ +/* + This code implements the "Search in Rotated Sorted Array" problem, which requires finding the target value + in a rotated sorted array. + + The binarySearch function takes a sorted rotated array and the target value as input. It initializes two pointers, + left and right, to the start and end indices of the array, respectively. It then enters a while loop as long as + the left pointer is less than or equal to the right pointer. + + Inside the loop, the function calculates the middle index and checks if the middle element is equal to the target. + If it is, the function returns the middle index. + + Otherwise, it checks if the left half of the array is sorted by comparing the values at the left and middle indices. + If it is sorted and the target lies within the left half, the right pointer is updated to search only in the left half. + Otherwise, the left pointer is updated to search in the right half. + + If the left half is not sorted, then the right half must be sorted. In this case, the function checks if the target + lies within the right half. If it does, the left pointer is updated to search in the right half; otherwise, the right + pointer is updated to search in the left half. + + If the target is not found in the loop, the function returns -1 to indicate that the target is not present in the array. + + O(log n) time | O(1) space - where n is the length of the input array +*/ + +package main + +func search(nums []int, target int) int { + left, right := 0, len(nums)-1 + + for left <= right { + mid := left + (right-left)/2 + + if nums[mid] == target { + return mid + } + + if nums[left] <= nums[mid] { // Left half is sorted + if target >= nums[left] && target < nums[mid] { + right = mid - 1 + } else { + left = mid + 1 + } + } else { // Right half is sorted + if target > nums[mid] && target <= nums[right] { + left = mid + 1 + } else { + right = mid - 1 + } + } + } + + return -1 +} From 7e5fdcb5d2bf2dff33f1e4967121a85e710f1f14 Mon Sep 17 00:00:00 2001 From: Arpan Biswas <99377659+Geeks-Arpan@users.noreply.github.com> Date: Fri, 18 Aug 2023 11:56:16 +0530 Subject: [PATCH 1743/1894] Create Linear_Search #1646 --- Linear_Search | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Linear_Search diff --git a/Linear_Search b/Linear_Search new file mode 100644 index 00000000..eed122c6 --- /dev/null +++ b/Linear_Search @@ -0,0 +1,33 @@ +import java.util.Scanner; + +class LinearSearch +{ + public static void main(String args[]) + { + int i, n, search, array[]; + + Scanner in = new Scanner(System.in); + System.out.println("Enter number of elements"); + n = in.nextInt(); + array = new int[n]; + + System.out.println("Enter those " + n + " elements"); + + for (i = 0; i < n; i++) + array[i] = in.nextInt(); + + System.out.println("Enter value to find"); + search = in.nextInt(); + + for (i = 0; i < n; i++) + { + if (array[i] == search) /* Searching element is present */ + { + System.out.println(search + " is present at location " + (i + 1) + "."); + break; + } + } + if (i == n) /* Element to search isn't present */ + System.out.println(search + " isn't present in array."); + } +} From 06ab6ffe912913606103f7479e36273c16f58493 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 19 Aug 2023 15:44:42 +0530 Subject: [PATCH 1744/1894] Create prime.js --- Math/prime.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Math/prime.js diff --git a/Math/prime.js b/Math/prime.js new file mode 100644 index 00000000..9ff5b88b --- /dev/null +++ b/Math/prime.js @@ -0,0 +1,27 @@ +// Function to find the number of prime numbers less than n +function countPrimes(n) { + // Helper function to check if a number is prime + function isPrime(num) { + if (num <= 1) return false; + if (num <= 3) return true; + if (num % 2 === 0 || num % 3 === 0) return false; + for (let i = 5; i * i <= num; i += 6) { + if (num % i === 0 || num % (i + 2) === 0) return false; + } + return true; + } + + let count = 0; + for (let i = 2; i < n; i++) { + if (isPrime(i)) { + count++; + } + } + + return count; +} + +// Example usage: +const n = 30; // You can change the value of n +const primeCount = countPrimes(n); +console.log(`Number of prime numbers less than ${n}: ${primeCount}`); From b08a68a71ae9494a6a35a0ed50155dad3c004671 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 20 Aug 2023 11:27:00 +0530 Subject: [PATCH 1745/1894] Create N-Queen.go closes #362 --- Backtracking/N-Queen.go | 79 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Backtracking/N-Queen.go diff --git a/Backtracking/N-Queen.go b/Backtracking/N-Queen.go new file mode 100644 index 00000000..1947063e --- /dev/null +++ b/Backtracking/N-Queen.go @@ -0,0 +1,79 @@ +package main + +import ( + "fmt" +) + +func solveNQueens(n int) [][]string { + var result [][]string + board := make([][]rune, n) + for i := range board { + board[i] = make([]rune, n) + for j := range board[i] { + board[i][j] = '.' + } + } + + var isSafe func(row, col int) bool + isSafe = func(row, col int) bool { + // Check if no queen attacks this cell horizontally + for i := 0; i < col; i++ { + if board[row][i] == 'Q' { + return false + } + } + + // Check if no queen attacks this cell diagonally (left upper diagonal) + for i, j := row, col; i >= 0 && j >= 0; i, j = i-1, j-1 { + if board[i][j] == 'Q' { + return false + } + } + + // Check if no queen attacks this cell diagonally (left lower diagonal) + for i, j := row, col; i < n && j >= 0; i, j = i+1, j-1 { + if board[i][j] == 'Q' { + return false + } + } + + return true + } + + var backtrack func(col int) + backtrack = func(col int) { + if col == n { + var solution []string + for _, row := range board { + solution = append(solution, string(row)) + } + result = append(result, solution) + return + } + + for row := 0; row < n; row++ { + if isSafe(row, col) { + board[row][col] = 'Q' + backtrack(col + 1) + board[row][col] = '.' + } + } + } + + backtrack(0) + return result +} + +func main() { + n := 4 // Change this value to the desired board size + solutions := solveNQueens(n) + + fmt.Printf("Solutions for %d-Queens problem:\n", n) + for i, solution := range solutions { + fmt.Printf("Solution %d:\n", i+1) + for _, row := range solution { + fmt.Println(row) + } + fmt.Println() + } +} From 113e9d2b4ddab48421a74b9036adee5a89e08cb5 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 21 Aug 2023 08:49:08 +0530 Subject: [PATCH 1746/1894] Create Rotatedarr.go closes #431 --- Binary Search/Rotatedarr.go | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Binary Search/Rotatedarr.go diff --git a/Binary Search/Rotatedarr.go b/Binary Search/Rotatedarr.go new file mode 100644 index 00000000..9a735b0c --- /dev/null +++ b/Binary Search/Rotatedarr.go @@ -0,0 +1,52 @@ +//To perform a binary search in a rotated sorted array in Go, you can follow these steps: + +//Find the pivot point where the array is rotated. +//Once you have the pivot point, split the array into two subarrays, and perform binary search in one of the subarrays based on the target value. +//If the target value is not found in the first subarray, search in the second subarray. + +package main + +import "fmt" + +func search(nums []int, target int) int { + left, right := 0, len(nums)-1 + + for left <= right { + mid := left + (right-left)/2 + + if nums[mid] == target { + return mid + } + + // Check if the left subarray is sorted + if nums[left] <= nums[mid] { + // Check if the target is within the left subarray + if nums[left] <= target && target < nums[mid] { + right = mid - 1 + } else { + left = mid + 1 + } + } else { // Right subarray is sorted + // Check if the target is within the right subarray + if nums[mid] < target && target <= nums[right] { + left = mid + 1 + } else { + right = mid - 1 + } + } + } + + return -1 // Target not found +} + +func main() { + nums := []int{4, 5, 6, 7, 0, 1, 2} + target := 0 + result := search(nums, target) + + if result != -1 { + fmt.Printf("Target %d found at index %d\n", target, result) + } else { + fmt.Printf("Target %d not found in the array\n", target) + } +} From a58fe69e3b8845e2cf31c13c6181e501873637a7 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Tue, 22 Aug 2023 08:10:08 +0530 Subject: [PATCH 1747/1894] Create Sum_four.cpp --- Math/Sum_four.cpp | 79 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Math/Sum_four.cpp diff --git a/Math/Sum_four.cpp b/Math/Sum_four.cpp new file mode 100644 index 00000000..977210f2 --- /dev/null +++ b/Math/Sum_four.cpp @@ -0,0 +1,79 @@ +#include +#include +#include + +using namespace std; + +vector> fourSum(vector& nums, int target) { + vector> result; + + int n = nums.size(); + + if (n < 4) { + return result; + } + + sort(nums.begin(), nums.end()); + + for (int i = 0; i < n - 3; i++) { + // Avoid duplicates + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + + for (int j = i + 1; j < n - 2; j++) { + // Avoid duplicates + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + + int left = j + 1; + int right = n - 1; + + while (left < right) { + int sum = nums[i] + nums[j] + nums[left] + nums[right]; + + if (sum < target) { + left++; + } else if (sum > target) { + right--; + } else { + result.push_back({nums[i], nums[j], nums[left], nums[right]}); + + // Avoid duplicates + while (left < right && nums[left] == nums[left + 1]) { + left++; + } + while (left < right && nums[right] == nums[right - 1]) { + right--; + } + + left++; + right--; + } + } + } + } + + return result; +} + +int main() { + vector nums = {1, 0, -1, 0, -2, 2}; + int target = 0; + + vector> result = fourSum(nums, target); + + for (vector& quad : result) { + cout << "["; + for (int i = 0; i < 4; i++) { + cout << quad[i]; + if (i < 3) { + cout << ", "; + } + } + cout << "]" << endl; + } + + return 0; +} From cb971e50b06b2d6d39e6a9b6a2d91b3fb3e62a1e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta <65363296+akgmage@users.noreply.github.com> Date: Wed, 23 Aug 2023 22:13:46 +0530 Subject: [PATCH 1748/1894] Delete A*.js --- Graphs/A*.js | 98 ---------------------------------------------------- 1 file changed, 98 deletions(-) delete mode 100644 Graphs/A*.js diff --git a/Graphs/A*.js b/Graphs/A*.js deleted file mode 100644 index 91f7e499..00000000 --- a/Graphs/A*.js +++ /dev/null @@ -1,98 +0,0 @@ -class Node { - constructor(x, y) { - this.x = x; - this.y = y; - this.g = 0; // Cost from start node to this node - this.h = 0; // Heuristic cost from this node to target node - this.f = 0; // Total cost (g + h) - this.parent = null; // Parent node in the path - } -} - -function euclideanDistance(node1, node2) { - const dx = node2.x - node1.x; - const dy = node2.y - node1.y; - return Math.sqrt(dx * dx + dy * dy); -} - -function aStar(start, target, grid) { - const openList = [start]; - const closedList = []; - - while (openList.length > 0) { - let currentNode = openList[0]; - let currentIndex = 0; - - for (let i = 1; i < openList.length; i++) { - if (openList[i].f < currentNode.f) { - currentNode = openList[i]; - currentIndex = i; - } - } - - openList.splice(currentIndex, 1); - closedList.push(currentNode); - - if (currentNode === target) { - const path = []; - let current = currentNode; - while (current !== null) { - path.unshift(current); - current = current.parent; - } - return path; - } - - const neighbors = getNeighbors(currentNode, grid); - for (let neighbor of neighbors) { - if (closedList.some(node => node === neighbor)) { - continue; - } - - const tentativeG = currentNode.g + euclideanDistance(currentNode, neighbor); - let newPath = false; - - if (!openList.some(node => node === neighbor)) { - openList.push(neighbor); - newPath = true; - } else if (tentativeG < neighbor.g) { - newPath = true; - } - - if (newPath) { - neighbor.parent = currentNode; - neighbor.g = tentativeG; - neighbor.h = euclideanDistance(neighbor, target); - neighbor.f = neighbor.g + neighbor.h; - } - } - } - - return []; // No path found -} - -function getNeighbors(node, grid) { - const neighbors = []; - const x = node.x; - const y = node.y; - - if (x > 0) neighbors.push(grid[x - 1][y]); - if (x < grid.length - 1) neighbors.push(grid[x + 1][y]); - if (y > 0) neighbors.push(grid[x][y - 1]); - if (y < grid[0].length - 1) neighbors.push(grid[x][y + 1]); - - return neighbors; -} - -// Example usage -const grid = [ - [new Node(0, 0), new Node(1, 0), new Node(2, 0)], - [new Node(0, 1), new Node(1, 1), new Node(2, 1)], - [new Node(0, 2), new Node(1, 2), new Node(2, 2)] -]; - -const startNode = grid[0][0]; -const targetNode = grid[2][2]; - -const path = aStar(startNode, targetNode, grid); -console.log(path); From cb68dd1eca8196a1ee6ab84a48658a25cd52792c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 23 Aug 2023 22:15:46 +0530 Subject: [PATCH 1749/1894] remove files --- Backtracking/N-Queen.go | 79 ------------------------------ Binary Search/Rotatedarr.go | 52 -------------------- Binary Search/Sorted_rotate_arr.go | 53 -------------------- Linear_Search | 33 ------------- Math/prime.js | 27 ---------- 5 files changed, 244 deletions(-) delete mode 100644 Backtracking/N-Queen.go delete mode 100644 Binary Search/Rotatedarr.go delete mode 100644 Binary Search/Sorted_rotate_arr.go delete mode 100644 Linear_Search delete mode 100644 Math/prime.js diff --git a/Backtracking/N-Queen.go b/Backtracking/N-Queen.go deleted file mode 100644 index 1947063e..00000000 --- a/Backtracking/N-Queen.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import ( - "fmt" -) - -func solveNQueens(n int) [][]string { - var result [][]string - board := make([][]rune, n) - for i := range board { - board[i] = make([]rune, n) - for j := range board[i] { - board[i][j] = '.' - } - } - - var isSafe func(row, col int) bool - isSafe = func(row, col int) bool { - // Check if no queen attacks this cell horizontally - for i := 0; i < col; i++ { - if board[row][i] == 'Q' { - return false - } - } - - // Check if no queen attacks this cell diagonally (left upper diagonal) - for i, j := row, col; i >= 0 && j >= 0; i, j = i-1, j-1 { - if board[i][j] == 'Q' { - return false - } - } - - // Check if no queen attacks this cell diagonally (left lower diagonal) - for i, j := row, col; i < n && j >= 0; i, j = i+1, j-1 { - if board[i][j] == 'Q' { - return false - } - } - - return true - } - - var backtrack func(col int) - backtrack = func(col int) { - if col == n { - var solution []string - for _, row := range board { - solution = append(solution, string(row)) - } - result = append(result, solution) - return - } - - for row := 0; row < n; row++ { - if isSafe(row, col) { - board[row][col] = 'Q' - backtrack(col + 1) - board[row][col] = '.' - } - } - } - - backtrack(0) - return result -} - -func main() { - n := 4 // Change this value to the desired board size - solutions := solveNQueens(n) - - fmt.Printf("Solutions for %d-Queens problem:\n", n) - for i, solution := range solutions { - fmt.Printf("Solution %d:\n", i+1) - for _, row := range solution { - fmt.Println(row) - } - fmt.Println() - } -} diff --git a/Binary Search/Rotatedarr.go b/Binary Search/Rotatedarr.go deleted file mode 100644 index 9a735b0c..00000000 --- a/Binary Search/Rotatedarr.go +++ /dev/null @@ -1,52 +0,0 @@ -//To perform a binary search in a rotated sorted array in Go, you can follow these steps: - -//Find the pivot point where the array is rotated. -//Once you have the pivot point, split the array into two subarrays, and perform binary search in one of the subarrays based on the target value. -//If the target value is not found in the first subarray, search in the second subarray. - -package main - -import "fmt" - -func search(nums []int, target int) int { - left, right := 0, len(nums)-1 - - for left <= right { - mid := left + (right-left)/2 - - if nums[mid] == target { - return mid - } - - // Check if the left subarray is sorted - if nums[left] <= nums[mid] { - // Check if the target is within the left subarray - if nums[left] <= target && target < nums[mid] { - right = mid - 1 - } else { - left = mid + 1 - } - } else { // Right subarray is sorted - // Check if the target is within the right subarray - if nums[mid] < target && target <= nums[right] { - left = mid + 1 - } else { - right = mid - 1 - } - } - } - - return -1 // Target not found -} - -func main() { - nums := []int{4, 5, 6, 7, 0, 1, 2} - target := 0 - result := search(nums, target) - - if result != -1 { - fmt.Printf("Target %d found at index %d\n", target, result) - } else { - fmt.Printf("Target %d not found in the array\n", target) - } -} diff --git a/Binary Search/Sorted_rotate_arr.go b/Binary Search/Sorted_rotate_arr.go deleted file mode 100644 index 7e59497d..00000000 --- a/Binary Search/Sorted_rotate_arr.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - This code implements the "Search in Rotated Sorted Array" problem, which requires finding the target value - in a rotated sorted array. - - The binarySearch function takes a sorted rotated array and the target value as input. It initializes two pointers, - left and right, to the start and end indices of the array, respectively. It then enters a while loop as long as - the left pointer is less than or equal to the right pointer. - - Inside the loop, the function calculates the middle index and checks if the middle element is equal to the target. - If it is, the function returns the middle index. - - Otherwise, it checks if the left half of the array is sorted by comparing the values at the left and middle indices. - If it is sorted and the target lies within the left half, the right pointer is updated to search only in the left half. - Otherwise, the left pointer is updated to search in the right half. - - If the left half is not sorted, then the right half must be sorted. In this case, the function checks if the target - lies within the right half. If it does, the left pointer is updated to search in the right half; otherwise, the right - pointer is updated to search in the left half. - - If the target is not found in the loop, the function returns -1 to indicate that the target is not present in the array. - - O(log n) time | O(1) space - where n is the length of the input array -*/ - -package main - -func search(nums []int, target int) int { - left, right := 0, len(nums)-1 - - for left <= right { - mid := left + (right-left)/2 - - if nums[mid] == target { - return mid - } - - if nums[left] <= nums[mid] { // Left half is sorted - if target >= nums[left] && target < nums[mid] { - right = mid - 1 - } else { - left = mid + 1 - } - } else { // Right half is sorted - if target > nums[mid] && target <= nums[right] { - left = mid + 1 - } else { - right = mid - 1 - } - } - } - - return -1 -} diff --git a/Linear_Search b/Linear_Search deleted file mode 100644 index eed122c6..00000000 --- a/Linear_Search +++ /dev/null @@ -1,33 +0,0 @@ -import java.util.Scanner; - -class LinearSearch -{ - public static void main(String args[]) - { - int i, n, search, array[]; - - Scanner in = new Scanner(System.in); - System.out.println("Enter number of elements"); - n = in.nextInt(); - array = new int[n]; - - System.out.println("Enter those " + n + " elements"); - - for (i = 0; i < n; i++) - array[i] = in.nextInt(); - - System.out.println("Enter value to find"); - search = in.nextInt(); - - for (i = 0; i < n; i++) - { - if (array[i] == search) /* Searching element is present */ - { - System.out.println(search + " is present at location " + (i + 1) + "."); - break; - } - } - if (i == n) /* Element to search isn't present */ - System.out.println(search + " isn't present in array."); - } -} diff --git a/Math/prime.js b/Math/prime.js deleted file mode 100644 index 9ff5b88b..00000000 --- a/Math/prime.js +++ /dev/null @@ -1,27 +0,0 @@ -// Function to find the number of prime numbers less than n -function countPrimes(n) { - // Helper function to check if a number is prime - function isPrime(num) { - if (num <= 1) return false; - if (num <= 3) return true; - if (num % 2 === 0 || num % 3 === 0) return false; - for (let i = 5; i * i <= num; i += 6) { - if (num % i === 0 || num % (i + 2) === 0) return false; - } - return true; - } - - let count = 0; - for (let i = 2; i < n; i++) { - if (isPrime(i)) { - count++; - } - } - - return count; -} - -// Example usage: -const n = 30; // You can change the value of n -const primeCount = countPrimes(n); -console.log(`Number of prime numbers less than ${n}: ${primeCount}`); From 4fb4fd3b6a88d96194eabe593697162d25cf3584 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 24 Aug 2023 07:49:05 +0530 Subject: [PATCH 1750/1894] Create Graph_Dijstra.java --- Graphs/Graph_Dijstra.java | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Graphs/Graph_Dijstra.java diff --git a/Graphs/Graph_Dijstra.java b/Graphs/Graph_Dijstra.java new file mode 100644 index 00000000..f40ac596 --- /dev/null +++ b/Graphs/Graph_Dijstra.java @@ -0,0 +1,79 @@ +import java.util.*; + +class Graph { + private int V; // Number of vertices + private List> adj; // Adjacency list + + public Graph(int V) { + this.V = V; + adj = new ArrayList<>(V); + for (int i = 0; i < V; i++) { + adj.add(new ArrayList<>()); + } + } + + // Add an edge to the graph + public void addEdge(int source, int destination, int weight) { + Node node = new Node(destination, weight); + adj.get(source).add(node); + } + + public void dijkstra(int source) { + int[] distance = new int[V]; + Arrays.fill(distance, Integer.MAX_VALUE); + distance[source] = 0; + + PriorityQueue pq = new PriorityQueue<>(V, Comparator.comparingInt(node -> node.weight)); + pq.add(new Node(source, 0)); + + while (!pq.isEmpty()) { + int u = pq.poll().vertex; + + for (Node neighbor : adj.get(u)) { + int v = neighbor.vertex; + int w = neighbor.weight; + + if (distance[u] != Integer.MAX_VALUE && distance[u] + w < distance[v]) { + distance[v] = distance[u] + w; + pq.add(new Node(v, distance[v])); + } + } + } + + // Print the shortest distances from the source + System.out.println("Shortest distances from source vertex " + source + ":"); + for (int i = 0; i < V; i++) { + System.out.println("Vertex " + i + ": " + distance[i]); + } + } + + private static class Node { + int vertex; + int weight; + + Node(int vertex, int weight) { + this.vertex = vertex; + this.weight = weight; + } + } +} + +public class DijkstraAlgorithm { + public static void main(String[] args) { + int V = 6; // Number of vertices + Graph graph = new Graph(V); + + // Add edges and their weights + graph.addEdge(0, 1, 2); + graph.addEdge(0, 2, 4); + graph.addEdge(1, 2, 1); + graph.addEdge(1, 3, 7); + graph.addEdge(2, 4, 3); + graph.addEdge(3, 4, 1); + graph.addEdge(3, 5, 5); + graph.addEdge(4, 5, 2); + + int source = 0; // Source vertex + graph.dijkstra(source); + } +} From 1e68a1a18baa00d544b614d3be1fe07387555fee Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 25 Aug 2023 19:53:32 +0530 Subject: [PATCH 1751/1894] Create Basic_operations.py closes #1661 --- Math/Basic_operations.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Math/Basic_operations.py diff --git a/Math/Basic_operations.py b/Math/Basic_operations.py new file mode 100644 index 00000000..e4d8cf96 --- /dev/null +++ b/Math/Basic_operations.py @@ -0,0 +1,34 @@ +def divide(dividend, divisor): + if divisor == 0: + raise ZeroDivisionError("Division by zero") + if dividend == 0: + return 0 + + negative = (dividend < 0) ^ (divisor < 0) + dividend = abs(dividend) + divisor = abs(divisor) + + quotient = 0 + while dividend >= divisor: + dividend -= divisor + quotient += 1 + + if negative: + quotient = -quotient + + INT_MAX = 2**31 - 1 + INT_MIN = -2**31 + if quotient > INT_MAX: + return INT_MAX + elif quotient < INT_MIN: + return INT_MIN + else: + return quotient + +# Take user input for dividend and divisor +dividend = int(input("Enter the dividend: ")) +divisor = int(input("Enter the divisor: ")) + +# Perform the division and print the result +result = divide(dividend, divisor) +print(f"The result of {dividend} divided by {divisor} is: {result}") From 1d562056554e2e7629f152c412afc566273fe3b6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 26 Aug 2023 21:38:39 +0530 Subject: [PATCH 1752/1894] add knight probability --- .../knight_probability_chessboard.cpp | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Dynamic Programming/knight_probability_chessboard.cpp diff --git a/Dynamic Programming/knight_probability_chessboard.cpp b/Dynamic Programming/knight_probability_chessboard.cpp new file mode 100644 index 00000000..5fd04ebe --- /dev/null +++ b/Dynamic Programming/knight_probability_chessboard.cpp @@ -0,0 +1,73 @@ +/* +On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly k moves or has moved off the chessboard. + +Return the probability that the knight remains on the board after it has stopped moving. + + + +Example 1: + +Input: n = 3, k = 2, row = 0, column = 0 +Output: 0.06250 +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +From each of those positions, there are also two moves that will keep the knight on the board. +The total probability the knight stays on the board is 0.0625. +Example 2: + +Input: n = 1, k = 0, row = 0, column = 0 +Output: 1.00000 +*/ +#include +#include + +using namespace std; + +class Solution { +public: + double knightProbability(int n, int k, int row, int column) { + vector>> dp(k + 1, vector>(n, vector(n, -1.0))); + return dfs(n, k, row, column, dp); + } + + double dfs(int n, int k, int row, int column, vector>>& dp) { + if (row < 0 || row >= n || column < 0 || column >= n) { + return 0.0; + } + if (k == 0) { + return 1.0; + } + if (dp[k][row][column] != -1.0) { + return dp[k][row][column]; + } + + double probability = 0.0; + int directions[8][2] = {{-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {2, -1}, {1, -2}, {2, 1}, {1, 2}}; + + for (int i = 0; i < 8; ++i) { + int newRow = row + directions[i][0]; + int newColumn = column + directions[i][1]; + probability += 0.125 * dfs(n, k - 1, newRow, newColumn, dp); + } + + dp[k][row][column] = probability; + return probability; + } +}; + +int main() { + Solution solution; + int n1 = 3, k1 = 2, row1 = 0, column1 = 0; + cout << "Output 1: " << solution.knightProbability(n1, k1, row1, column1) << endl; + + int n2 = 1, k2 = 0, row2 = 0, column2 = 0; + cout << "Output 2: " << solution.knightProbability(n2, k2, row2, column2) << endl; + + return 0; +} From d6dd66479b4ab9840f943943f81245c2c340e506 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 26 Aug 2023 21:39:48 +0530 Subject: [PATCH 1753/1894] add comments --- .../knight_probability_chessboard.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Dynamic Programming/knight_probability_chessboard.cpp b/Dynamic Programming/knight_probability_chessboard.cpp index 5fd04ebe..e90faaa2 100644 --- a/Dynamic Programming/knight_probability_chessboard.cpp +++ b/Dynamic Programming/knight_probability_chessboard.cpp @@ -32,17 +32,25 @@ using namespace std; class Solution { public: double knightProbability(int n, int k, int row, int column) { + // Create a 3D vector for memoization vector>> dp(k + 1, vector>(n, vector(n, -1.0))); + + // Call the DFS function to compute the probability return dfs(n, k, row, column, dp); } double dfs(int n, int k, int row, int column, vector>>& dp) { + // Base case: Check if the knight goes off the board if (row < 0 || row >= n || column < 0 || column >= n) { return 0.0; } + + // Base case: If no more moves left, knight remains on the board if (k == 0) { return 1.0; } + + // If result is already computed, return it if (dp[k][row][column] != -1.0) { return dp[k][row][column]; } @@ -50,12 +58,14 @@ class Solution { double probability = 0.0; int directions[8][2] = {{-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {2, -1}, {1, -2}, {2, 1}, {1, 2}}; + // Try all 8 possible knight moves for (int i = 0; i < 8; ++i) { int newRow = row + directions[i][0]; int newColumn = column + directions[i][1]; probability += 0.125 * dfs(n, k - 1, newRow, newColumn, dp); } + // Memoize the result and return it dp[k][row][column] = probability; return probability; } @@ -63,11 +73,15 @@ class Solution { int main() { Solution solution; + + // Example 1 int n1 = 3, k1 = 2, row1 = 0, column1 = 0; cout << "Output 1: " << solution.knightProbability(n1, k1, row1, column1) << endl; + // Example 2 int n2 = 1, k2 = 0, row2 = 0, column2 = 0; cout << "Output 2: " << solution.knightProbability(n2, k2, row2, column2) << endl; return 0; } + From d0674f54de64d2e27027bfa539de3222379b89bf Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 26 Aug 2023 21:41:21 +0530 Subject: [PATCH 1754/1894] add knight probability in java --- .../knight_probability_chessboard.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Dynamic Programming/knight_probability_chessboard.java diff --git a/Dynamic Programming/knight_probability_chessboard.java b/Dynamic Programming/knight_probability_chessboard.java new file mode 100644 index 00000000..588159a2 --- /dev/null +++ b/Dynamic Programming/knight_probability_chessboard.java @@ -0,0 +1,78 @@ +/* +On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly k moves or has moved off the chessboard. + +Return the probability that the knight remains on the board after it has stopped moving. + + + +Example 1: + +Input: n = 3, k = 2, row = 0, column = 0 +Output: 0.06250 +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +From each of those positions, there are also two moves that will keep the knight on the board. +The total probability the knight stays on the board is 0.0625. +Example 2: + +Input: n = 1, k = 0, row = 0, column = 0 +Output: 1.00000 +*/ +public class KnightProbability { + public double knightProbability(int n, int k, int row, int column) { + // Create a 3D array for memoization + double[][][] dp = new double[k + 1][n][n]; + + // Call the recursive function to compute the probability + return dfs(n, k, row, column, dp); + } + + private double dfs(int n, int k, int row, int column, double[][][] dp) { + // Base case: Check if the knight goes off the board + if (row < 0 || row >= n || column < 0 || column >= n) { + return 0.0; + } + + // Base case: If no more moves left, knight remains on the board + if (k == 0) { + return 1.0; + } + + // If result is already computed, return it + if (dp[k][row][column] != 0.0) { + return dp[k][row][column]; + } + + double probability = 0.0; + int[][] directions = {{-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {2, -1}, {1, -2}, {2, 1}, {1, 2}}; + + // Try all 8 possible knight moves + for (int i = 0; i < 8; ++i) { + int newRow = row + directions[i][0]; + int newColumn = column + directions[i][1]; + probability += 0.125 * dfs(n, k - 1, newRow, newColumn, dp); + } + + // Memoize the result and return it + dp[k][row][column] = probability; + return probability; + } + + public static void main(String[] args) { + KnightProbability solution = new KnightProbability(); + + // Example 1 + int n1 = 3, k1 = 2, row1 = 0, column1 = 0; + System.out.println("Output 1: " + solution.knightProbability(n1, k1, row1, column1)); + + // Example 2 + int n2 = 1, k2 = 0, row2 = 0, column2 = 0; + System.out.println("Output 2: " + solution.knightProbability(n2, k2, row2, column2)); + } +} From 9f263782e0a1e084ca2909d63c52af94e69c241d Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 26 Aug 2023 22:45:55 +0530 Subject: [PATCH 1755/1894] Create op.js --- Math/op.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Math/op.js diff --git a/Math/op.js b/Math/op.js new file mode 100644 index 00000000..b4ec4442 --- /dev/null +++ b/Math/op.js @@ -0,0 +1,40 @@ +function divide(dividend, divisor) { + // Handle special cases + if (divisor === 0) { + throw new Error("Division by zero"); + } + if (dividend === 0) { + return 0; + } + + // Determine the sign of the result + const negativeResult = (dividend < 0) ^ (divisor < 0); + + // Make dividend and divisor positive for easier calculations + dividend = Math.abs(dividend); + divisor = Math.abs(divisor); + + let quotient = 0; + + while (dividend >= divisor) { + dividend -= divisor; + quotient++; + } + + if (negativeResult) { + quotient = -quotient; + } + + // Check for overflow + if (quotient < -(2**31) || quotient > 2**31 - 1) { + return 2**31 - 1; // Return INT_MAX for overflow + } + + return quotient; +} + +// Example usage: +const dividend = 10; +const divisor = 3; +const result = divide(dividend, divisor); +console.log(result); // Output should be 3 From 8d5806a8ec6e451571beb991d95d1300ba005da3 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 27 Aug 2023 09:32:13 +0530 Subject: [PATCH 1756/1894] Create Diljstra.go --- Graphs/Diljstra.go | 84 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Graphs/Diljstra.go diff --git a/Graphs/Diljstra.go b/Graphs/Diljstra.go new file mode 100644 index 00000000..8802aa27 --- /dev/null +++ b/Graphs/Diljstra.go @@ -0,0 +1,84 @@ +package main + +import ( + "fmt" + "math" +) + +// Define a struct to represent a graph. +type Graph struct { + nodes map[string]map[string]float64 +} + +// Add an edge to the graph. +func (g *Graph) AddEdge(node1, node2 string, weight float64) { + if g.nodes == nil { + g.nodes = make(map[string]map[string]float64) + } + if g.nodes[node1] == nil { + g.nodes[node1] = make(map[string]float64) + } + if g.nodes[node2] == nil { + g.nodes[node2] = make(map[string]float64) + } + g.nodes[node1][node2] = weight + g.nodes[node2][node1] = weight // Assuming an undirected graph +} + +// Dijkstra's algorithm to find the shortest path. +func Dijkstra(graph Graph, startNode string) map[string]float64 { + distances := make(map[string]float64) + visited := make(map[string]bool) + + for node := range graph.nodes { + distances[node] = math.Inf(1) + } + + distances[startNode] = 0 + + for { + var closestNode string + var shortestDistance float64 = math.Inf(1) + + for node, distance := range distances { + if !visited[node] && distance < shortestDistance { + closestNode = node + shortestDistance = distance + } + } + + if closestNode == "" { + break + } + + visited[closestNode] = true + + for neighbor, weight := range graph.nodes[closestNode] { + if newDistance := distances[closestNode] + weight; newDistance < distances[neighbor] { + distances[neighbor] = newDistance + } + } + } + + return distances +} + +func main() { + // Create a graph. + g := Graph{} + g.AddEdge("A", "B", 1) + g.AddEdge("A", "C", 4) + g.AddEdge("B", "C", 2) + g.AddEdge("B", "D", 5) + g.AddEdge("C", "D", 1) + g.AddEdge("D", "E", 3) + g.AddEdge("E", "F", 2) + + // Find the shortest distances from node "A" to all other nodes. + shortestDistances := Dijkstra(g, "A") + + // Print the shortest distances. + for node, distance := range shortestDistances { + fmt.Printf("Shortest distance from A to %s: %v\n", node, distance) + } +} From b17534b19e3ca2e8d821cee0f45529450989f4fe Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 28 Aug 2023 07:57:29 +0530 Subject: [PATCH 1757/1894] Create Count.go closes #499 --- Math/Count.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Math/Count.go diff --git a/Math/Count.go b/Math/Count.go new file mode 100644 index 00000000..2a89980c --- /dev/null +++ b/Math/Count.go @@ -0,0 +1,20 @@ +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; // There's only one number with 0 digits, which is 0. + } + + int result = 10; // For n = 1, there are 10 numbers with unique digits (0-9). + int uniqueDigits = 9; + int availableDigits = 9; + + for (int i = 2; i <= n && availableDigits > 0; i++) { + uniqueDigits *= availableDigits; + result += uniqueDigits; + availableDigits--; + } + + return result; + } +}; From 4bdc16ba40b57d98f0490ccf44b87bca6e94d793 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Wed, 30 Aug 2023 19:53:06 +0530 Subject: [PATCH 1758/1894] Create 2D_sorted.go closes #270 --- 2D Arrays (Matrix)/2D_sorted.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 2D Arrays (Matrix)/2D_sorted.go diff --git a/2D Arrays (Matrix)/2D_sorted.go b/2D Arrays (Matrix)/2D_sorted.go new file mode 100644 index 00000000..fbb74145 --- /dev/null +++ b/2D Arrays (Matrix)/2D_sorted.go @@ -0,0 +1,25 @@ +func searchMatrix(matrix [][]int, target int) bool { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return false + } + + rows, cols := len(matrix), len(matrix[0]) + left, right := 0, rows*cols-1 + + for left <= right { + mid := left + (right-left)/2 + // Convert the 1D index back to 2D coordinates + row, col := mid/cols, mid%cols + midValue := matrix[row][col] + + if midValue == target { + return true + } else if midValue < target { + left = mid + 1 + } else { + right = mid - 1 + } + } + + return false +} From 9b077701cf27f305e7a1f560d81173a394fcbf7d Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Fri, 1 Sep 2023 20:25:28 +0530 Subject: [PATCH 1759/1894] Create N_queen.js closes #365' --- Famous Algorithms/N_queen.js | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Famous Algorithms/N_queen.js diff --git a/Famous Algorithms/N_queen.js b/Famous Algorithms/N_queen.js new file mode 100644 index 00000000..b83980b3 --- /dev/null +++ b/Famous Algorithms/N_queen.js @@ -0,0 +1,59 @@ +function solveNQueens(n) { + const board = new Array(n).fill().map(() => new Array(n).fill('.')); // Create an empty NxN chessboard + + const solutions = []; + + function isSafe(row, col) { + // Check if no other queens are in the same column + for (let i = 0; i < row; i++) { + if (board[i][col] === 'Q') { + return false; + } + } + + // Check upper-left diagonal + for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) { + if (board[i][j] === 'Q') { + return false; + } + } + + // Check upper-right diagonal + for (let i = row, j = col; i >= 0 && j < n; i--, j++) { + if (board[i][j] === 'Q') { + return false; + } + } + + return true; + } + + function solve(row) { + if (row === n) { + // Found a valid solution, push a copy of the board to the solutions array + solutions.push(board.map(row => row.join(''))); + return; + } + + for (let col = 0; col < n; col++) { + if (isSafe(row, col)) { + board[row][col] = 'Q'; // Place a queen + solve(row + 1); // Recursively move to the next row + board[row][col] = '.'; // Backtrack by removing the queen + } + } + } + + solve(0); // Start solving from the first row + + return solutions; +} + +// Example usage: +const n = 4; // Change this to the desired board size +const solutions = solveNQueens(n); + +console.log(`Solutions for ${n}-Queens:`); +for (const solution of solutions) { + console.log(solution); +} From 694f51ad70c43f0ad9905009a9ceb6027e507b45 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 3 Sep 2023 07:40:54 +0530 Subject: [PATCH 1760/1894] Create plaindrome_str.cpp #1373 closes --- Strings/plaindrome_str.cpp | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Strings/plaindrome_str.cpp diff --git a/Strings/plaindrome_str.cpp b/Strings/plaindrome_str.cpp new file mode 100644 index 00000000..874d80b3 --- /dev/null +++ b/Strings/plaindrome_str.cpp @@ -0,0 +1,53 @@ +#include +#include + +using namespace std; + +bool isPalindrome(string s, int start, int end) { + while (start < end) { + if (s[start] != s[end]) { + return false; + } + start++; + end--; + } + return true; +} + +vector> partitionPalindrome(string s) { + vector> result; + vector current; + + backtrack(s, 0, current, result); + + return result; +} + +void backtrack(string s, int start, vector& current, vector>& result) { + if (start == s.length()) { + result.push_back(current); + return; + } + + for (int end = start; end < s.length(); end++) { + if (isPalindrome(s, start, end)) { + current.push_back(s.substr(start, end - start + 1)); + backtrack(s, end + 1, current, result); + current.pop_back(); + } + } +} + +int main() { + string s = "aab"; + vector> partitions = partitionPalindrome(s); + + for (auto partition : partitions) { + for (string palindrome : partition) { + cout << palindrome << " "; + } + cout << endl; + } + + return 0; +} From 2e60ea6ec9bf4543f6d63b51ce08677f55563c57 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 4 Sep 2023 20:59:03 +0530 Subject: [PATCH 1761/1894] Create circle.cpp closes #448 --- Math/circle.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Math/circle.cpp diff --git a/Math/circle.cpp b/Math/circle.cpp new file mode 100644 index 00000000..4e2567dc --- /dev/null +++ b/Math/circle.cpp @@ -0,0 +1,28 @@ +class Solution { + public int[] countPoints(int[][] points, int[][] queries) { + int[] answer = new int[queries.length]; + + for (int j = 0; j < queries.length; j++) { + int centerX = queries[j][0]; + int centerY = queries[j][1]; + int radius = queries[j][2]; + + for (int i = 0; i < points.length; i++) { + int pointX = points[i][0]; + int pointY = points[i][1]; + + // Check if the point (pointX, pointY) is inside the circle. + if (isInsideCircle(pointX, pointY, centerX, centerY, radius)) { + answer[j]++; + } + } + } + + return answer; + } + + private boolean isInsideCircle(int x, int y, int centerX, int centerY, int radius) { + int distanceSquared = (x - centerX) * (x - centerX) + (y - centerY) * (y - centerY); + return distanceSquared <= radius * radius; + } +} From 86b94a48ad57ddb98de1fa1ca159af8a717c3977 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 5 Sep 2023 21:04:47 +0530 Subject: [PATCH 1762/1894] add knight probability in python --- .../knight_probability_chessboard.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Dynamic Programming/knight_probability_chessboard.py diff --git a/Dynamic Programming/knight_probability_chessboard.py b/Dynamic Programming/knight_probability_chessboard.py new file mode 100644 index 00000000..52d29482 --- /dev/null +++ b/Dynamic Programming/knight_probability_chessboard.py @@ -0,0 +1,57 @@ +''' + On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). + + A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + + + Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + + The knight continues moving until it has made exactly k moves or has moved off the chessboard. + + Return the probability that the knight remains on the board after it has stopped moving. + + + + Example 1: + + Input: n = 3, k = 2, row = 0, column = 0 + Output: 0.06250 + Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. + From each of those positions, there are also two moves that will keep the knight on the board. + The total probability the knight stays on the board is 0.0625. + Example 2: + + Input: n = 1, k = 0, row = 0, column = 0 + Output: 1.00000 +''' +class Solution: + def knightProbability(self, n: int, k: int, row: int, column: int) -> float: + # Create a 3D grid to store the probabilities + dp = [[[0 for _ in range(k + 1)] for _ in range(n)] for _ in range(n)] + + # Define the eight possible knight moves + moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)] + + # Set the initial probability of the knight being on the starting cell to 1 + dp[row][column][0] = 1.0 + + # Calculate the probabilities for each move + for s in range(1, k + 1): + for i in range(n): + for j in range(n): + for move in moves: + x = i + move[0] + y = j + move[1] + + # Check if the move is within the chessboard + if 0 <= x < n and 0 <= y < n: + # Accumulate the probability for the current cell + dp[i][j][s] += dp[x][y][s - 1] / 8.0 + + # Calculate the total probability of the knight remaining on the board + probability = 0.0 + for i in range(n): + for j in range(n): + probability += dp[i][j][k] + + return probability From 8acd1f0fed0fc181cd68179e8f0a6fa77f4ad054 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 5 Sep 2023 21:06:17 +0530 Subject: [PATCH 1763/1894] update js verion --- .../knight_probability_chessboard.js | 106 ++++++++++++------ 1 file changed, 71 insertions(+), 35 deletions(-) diff --git a/Dynamic Programming/knight_probability_chessboard.js b/Dynamic Programming/knight_probability_chessboard.js index cff78471..461e6097 100644 --- a/Dynamic Programming/knight_probability_chessboard.js +++ b/Dynamic Programming/knight_probability_chessboard.js @@ -1,39 +1,75 @@ -/*Time Complexity: The time complexity of the code is O(n^2 * k) because, in the calculateProbability function, we have a loop that iterates over each cell on the chessboard (n x n) and for each cell, we make recursive calls for k moves. So, the total number of iterations would be proportional to n^2 * k. -Space Complexity: The space complexity of the code is O(n^2 * k) because we use a 3D array dp to store the calculated probabilities for each cell and the number of moves. The size of this array is n x n x k, which requires space proportional to n^2 * k. +/* +On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1). + +A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. + + +Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. + +The knight continues moving until it has made exactly k moves or has moved off the chessboard. + +Return the probability that the knight remains on the board after it has stopped moving. + + + +Example 1: + +Input: n = 3, k = 2, row = 0, column = 0 +Output: 0.06250 +Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +From each of those positions, there are also two moves that will keep the knight on the board. +The total probability the knight stays on the board is 0.0625. +Example 2: + +Input: n = 1, k = 0, row = 0, column = 0 +Output: 1.00000 */ +var knightProbability = function (n, k, row, column) { + // Create a 3D grid to store the probabilities + let dp = new Array(n) + .fill(0) + .map(() => new Array(n).fill(0).map(() => new Array(k + 1).fill(0))); -var knightProbability = function(n, k, row, column) { - const moves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]; - const dp = Array.from({ length: n }, () => Array.from({ length: n }, () => Array(k + 1).fill(0.0))); - // 3D array to store calculated probabilities - - const calculateProbability = (n, k, row, column) => { - // Base cases - if (row < 0 || row >= n || column < 0 || column >= n) { - return 0.0; // Knight is out of the chessboard - } - - if (k === 0) { - return 1.0; // Knight has made all the moves, so it remains on the board - } - - if (dp[row][column][k] > 0.0) { - return dp[row][column][k]; // Return already calculated probability - } - - let probability = 0.0; - - for (const knightMove of moves) { - const nextRow = row + knightMove[0]; - const nextColumn = column + knightMove[1]; - - probability += calculateProbability(n, k - 1, nextRow, nextColumn) / 8.0; // Recursively calculate probability for next moves + // Define the eight possible knight moves + const moves = [ + [-2, -1], + [-2, 1], + [-1, -2], + [-1, 2], + [1, -2], + [1, 2], + [2, -1], + [2, 1], + ]; + + // Set the initial probability of the knight being on the starting cell to 1 + dp[row][column][0] = 1.0; + + // Calculate the probabilities for each move + for (let s = 1; s <= k; s++) { + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + for (const move of moves) { + const x = i + move[0]; + const y = j + move[1]; + + // Check if the move is within the chessboard + if (x >= 0 && x < n && y >= 0 && y < n) { + // Accumulate the probability for the current cell + dp[i][j][s] += dp[x][y][s - 1] / 8.0; + } } - - dp[row][column][k] = probability; // Store the calculated probability - - return probability; - }; - - return calculateProbability(n, k, row, column); + } + } + } + + // Calculate the total probability of the knight remaining on the board + let probability = 0.0; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + probability += dp[i][j][k]; + } + } + + return probability; }; From f9098c03b862d29e59720396e4eb9ae8b6135702 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 6 Sep 2023 18:35:09 +0530 Subject: [PATCH 1764/1894] add knapsack in java --- Dynamic Programming/knapsack.java | 159 ++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 Dynamic Programming/knapsack.java diff --git a/Dynamic Programming/knapsack.java b/Dynamic Programming/knapsack.java new file mode 100644 index 00000000..799db62e --- /dev/null +++ b/Dynamic Programming/knapsack.java @@ -0,0 +1,159 @@ +/* + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. + + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. + + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + + Explanation: + + Sure! Let's break down the code step by step: + + 1. `KnapsackProblem` function: This function takes in two arguments - `items`, a 2D slice representing the + list of items with their values and weights, and `capacity`, an integer representing the maximum weight + capacity of the knapsack. It returns an interface slice containing the maximum value that can be achieved + and the sequence of items included in the knapsack to achieve that maximum value. + + 2. Initializing the `values` array: The function creates a 2D slice called `values` to store the maximum + achievable values for different knapsack configurations. The size of this array is `(len(items)+1) x (capacity+1)`, + where `(len(items)+1)` represents the number of items, and `(capacity+1)` represents the weight capacity of the knapsack. + The `values` array will be filled during the dynamic programming process. + + 3. Filling the `values` array: The function iterates through the `items` array and fills the `values` + array using dynamic programming. For each item at index `i`, the function calculates the maximum achievable + value for all possible capacities from `0` to `capacity`. + + 4. Inner loop: The inner loop iterates from `0` to `capacity` and calculates the maximum achievable value for + the current item at index `i` and the current capacity `c`. + + 5. Updating the `values` array: There are two possibilities for each item: + a. If the weight of the current item `items[i-1][1]` is greater than the current capacity `c`, we cannot + include the item in the knapsack at this capacity. So, we use the value from the previous row `values[i-1][c]` + for the current cell `values[i][c]`. + b. If we can include the current item, we have two choices: + i. Not include the current item, so the value remains the same as in the previous row `values[i-1][c]`. + ii. Include the current item, which adds its value `items[i-1][0]` to the value of the knapsack at capacity `c - items[i-1][1]`. + We choose the maximum of these two options and update the current cell `values[i][c]`. + + 6. Finding the maximum value: Once the `values` array is filled, the maximum achievable value for the knapsack is stored in the + bottom-right cell `values[len(items)][capacity]`. + + 7. Calling `getKnapSackItems` function: The function calls the `getKnapSackItems` function to find the sequence of items included in + the knapsack to achieve the maximum value. + + 8. `getKnapSackItems` function: This function takes in the `values` array and the `items` array as input and returns a slice containing + the indices of the items included in the knapsack. + + 9. Traversing back to find the items: Starting from the bottom-right cell of the `values` array, the function traverses back to find the + items included in the knapsack. It does this by comparing the value in the current cell `values[i][c]` with the value in the cell above + `values[i-1][c]`. If the values are the same, it means the current item was not included, so it moves to the previous row. Otherwise, + it means the current item was included, so it adds the index of the current item `(i-1)` to the `sequence` slice and updates the capacity `c` accordingly. + + 10. Reversing the `sequence`: The sequence of items is built in reverse order, so the function uses the `reverse` helper function to + reverse the order of elements in the `sequence` slice. + + 11. Returning the result: The function returns the maximum value and the sequence of items included in the knapsack as an interface slice. + + 12. Helper functions: The `max` function is a simple helper function that returns the maximum of two integers, and the `reverse` + function is used to reverse the order of elements in a slice. + + Time and Space complexity: + O(nc) time | O(nc) space - where n is the number of items and c is the capacity +*/ +import java.util.ArrayList; +import java.util.List; + +public class KnapsackProblem { + public static List knapsackProblem(int[][] items, int capacity) { + // Create a 2D array to store the values of different knapsack configurations. + int[][] values = new int[items.length + 1][capacity + 1]; + + // Iterate through the items and fill the values array. + for (int i = 1; i <= items.length; i++) { + int currentValue = items[i - 1][0]; + int currentWeight = items[i - 1][1]; + + for (int c = 0; c <= capacity; c++) { + // If the current item's weight is more than the current capacity (c), + // then we cannot include it, so we use the value from the previous row (i - 1). + if (currentWeight > c) { + values[i][c] = values[i - 1][c]; + } else { + // If we can include the current item, we have two choices: + // 1. Not include the current item, so the value remains the same as the previous row. + // 2. Include the current item, which adds its value to the value of the knapsack at capacity (c - currentWeight). + // We choose the maximum of these two options. + values[i][c] = Math.max(values[i - 1][c], values[i - 1][c - currentWeight] + currentValue); + } + } + } + + // The value at the bottom-right corner of the values array represents the maximum achievable value for the knapsack problem. + int value = values[items.length][capacity]; + + // Call the getKnapSackItems function to find the items that were included in the knapsack to achieve the maximum value. + List sequence = getKnapSackItems(values, items); + + // Return the maximum value and the sequence of items included in the knapsack as a list of objects. + List result = new ArrayList<>(); + result.add(value); + result.add(sequence); + return result; + } + + // getKnapSackItems is a helper function to find the sequence of items included in the knapsack. + private static List getKnapSackItems(int[][] values, int[][] items) { + List sequence = new ArrayList<>(); + int i = values.length - 1; + int c = values[0].length - 1; + + // Starting from the bottom-right corner of the values array, + // we traverse back to find the items included in the knapsack. + while (i > 0) { + if (values[i][c] == values[i - 1][c]) { + // If the value is the same as in the previous row, it means the current item was not included. + // So, we move to the previous row without adding the item to the sequence. + i--; + } else { + // If the value is greater than the value in the previous row, it means the current item was included. + // So, we add the index of the current item (i-1) to the sequence and update the capacity (c) accordingly. + sequence.add(i - 1); + c -= items[i - 1][1]; + i--; + } + // If the capacity becomes 0, it means we have included all the items needed to achieve the maximum value. + if (c == 0) { + break; + } + } + + // The sequence of items is built in reverse order, so we need to reverse it to get the correct order. + reverseList(sequence); + return sequence; + } + + // max returns the maximum of two integers. + private static int max(int a, int b) { + return Math.max(a, b); + } + + // reverseList reverses the order of elements in the given list. + private static void reverseList(List list) { + int left = 0; + int right = list.size() - 1; + while (left < right) { + int temp = list.get(left); + list.set(left, list.get(right)); + list.set(right, temp); + left++; + right--; + } + } +} From 9b07184909944fe73b77e5651582150d96593906 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 6 Sep 2023 18:48:41 +0530 Subject: [PATCH 1765/1894] add knapsack in c++ --- Dynamic Programming/knapsack.cpp | 140 +++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 Dynamic Programming/knapsack.cpp diff --git a/Dynamic Programming/knapsack.cpp b/Dynamic Programming/knapsack.cpp new file mode 100644 index 00000000..bd4b437b --- /dev/null +++ b/Dynamic Programming/knapsack.cpp @@ -0,0 +1,140 @@ +/* + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. + + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. + + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + + Explanation: + + Sure! Let's break down the code step by step: + + 1. `KnapsackProblem` function: This function takes in two arguments - `items`, a 2D slice representing the + list of items with their values and weights, and `capacity`, an integer representing the maximum weight + capacity of the knapsack. It returns an interface slice containing the maximum value that can be achieved + and the sequence of items included in the knapsack to achieve that maximum value. + + 2. Initializing the `values` array: The function creates a 2D slice called `values` to store the maximum + achievable values for different knapsack configurations. The size of this array is `(len(items)+1) x (capacity+1)`, + where `(len(items)+1)` represents the number of items, and `(capacity+1)` represents the weight capacity of the knapsack. + The `values` array will be filled during the dynamic programming process. + + 3. Filling the `values` array: The function iterates through the `items` array and fills the `values` + array using dynamic programming. For each item at index `i`, the function calculates the maximum achievable + value for all possible capacities from `0` to `capacity`. + + 4. Inner loop: The inner loop iterates from `0` to `capacity` and calculates the maximum achievable value for + the current item at index `i` and the current capacity `c`. + + 5. Updating the `values` array: There are two possibilities for each item: + a. If the weight of the current item `items[i-1][1]` is greater than the current capacity `c`, we cannot + include the item in the knapsack at this capacity. So, we use the value from the previous row `values[i-1][c]` + for the current cell `values[i][c]`. + b. If we can include the current item, we have two choices: + i. Not include the current item, so the value remains the same as in the previous row `values[i-1][c]`. + ii. Include the current item, which adds its value `items[i-1][0]` to the value of the knapsack at capacity `c - items[i-1][1]`. + We choose the maximum of these two options and update the current cell `values[i][c]`. + + 6. Finding the maximum value: Once the `values` array is filled, the maximum achievable value for the knapsack is stored in the + bottom-right cell `values[len(items)][capacity]`. + + 7. Calling `getKnapSackItems` function: The function calls the `getKnapSackItems` function to find the sequence of items included in + the knapsack to achieve the maximum value. + + 8. `getKnapSackItems` function: This function takes in the `values` array and the `items` array as input and returns a slice containing + the indices of the items included in the knapsack. + + 9. Traversing back to find the items: Starting from the bottom-right cell of the `values` array, the function traverses back to find the + items included in the knapsack. It does this by comparing the value in the current cell `values[i][c]` with the value in the cell above + `values[i-1][c]`. If the values are the same, it means the current item was not included, so it moves to the previous row. Otherwise, + it means the current item was included, so it adds the index of the current item `(i-1)` to the `sequence` slice and updates the capacity `c` accordingly. + + 10. Reversing the `sequence`: The sequence of items is built in reverse order, so the function uses the `reverse` helper function to + reverse the order of elements in the `sequence` slice. + + 11. Returning the result: The function returns the maximum value and the sequence of items included in the knapsack as an interface slice. + + 12. Helper functions: The `max` function is a simple helper function that returns the maximum of two integers, and the `reverse` + function is used to reverse the order of elements in a slice. + + Time and Space complexity: + O(nc) time | O(nc) space - where n is the number of items and c is the capacity +*/ +#include +#include + +using namespace std; + +vector knapsackProblem(vector>& items, int capacity) { + // Create a 2D vector to store the values of different knapsack configurations. + vector> values(items.size() + 1, vector(capacity + 1, 0)); + + // Iterate through the items and fill the values vector. + for (int i = 1; i <= items.size(); i++) { + int currentValue = items[i - 1][0]; + int currentWeight = items[i - 1][1]; + + for (int c = 0; c <= capacity; c++) { + // If the current item's weight is more than the current capacity (c), + // then we cannot include it, so we use the value from the previous row (i - 1). + if (currentWeight > c) { + values[i][c] = values[i - 1][c]; + } else { + // If we can include the current item, we have two choices: + // 1. Not include the current item, so the value remains the same as the previous row. + // 2. Include the current item, which adds its value to the value of the knapsack at capacity (c - currentWeight). + // We choose the maximum of these two options. + values[i][c] = max(values[i - 1][c], values[i - 1][c - currentWeight] + currentValue); + } + } + } + + // The value at the bottom-right corner of the values vector represents the maximum achievable value for the knapsack problem. + int value = values[items.size()][capacity]; + + // Call the getKnapSackItems function to find the items that were included in the knapsack to achieve the maximum value. + vector sequence = getKnapSackItems(values, items); + + // Return the maximum value and the sequence of items included in the knapsack. + vector result = {value}; + result.insert(result.end(), sequence.begin(), sequence.end()); + return result; +} + +// getKnapSackItems is a helper function to find the sequence of items included in the knapsack. +vector getKnapSackItems(vector>& values, vector>& items) { + vector sequence; + int i = values.size() - 1; + int c = values[0].size() - 1; + + // Starting from the bottom-right corner of the values vector, + // we traverse back to find the items included in the knapsack. + while (i > 0) { + if (values[i][c] == values[i - 1][c]) { + // If the value is the same as in the previous row, it means the current item was not included. + // So, we move to the previous row without adding the item to the sequence. + i--; + } else { + // If the value is greater than the value in the previous row, it means the current item was included. + // So, we add the index of the current item (i-1) to the sequence and update the capacity (c) accordingly. + sequence.push_back(i - 1); + c -= items[i - 1][1]; + i--; + } + // If the capacity becomes 0, it means we have included all the items needed to achieve the maximum value. + if (c == 0) { + break; + } + } + + // The sequence of items is built in reverse order, so we need to reverse it to get the correct order. + reverse(sequence.begin(), sequence.end()); + return sequence; +} From e073d037de5f763cf4a1a4a5fe131f1bfb987a85 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 7 Sep 2023 21:24:02 +0530 Subject: [PATCH 1766/1894] add knapsack in py --- Dynamic Programming/knapsack.py | 125 ++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Dynamic Programming/knapsack.py diff --git a/Dynamic Programming/knapsack.py b/Dynamic Programming/knapsack.py new file mode 100644 index 00000000..f1715316 --- /dev/null +++ b/Dynamic Programming/knapsack.py @@ -0,0 +1,125 @@ +''' + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. + + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. + + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + + Explanation: + + Sure! Let's break down the code step by step: + + 1. `KnapsackProblem` function: This function takes in two arguments - `items`, a 2D slice representing the + list of items with their values and weights, and `capacity`, an integer representing the maximum weight + capacity of the knapsack. It returns an interface slice containing the maximum value that can be achieved + and the sequence of items included in the knapsack to achieve that maximum value. + + 2. Initializing the `values` array: The function creates a 2D slice called `values` to store the maximum + achievable values for different knapsack configurations. The size of this array is `(len(items)+1) x (capacity+1)`, + where `(len(items)+1)` represents the number of items, and `(capacity+1)` represents the weight capacity of the knapsack. + The `values` array will be filled during the dynamic programming process. + + 3. Filling the `values` array: The function iterates through the `items` array and fills the `values` + array using dynamic programming. For each item at index `i`, the function calculates the maximum achievable + value for all possible capacities from `0` to `capacity`. + + 4. Inner loop: The inner loop iterates from `0` to `capacity` and calculates the maximum achievable value for + the current item at index `i` and the current capacity `c`. + + 5. Updating the `values` array: There are two possibilities for each item: + a. If the weight of the current item `items[i-1][1]` is greater than the current capacity `c`, we cannot + include the item in the knapsack at this capacity. So, we use the value from the previous row `values[i-1][c]` + for the current cell `values[i][c]`. + b. If we can include the current item, we have two choices: + i. Not include the current item, so the value remains the same as in the previous row `values[i-1][c]`. + ii. Include the current item, which adds its value `items[i-1][0]` to the value of the knapsack at capacity `c - items[i-1][1]`. + We choose the maximum of these two options and update the current cell `values[i][c]`. + + 6. Finding the maximum value: Once the `values` array is filled, the maximum achievable value for the knapsack is stored in the + bottom-right cell `values[len(items)][capacity]`. + + 7. Calling `getKnapSackItems` function: The function calls the `getKnapSackItems` function to find the sequence of items included in + the knapsack to achieve the maximum value. + + 8. `getKnapSackItems` function: This function takes in the `values` array and the `items` array as input and returns a slice containing + the indices of the items included in the knapsack. + + 9. Traversing back to find the items: Starting from the bottom-right cell of the `values` array, the function traverses back to find the + items included in the knapsack. It does this by comparing the value in the current cell `values[i][c]` with the value in the cell above + `values[i-1][c]`. If the values are the same, it means the current item was not included, so it moves to the previous row. Otherwise, + it means the current item was included, so it adds the index of the current item `(i-1)` to the `sequence` slice and updates the capacity `c` accordingly. + + 10. Reversing the `sequence`: The sequence of items is built in reverse order, so the function uses the `reverse` helper function to + reverse the order of elements in the `sequence` slice. + + 11. Returning the result: The function returns the maximum value and the sequence of items included in the knapsack as an interface slice. + + 12. Helper functions: The `max` function is a simple helper function that returns the maximum of two integers, and the `reverse` + function is used to reverse the order of elements in a slice. + + Time and Space complexity: + O(nc) time | O(nc) space - where n is the number of items and c is the capacity +''' +def knapsack_problem(items, capacity): + # Create a 2D list to store the values of different knapsack configurations. + values = [[0] * (capacity + 1) for _ in range(len(items) + 1)] + + # Iterate through the items and fill the values list. + for i in range(1, len(items) + 1): + current_value = items[i - 1][0] + current_weight = items[i - 1][1] + + for c in range(capacity + 1): + # If the current item's weight is more than the current capacity (c), + # then we cannot include it, so we use the value from the previous row (i - 1). + if current_weight > c: + values[i][c] = values[i - 1][c] + else: + # If we can include the current item, we have two choices: + # 1. Not include the current item, so the value remains the same as the previous row. + # 2. Include the current item, which adds its value to the value of the knapsack at capacity (c - current_weight). + # We choose the maximum of these two options. + values[i][c] = max(values[i - 1][c], values[i - 1][c - current_weight] + current_value) + + # The value at the bottom-right corner of the values list represents the maximum achievable value for the knapsack problem. + value = values[len(items)][capacity] + + # Call the get_knapsack_items function to find the items that were included in the knapsack to achieve the maximum value. + sequence = get_knapsack_items(values, items) + + # Return the maximum value and the sequence of items included in the knapsack. + return [value] + sequence + +# get_knapsack_items is a helper function to find the sequence of items included in the knapsack. +def get_knapsack_items(values, items): + sequence = [] + i = len(values) - 1 + c = len(values[0]) - 1 + + # Starting from the bottom-right corner of the values list, + # we traverse back to find the items included in the knapsack. + while i > 0: + if values[i][c] == values[i - 1][c]: + # If the value is the same as in the previous row, it means the current item was not included. + # So, we move to the previous row without adding the item to the sequence. + i -= 1 + else: + # If the value is greater than the value in the previous row, it means the current item was included. + # So, we add the index of the current item (i-1) to the sequence and update the capacity (c) accordingly. + sequence.append(i - 1) + c -= items[i - 1][1] + i -= 1 + # If the capacity becomes 0, it means we have included all the items needed to achieve the maximum value. + if c == 0: + break + + # The sequence of items is built in reverse order, so we need to reverse it to get the correct order. + sequence.reverse() + return sequence From 71760a594078603726fd10032bcd04067057e2d7 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 7 Sep 2023 21:32:50 +0530 Subject: [PATCH 1767/1894] Create Maximum_freq.py #292 --- Arrays/Maximum_freq.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Arrays/Maximum_freq.py diff --git a/Arrays/Maximum_freq.py b/Arrays/Maximum_freq.py new file mode 100644 index 00000000..d0868caf --- /dev/null +++ b/Arrays/Maximum_freq.py @@ -0,0 +1,25 @@ +class Solution { + public int majorityElement(int[] nums) { + int candidate = nums[0]; // Initialize the candidate as the first element + int count = 1; // Initialize the count of the current candidate as 1 + + // Iterate through the array starting from the second element + for (int i = 1; i < nums.length; i++) { + if (nums[i] == candidate) { + // If the current element is the same as the candidate, increment the count + count++; + } else if (count > 0) { + // If the current element is different from the candidate and count is positive, + // decrement the count since we have a matching pair (candidate vs. current element) + count--; + } else { + // If count becomes zero, update the candidate to the current element and set count to 1 + candidate = nums[i]; + count = 1; + } + } + + // At the end, the candidate will be the majority element + return candidate; + } +} From 39f8faec2a4bec9f7d06e53161489c037ecde5ef Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 9 Sep 2023 19:06:40 +0530 Subject: [PATCH 1768/1894] Create n_queen.cpp --- Backtracking/n_queen.cpp | 80 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Backtracking/n_queen.cpp diff --git a/Backtracking/n_queen.cpp b/Backtracking/n_queen.cpp new file mode 100644 index 00000000..d681dda0 --- /dev/null +++ b/Backtracking/n_queen.cpp @@ -0,0 +1,80 @@ +#include +#include + +using namespace std; + +// Function to check if it's safe to place a queen at board[row][col] +bool isSafe(vector& board, int row, int col, int N) { + // Check the row on the left side + for (int i = 0; i < col; ++i) { + if (board[row][i] == 'Q') { + return false; + } + } + + // Check upper diagonal on the left side + for (int i = row, j = col; i >= 0 && j >= 0; --i, --j) { + if (board[i][j] == 'Q') { + return false; + } + } + + // Check lower diagonal on the left side + for (int i = row, j = col; i < N && j >= 0; ++i, --j) { + if (board[i][j] == 'Q') { + return false; + } + } + + return true; +} + +// Recursive function to solve N-Queens problem +bool solveNQueens(vector& board, int col, int N) { + if (col == N) { + // All queens are placed successfully + return true; + } + + for (int i = 0; i < N; ++i) { + if (isSafe(board, i, col, N)) { + // Place queen + board[i][col] = 'Q'; + + // Recur to place the rest of the queens + if (solveNQueens(board, col + 1, N)) { + return true; + } + + // If placing queen in board[i][col] doesn't lead to a solution, backtrack + board[i][col] = '.'; + } + } + + // If no queen can be placed in this column, return false + return false; +} + +// Function to solve N-Queens problem and print the solution +void solveNQueens(int N) { + vector board(N, string(N, '.')); + + if (solveNQueens(board, 0, N)) { + // Print the solution + for (int i = 0; i < N; ++i) { + cout << board[i] << endl; + } + } else { + cout << "No solution exists." << endl; + } +} + +int main() { + int N; + cout << "Enter the number of queens (N): "; + cin >> N; + + solveNQueens(N); + + return 0; +} From f5d0e5e27d3986e43ca71019025f1e18bf70304d Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 10 Sep 2023 15:52:36 +0530 Subject: [PATCH 1769/1894] Create Rotatedarr.cpp --- Arrays/Rotatedarr.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Arrays/Rotatedarr.cpp diff --git a/Arrays/Rotatedarr.cpp b/Arrays/Rotatedarr.cpp new file mode 100644 index 00000000..6d7ca494 --- /dev/null +++ b/Arrays/Rotatedarr.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + int search(std::vector& nums, int target) { + int low = 0, high = nums.size() - 1; + + while (low <= high) { + int mid = (low + high) / 2; + + if (nums[mid] == target) { + return mid; + } + + if (nums[low] <= nums[mid]) { + if (nums[low] <= target && target < nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[high]) { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + + return -1; + } +}; From 93066d0251e2cfbbe2af64d074ff499a346136c4 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 11 Sep 2023 23:27:37 +0530 Subject: [PATCH 1770/1894] add knapsack in js --- Dynamic Programming/knapsack.js | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 Dynamic Programming/knapsack.js diff --git a/Dynamic Programming/knapsack.js b/Dynamic Programming/knapsack.js new file mode 100644 index 00000000..39653d22 --- /dev/null +++ b/Dynamic Programming/knapsack.js @@ -0,0 +1,143 @@ +/* + You're given an array of arrays where each subarray holds two integer values and represents an item; + the first integer is the item's value, and the second integer is the item's weight. + You're also given an integer representing the maximum capacity of a knapsack that you have. + + Your goal is to fit items in your knapsack without having the sum of their weights exceed the knapsack's + capacity, all the while maximizing their combined value. Note that you only have one of each item at your disposal. + + Write a function that returns the maximized combined value of the items that you should pick as well as an array of + the indices of each item picked. + + Sample Input:= [[1, 2], [4, 3], [5, 6], [6, 7]] + Output:= [10, [1, 3]] // items [4, 3] and [6, 7] + + Explanation: + + Sure! Let's break down the code step by step: + + 1. `KnapsackProblem` function: This function takes in two arguments - `items`, a 2D slice representing the + list of items with their values and weights, and `capacity`, an integer representing the maximum weight + capacity of the knapsack. It returns an interface slice containing the maximum value that can be achieved + and the sequence of items included in the knapsack to achieve that maximum value. + + 2. Initializing the `values` array: The function creates a 2D slice called `values` to store the maximum + achievable values for different knapsack configurations. The size of this array is `(len(items)+1) x (capacity+1)`, + where `(len(items)+1)` represents the number of items, and `(capacity+1)` represents the weight capacity of the knapsack. + The `values` array will be filled during the dynamic programming process. + + 3. Filling the `values` array: The function iterates through the `items` array and fills the `values` + array using dynamic programming. For each item at index `i`, the function calculates the maximum achievable + value for all possible capacities from `0` to `capacity`. + + 4. Inner loop: The inner loop iterates from `0` to `capacity` and calculates the maximum achievable value for + the current item at index `i` and the current capacity `c`. + + 5. Updating the `values` array: There are two possibilities for each item: + a. If the weight of the current item `items[i-1][1]` is greater than the current capacity `c`, we cannot + include the item in the knapsack at this capacity. So, we use the value from the previous row `values[i-1][c]` + for the current cell `values[i][c]`. + b. If we can include the current item, we have two choices: + i. Not include the current item, so the value remains the same as in the previous row `values[i-1][c]`. + ii. Include the current item, which adds its value `items[i-1][0]` to the value of the knapsack at capacity `c - items[i-1][1]`. + We choose the maximum of these two options and update the current cell `values[i][c]`. + + 6. Finding the maximum value: Once the `values` array is filled, the maximum achievable value for the knapsack is stored in the + bottom-right cell `values[len(items)][capacity]`. + + 7. Calling `getKnapSackItems` function: The function calls the `getKnapSackItems` function to find the sequence of items included in + the knapsack to achieve the maximum value. + + 8. `getKnapSackItems` function: This function takes in the `values` array and the `items` array as input and returns a slice containing + the indices of the items included in the knapsack. + + 9. Traversing back to find the items: Starting from the bottom-right cell of the `values` array, the function traverses back to find the + items included in the knapsack. It does this by comparing the value in the current cell `values[i][c]` with the value in the cell above + `values[i-1][c]`. If the values are the same, it means the current item was not included, so it moves to the previous row. Otherwise, + it means the current item was included, so it adds the index of the current item `(i-1)` to the `sequence` slice and updates the capacity `c` accordingly. + + 10. Reversing the `sequence`: The sequence of items is built in reverse order, so the function uses the `reverse` helper function to + reverse the order of elements in the `sequence` slice. + + 11. Returning the result: The function returns the maximum value and the sequence of items included in the knapsack as an interface slice. + + 12. Helper functions: The `max` function is a simple helper function that returns the maximum of two integers, and the `reverse` + function is used to reverse the order of elements in a slice. + + Time and Space complexity: + O(nc) time | O(nc) space - where n is the number of items and c is the capacity +*/ +function KnapsackProblem(items, capacity) { + // Create a 2D array to store the values of different knapsack configurations. + const values = new Array(items.length + 1) + .fill(0) + .map(() => new Array(capacity + 1).fill(0)); + + // Iterate through the items and fill the values array. + for (let i = 1; i < items.length + 1; i++) { + const currentValue = items[i - 1][0]; + const currentWeight = items[i - 1][1]; + + for (let c = 0; c < capacity + 1; c++) { + // If the current item's weight is more than the current capacity (c), + // then we cannot include it, so we use the value from the previous row (i - 1). + if (currentWeight > c) { + values[i][c] = values[i - 1][c]; + } else { + // If we can include the current item, we have two choices: + // 1. Not include the current item, so the value remains the same as the previous row. + // 2. Include the current item, which adds its value to the value of the knapsack at capacity (c - currentWeight). + // We choose the maximum of these two options. + values[i][c] = Math.max( + values[i - 1][c], + values[i - 1][c - currentWeight] + currentValue + ); + } + } + } + + // The value at the bottom-right corner of the values array represents the maximum achievable value for the knapsack problem. + const value = values[items.length][capacity]; + + // Call the getKnapSackItems function to find the items that were included in the knapsack to achieve the maximum value. + const sequence = getKnapSackItems(values, items); + + // Return the maximum value and the sequence of items included in the knapsack as an array. + return [value, sequence]; +} + +// getKnapSackItems is a helper function to find the sequence of items included in the knapsack. +function getKnapSackItems(values, items) { + const sequence = []; + let i = values.length - 1; + let c = values[0].length - 1; + + // Starting from the bottom-right corner of the values array, + // we traverse back to find the items included in the knapsack. + while (i > 0) { + if (values[i][c] == values[i - 1][c]) { + // If the value is the same as in the previous row, it means the current item was not included. + // So, we move to the previous row without adding the item to the sequence. + i--; + } else { + // If the value is greater than the value in the previous row, it means the current item was included. + // So, we add the index of the current item (i-1) to the sequence and update the capacity (c) accordingly. + sequence.push(i - 1); + c -= items[i - 1][1]; + i--; + } + // If the capacity becomes 0, it means we have included all the items needed to achieve the maximum value. + if (c == 0) { + break; + } + } + + // Reverse the sequence of items to get the correct order. + sequence.reverse(); + return sequence; +} + +// max returns the maximum of two integers. +function max(a, b) { + return a > b ? a : b; +} From e4d0b0f79eb0f1098f79aa22ef146ee6a160372b Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Mon, 11 Sep 2023 23:35:26 +0530 Subject: [PATCH 1771/1894] Create MaxConcatenatedstr.java --- Strings/MaxConcatenatedstr.java | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Strings/MaxConcatenatedstr.java diff --git a/Strings/MaxConcatenatedstr.java b/Strings/MaxConcatenatedstr.java new file mode 100644 index 00000000..4aef02bd --- /dev/null +++ b/Strings/MaxConcatenatedstr.java @@ -0,0 +1,47 @@ +class Solution { +public: + // i: arr[i] we are currently looking at + // mask: Bitmask that represents all the characters that have been added to the current string + // If 0-th bit in mask is set, it means that we have added "a" in the current string + int solve(vector &arr, int i, int mask) { + int n = arr.size(); + + if (i >= n) + return 0; + + // Skip concatenating arr[i] + int curRes = solve(arr, i+1, mask) + + // Mask to keep track of the characters that are present in arr[i] + int curMask = 0; + + // Check whether any character in arr[i] is present in current string, i.e. + // Check whether (arr[i]-'a')-th bit is set in mask + // If any existing character's bit is set, it means that we cannot concatenate arr[i] + // to the given string and so return curRes only which contains the result of skipping arr[i] + // Also, use curMask to maintain the characters in arr[i] that have been seen. + // It is possible that arr[i] itself has duplicate characters in which case, we will not be able to concatenate arr[i] + // So check whether (c-'a')-th bit is set in curMask and after that set the (c-'a')-th bit in curMask + for (char &c: arr[i]) { + if (mask & (1 << (c - 'a'))) + return curRes; + + if (curMask & (1 << (c - 'a'))) + return curRes; + + curMask |= (1 << (c - 'a')); + } + + // All the bits that were set in curMask will be now set in mask, + // in order to add all characters of arr[i] to the current string + mask |= curMask; + + // We make a call to i+1 with the updated mask and arr[i]'s length being added + curRes = max(curRes, (int) arr[i].length() + solve(arr, i+1, mask)); + return curRes; + } + + int maxLength(vector& arr) { + return solve(arr, 0, 0); + } +}; From 1430f6e244acb6f63859d7297f87c5f528755860 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Tue, 12 Sep 2023 23:41:08 +0530 Subject: [PATCH 1772/1894] Create MaxpathBinaryTree.cpp --- Trees/MaxpathBinaryTree.cpp | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Trees/MaxpathBinaryTree.cpp diff --git a/Trees/MaxpathBinaryTree.cpp b/Trees/MaxpathBinaryTree.cpp new file mode 100644 index 00000000..4183551e --- /dev/null +++ b/Trees/MaxpathBinaryTree.cpp @@ -0,0 +1,60 @@ +#include +#include // For max function + +using namespace std; + +// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +class Solution { +public: + int maxPathSum(TreeNode* root) { + int maxSum = INT_MIN; // Initialize with the minimum possible value + findMaxPathSum(root, maxSum); + return maxSum; + } + +private: + int findMaxPathSum(TreeNode* node, int& maxSum) { + if (!node) { + return 0; + } + + // Calculate the maximum path sum for the left and right subtrees + int leftMax = max(0, findMaxPathSum(node->left, maxSum)); + int rightMax = max(0, findMaxPathSum(node->right, maxSum)); + + // Calculate the maximum path sum that includes the current node + int currentMax = node->val + leftMax + rightMax; + + // Update the overall maximum path sum + maxSum = max(maxSum, currentMax); + + // Return the maximum path sum that can be extended from this node + return node->val + max(leftMax, rightMax); + } +}; + +int main() { + // Create a sample binary tree + TreeNode* root = new TreeNode(10); + root->left = new TreeNode(2); + root->right = new TreeNode(10); + root->left->left = new TreeNode(20); + root->left->right = new TreeNode(1); + root->right->right = new TreeNode(-25); + root->right->right->left = new TreeNode(3); + root->right->right->right = new TreeNode(4); + + Solution solution; + int maxSum = solution.maxPathSum(root); + + cout << "Maximum Path Sum: " << maxSum << endl; + + return 0; +} From 1d6a57f4a3f7ef82d5e2183ef7712d38fb8c2de9 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Thu, 14 Sep 2023 18:36:32 +0530 Subject: [PATCH 1773/1894] Create Hammingdistance.cpp --- Math/Hammingdistance.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Math/Hammingdistance.cpp diff --git a/Math/Hammingdistance.cpp b/Math/Hammingdistance.cpp new file mode 100644 index 00000000..68f2687f --- /dev/null +++ b/Math/Hammingdistance.cpp @@ -0,0 +1,14 @@ +lass Solution { +public: + int totalHammingDistance(vector& nums) { + int n=nums.size(), ans=0; + for(int i=0;i<32;i++){ + int count=0; + for(int k=0;k>i)&1; + } + ans += count*(n-count); + } + return ans; + } +}; From a81b6b64d908b5e71def5a7d6e29da1babd6adb6 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 16 Sep 2023 10:32:19 +0530 Subject: [PATCH 1774/1894] Update Hammingdistance.cpp --- Math/Hammingdistance.cpp | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/Math/Hammingdistance.cpp b/Math/Hammingdistance.cpp index 68f2687f..7c9904ee 100644 --- a/Math/Hammingdistance.cpp +++ b/Math/Hammingdistance.cpp @@ -1,14 +1,34 @@ -lass Solution { +#include + +class Solution { public: - int totalHammingDistance(vector& nums) { - int n=nums.size(), ans=0; - for(int i=0;i<32;i++){ - int count=0; - for(int k=0;k>i)&1; + int totalHammingDistance(std::vector& nums) { + // Get the number of elements in the input vector + int n = nums.size(); + // Initialize the variable to store the total Hamming distance + int ans = 0; + + // Iterate through each bit position (from 0 to 31) + for (int i = 0; i < 32; i++) { + // Initialize a variable to count the number of set bits at the current bit position + int count = 0; + + // Iterate through all elements in the vector + for (int k = 0; k < n; k++) { + // Count the number of set bits at the current bit position for each element + count += (nums[k] >> i) & 1; } - ans += count*(n-count); + + // Update the total Hamming distance by adding the product of set bits and unset bits + ans += count * (n - count); } + + // Return the total Hamming distance return ans; } }; + +/* +This program defines a Solution class with a totalHammingDistance method that calculates the total Hamming distance for the input vector nums. The outer loop iterates over each bit position (from 0 to 31), and the inner loop counts the number of set bits at that bit position for all elements in the vector. It then updates the ans variable by adding the product of the count of set bits and the count of unset bits at that position. + +This code efficiently calculates the total Hamming distance for a vector of integers by considering each bit position separately. */ From abe9c4ba288636eb5d4a6434d6da332d1b8960e7 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 16 Sep 2023 10:33:48 +0530 Subject: [PATCH 1775/1894] Create Bloomfilter.cpp --- Hash Table/Bloomfilter.cpp | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Hash Table/Bloomfilter.cpp diff --git a/Hash Table/Bloomfilter.cpp b/Hash Table/Bloomfilter.cpp new file mode 100644 index 00000000..76de2d67 --- /dev/null +++ b/Hash Table/Bloomfilter.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +class BloomFilter { +private: + int size; // Size of the Bloom Filter bitset + std::vector> hash_functions; + std::bitset<1000000> bitset; // Bitset to represent the Bloom Filter + +public: + // Constructor to initialize the Bloom Filter with a given size and hash functions + BloomFilter(int size, std::vector> hash_functions) + : size(size), hash_functions(hash_functions) {} + + // Function to add an element to the Bloom Filter + void add(const std::string& element) { + for (const auto& hash_function : hash_functions) { + size_t index = hash_function(element) % size; + bitset.set(index); + } + } + + // Function to check if an element may exist in the Bloom Filter + bool contains(const std::string& element) { + for (const auto& hash_function : hash_functions) { + size_t index = hash_function(element) % size; + if (!bitset.test(index)) { + return false; // If any bit is not set, the element is definitely not in the filter + } + } + return true; // If all bits are set, the element may exist in the filter (false positives are possible) + } +}; + +// Example hash function using std::hash +size_t hash1(const std::string& str) { + return std::hash{}(str); +} + +// Example hash function using a custom hash function +size_t hash2(const std::string& str) { + size_t hash = 0; + for (char c : str) { + hash = (hash * 31) + c; + } + return hash; +} + +int main() { + // Create a Bloom Filter with a size of 1000000 and two hash functions + BloomFilter bloomFilter(1000000, {hash1, hash2}); + + // Add elements to the Bloom Filter + bloomFilter.add("apple"); + bloomFilter.add("banana"); + bloomFilter.add("cherry"); + + // Check if elements may exist in the Bloom Filter + std::cout << "Contains 'apple': " << bloomFilter.contains("apple") << std::endl; // Should return 1 (true) + std::cout << "Contains 'grape': " << bloomFilter.contains("grape") << std::endl; // Should return 0 (false) + std::cout << "Contains 'cherry': " << bloomFilter.contains("cherry") << std::endl; // Should return 1 (true) + + return 0; +} From 4df56ba6e7700512517c2d8b5d184dc06441ee79 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sun, 17 Sep 2023 19:34:35 +0530 Subject: [PATCH 1776/1894] Create MiddleofLL.py --- Linked List/MiddleofLL.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Linked List/MiddleofLL.py diff --git a/Linked List/MiddleofLL.py b/Linked List/MiddleofLL.py new file mode 100644 index 00000000..bf232d90 --- /dev/null +++ b/Linked List/MiddleofLL.py @@ -0,0 +1,32 @@ +class ListNode: + def __init__(self, value=0, next=None): + self.value = value + self.next = next + +def find_middle(head): + # Initialize slow and fast pointers to the head of the linked list + slow_ptr = head + fast_ptr = head + + # Traverse the linked list with slow and fast pointers + while fast_ptr is not None and fast_ptr.next is not None: + # Move slow pointer one step at a time + slow_ptr = slow_ptr.next + # Move fast pointer two steps at a time + fast_ptr = fast_ptr.next.next + + # When the fast pointer reaches the end, the slow pointer will be at the middle + return slow_ptr + +# Create a sample linked list: 1 -> 2 -> 3 -> 4 -> 5 +head = ListNode(1) +head.next = ListNode(2) +head.next.next = ListNode(3) +head.next.next.next = ListNode(4) +head.next.next.next.next = ListNode(5) + +# Find the middle node of the linked list +middle_node = find_middle(head) + +# Print the value of the middle node +print("Middle Node:", middle_node.value) # Output: Middle Node: 3 From cb0efdca8f98696da889384afe07858bf2575014 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 18 Sep 2023 20:13:07 +0530 Subject: [PATCH 1777/1894] add dijkstras in python --- Graphs/dijkstras.py | 133 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Graphs/dijkstras.py diff --git a/Graphs/dijkstras.py b/Graphs/dijkstras.py new file mode 100644 index 00000000..8fb69c3d --- /dev/null +++ b/Graphs/dijkstras.py @@ -0,0 +1,133 @@ + +''' + + Write a function that computes the lengths of the shortest paths between start and all of the other vertices in the graph using Dijkstra's algorithm and returns them in an array. + + Sample Input: + Start: 0 + Edges : = [ + [[1, 7]], + [[2, 6], [3, 20], [4, 3]], + [[3, 14]], + [[4, 2]], + [], + [], + ] + Output: [0, 7, 13, 27, 10, -1] + + Dijkstras Algorithm + + Explanation: + + The code snippet is an implementation of Dijkstra's algorithm for finding the shortest path from a given starting vertex to all other vertices in a graph. Here's a breakdown of the code: + + 1. The `DijkstrasAlgorithm` function takes the starting vertex (`start`) and the graph represented by the adjacency list (`edges`) as input and returns a list of minimum distances from the starting vertex to all other vertices. + + 2. It initializes `numberOfVertices` as the total number of vertices in the graph. + + 3. The `minDistances` slice is initialized with maximum integer values to represent infinity distance for all vertices. The length of `minDistances` is set to the number of vertices. + + 4. The minimum distance from the starting vertex to itself is set to 0. + + 5. The `visited` map is used to keep track of visited vertices. Initially, it is empty. + + 6. The algorithm iterates until all vertices have been visited. In each iteration, it selects the vertex with the minimum distance from the `minDistances` slice using the `getVertexWithMinDistance` function. + + 7. If the current minimum distance is infinity (i.e., no more vertices to visit), the loop breaks. + + 8. The selected vertex is marked as visited by adding it to the `visited` map. + + 9. For each neighboring vertex of the selected vertex, it calculates the new path distance and updates the `minDistances` if the new distance is smaller. + + 10. After all iterations, the `finalDistances` slice is created to convert the `minDistances` into a format where unreachable vertices are represented as -1. + + 11. The `getVertexWithMinDistance` function returns the vertex with the minimum distance from the `distances` slice and the current minimum distance. + + Overall, the code implements Dijkstra's algorithm to find the shortest path from a starting vertex to all other vertices in a graph, using an adjacency list representation. It keeps track of minimum distances, visited vertices, and updates the distances based on the neighboring vertices. + + Time Complexity: O(V^2 + e) + Space complexity: O(V) + +''' + +import "math" + +# DijkstrasAlgorithm finds the shortest path from a starting vertex to all other vertices in a graph. +func DijkstrasAlgorithm(start int, edges [][][]int) []int { + numberOfVertices := len(edges) + minDistances := make([]int, 0, len(edges)) + + # Initialize the minDistances slice with maximum integer values + for range edges { + minDistances = append(minDistances, math.MaxInt32) + } + + # Set the distance of the starting vertex to 0 + minDistances[start] = 0 + visited := map[int]bool{} + + # Iterate until all vertices have been visited + for len(visited) != numberOfVertices { + # Get the vertex with the minimum distance + vertex, currentMinDistance := getVertexWithMinDistance(minDistances, visited) + + # If the current minimum distance is infinity, break the loop + if currentMinDistance == math.MaxInt32 { + break + } + + # Mark the vertex as visited + visited[vertex] = true + + # Explore neighboring vertices + for _, edge := range edges[vertex] { + destination, distanceToDestination := edge[0], edge[1] + + # Skip if the destination vertex is already visited + if visited[destination] { + continue + } + + # Calculate the new path distance to the destination + newPathDistance := currentMinDistance + distanceToDestination + currentDestinationDistance := minDistances[destination] + + # Update the minimum distance if the new distance is smaller + if newPathDistance < currentDestinationDistance { + minDistances[destination] = newPathDistance + } + } + } + + # Convert the minDistances slice to finalDistances, representing unreachable vertices as -1 + finalDistances := make([]int, 0, len(minDistances)) + for _, distance := range minDistances { + if distance == math.MaxInt32 { + finalDistances = append(finalDistances, -1) + } else { + finalDistances = append(finalDistances, distance) + } + } + + return finalDistances +} + +# getVertexWithMinDistance returns the vertex with the minimum distance from the distances slice. +func getVertexWithMinDistance(distances []int, visited map[int]bool) (int, int) { + currentMinDistance := math.MaxInt32 + vertex := -1 + + # Find the vertex with the minimum distance among unvisited vertices + for vertexIdx, distance := range distances { + if visited[vertexIdx] { + continue + } + + if distance <= currentMinDistance { + vertex = vertexIdx + currentMinDistance = distance + } + } + + return vertex, currentMinDistance +} From 3c07abd87e79e5698172e0f5d0717ba259956d94 Mon Sep 17 00:00:00 2001 From: p1kalys Date: Tue, 19 Sep 2023 10:02:24 +0530 Subject: [PATCH 1778/1894] Added a program in Hash Table. --- .../Count_Pairs_of_Points_With_Distance_k.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Hash Table/Count_Pairs_of_Points_With_Distance_k.py diff --git a/Hash Table/Count_Pairs_of_Points_With_Distance_k.py b/Hash Table/Count_Pairs_of_Points_With_Distance_k.py new file mode 100644 index 00000000..85a40bfa --- /dev/null +++ b/Hash Table/Count_Pairs_of_Points_With_Distance_k.py @@ -0,0 +1,33 @@ +#Given a 2D integer array coordinates and an integer k, where coordinates[i] = [xi, yi] are the coordinates of the ith point in a 2D plane. + +#We define the distance between two points (x1, y1) and (x2, y2) as (x1 XOR x2) + (y1 XOR y2) where XOR is the bitwise XOR operation. + +#Return the number of pairs (i, j) such that i < j and the distance between points i and j is equal to k. + +def count_pairs(coordinates, k): + result = 0 + seen = {} + + for x, y in coordinates: + for split in range(k + 1): + x_complement = x ^ split + y_complement = y ^ (k - split) + result += seen.get((x_complement, y_complement), 0) + seen[x, y] = seen.get((x, y), 0) + 1 + + return result + +# Take user input for coordinates +coordinates = [] +num_coordinates = int(input("Enter the number of coordinates: ")) + +for i in range(num_coordinates): + x = int(input(f"Enter x-coordinate for point {i + 1}: ")) + y = int(input(f"Enter y-coordinate for point {i + 1}: ")) + coordinates.append((x, y)) + +# Take user input for k +k = int(input("Enter the value of k: ")) + +pair_count = count_pairs(coordinates, k) +print(f"Number of pairs that satisfy the condition: {pair_count}") From 680eba5cceb6817e95b2ccdaa98bc78360692616 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 20 Sep 2023 22:13:16 +0530 Subject: [PATCH 1779/1894] refactor --- Arrays/find_no_of_good_pairs_in_array.java | 133 ------------------ Arrays/shuffle_array.java | 110 --------------- .../subarray_with_given_sum_and_length.java | 101 ------------- Binary Search/ceil_letter.java | 47 ------- Binary Search/peak_index_in_array.cpp | 62 -------- ...opological_sort,js => topological_sort.js} | 0 6 files changed, 453 deletions(-) delete mode 100644 Arrays/find_no_of_good_pairs_in_array.java delete mode 100644 Arrays/shuffle_array.java delete mode 100644 Arrays/subarray_with_given_sum_and_length.java delete mode 100644 Binary Search/ceil_letter.java delete mode 100644 Binary Search/peak_index_in_array.cpp rename Graphs/{topological_sort,js => topological_sort.js} (100%) diff --git a/Arrays/find_no_of_good_pairs_in_array.java b/Arrays/find_no_of_good_pairs_in_array.java deleted file mode 100644 index be63d9ca..00000000 --- a/Arrays/find_no_of_good_pairs_in_array.java +++ /dev/null @@ -1,133 +0,0 @@ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Scanner; - -/* -Given an array of integers nums, return the number of good pairs. - -A pair (i, j) is called good if nums[i] == nums[j] and i < j. - -Example 1: - -Input: num -s = [1,2,3,1,1,3] -Output: 4 -Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. -Example 2: - -Input: nums = [1,1,1,1] -Output: 6 -Explanation: Each pair in the array are good. -Example 3: - -Input: nums = [1,2,3] -Output: 0 - -Constraints: - -1 <= nums.length <= 100 -1 <= nums[i] <= 100 - -*/ -public class FindNoOfGoodPairs{ - - /* - Brute Force solution: - time complexity : O(n^2) - space complexity : O(1) - */ - public static int countNoOfGoodPairsBF(List array){ - int len = array.size(); - int goodPairs=0; - - for(int i=0; i array){ - int len = array.size(); - int goodPairs = 0; - - HashMap occurence = new HashMap<>(); - - // construct the occurence map - for(int i=0; i 1){ - goodPairs += ( (freq-1)*(freq) / 2 ); - } - } - - return goodPairs; - } - - public static void main(String args[]){ - - Scanner sc = new Scanner(System.in); - int arrLen = sc.nextInt(); - - List array = new ArrayList<>(); - - for(int i=0; i>int[] rand = Arrays.copyOf(nums, nums.length); creates a copy of the original array nums using Arrays.copyOf() method. -This copy, called rand, will be shuffled to avoid modifying the original array. - ->>The for loop iterates over each element of the array. The loop variable i represents the current index being processed. - ->>Inside the loop, int r = (int) (Math.random() * (i+1)); generates a random index r between 0 and i, inclusive. - This index r will be used to swap elements in the rand array. - ->>The lines int temp = rand[i];, rand[i] = rand[r];, and rand[r] = temp; perform the swapping of elements. - The element at index i is temporarily stored in temp, then the element at index r is moved to index i, and finally, the element stored in temp is moved to index r. This swapping step ensures a random shuffling of the elements. - ->>After the loop completes, the shuffled array rand is returned. - ->>The Fisher-Yates algorithm used in the shuffle() method ensures that each possible permutation of the array has an equal probability of occurring. - By swapping elements randomly, it guarantees a uniform and unbiased shuffling of the array. - - // - - import java.util.Arrays; -import java.util.Scanner; - -public class Solution { - private int[] nums; - - public Solution(int[] nums) { - this.nums = nums; - } - - public int[] reset() { - return nums; - } - - public int[] shuffle() { - int[] rand = Arrays.copyOf(nums, nums.length); - for (int i = 0; i < nums.length; i++) { - int r = (int) (Math.random() * (i+1)); - int temp = rand[i]; - rand[i] = rand[r]; - rand[r] = temp; - } - return rand; - } - - public static void main(String[] args) { - int[] nums = {1, 2, 3, 4, 5}; - - Solution solution = new Solution(nums); - - Scanner scanner = new Scanner(System.in); - - while (true) { - System.out.println("Enter 1 to reset the array, 2 to shuffle the array, or 0 to exit:"); - int choice = scanner.nextInt(); - - if (choice == 1) { - int[] resetArray = solution.reset(); - System.out.println("Reset Array:"); - printArray(resetArray); - } else if (choice == 2) { - int[] shuffledArray = solution.shuffle(); - System.out.println("Shuffled Array:"); - printArray(shuffledArray); - } else if (choice == 0) { - System.out.println("Exiting..."); - break; - } else { - System.out.println("Invalid choice. Please try again."); - } - } - - scanner.close(); - } - - public static void printArray(int[] arr) { - for (int num : arr) { - System.out.print(num + " "); - } - System.out.println(); - } -} - - - diff --git a/Arrays/subarray_with_given_sum_and_length.java b/Arrays/subarray_with_given_sum_and_length.java deleted file mode 100644 index 9f1521e2..00000000 --- a/Arrays/subarray_with_given_sum_and_length.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Given an array A of length N. Also given are integers B and C. - * - * Return 1 if there exists a subarray with length B having sum C and 0 otherwise - * - * - * - * Problem Constraints - * 1 <= N <= 105 - * - * 1 <= A[i] <= 104 - * - * 1 <= B <= N - * - * 1 <= C <= 109 - * - * - * - * Input Format - * First argument A is an array of integers. - * - * The remaining arguments B and C are integers - * - * - * - * Output Format - * Return 1 if such a subarray exist and 0 otherwise - * - * - * Example Input - * Input 1: - * A = [4, 3, 2, 6] - * B = 2 - * C = 5 - * Input 2: - * - * A = [4, 2, 2] - * B = 2 - * C = 8 - * - * - * Example Output - * Output 1: - * 1 - * Output 2: - * - * 0 - * - * - * Example Explanation - * Explanation 1: - * The subarray [3, 2] is of length 2 and sum 5. - * Explanation 2: - * There are no such subarray. - */ - -package SlidingWindow; - -public class SubarrayWithGivenSumAndLength { - public static void main(String[] args) { - final long startTime = System.currentTimeMillis(); - final long beforeUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - - int[] array = {4, 3, 2, 6}; - int b = 2; - int c = 5; - int ans = solve(array, b, c); - System.out.println(ans); - - final long endTime = System.currentTimeMillis(); - final long afterUsedMem = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory(); - final long actualMemUsed = afterUsedMem-beforeUsedMem; - System.out.println("Runtime " + (endTime - startTime) + " ms"); - System.out.println("Space " + actualMemUsed + " B"); - } - - public static int solve(int[] array, int b, int c) { - //O(n) time | O(1) space - int sum = 0; - int len = array.length; - for (int i = 0; i < b; i++) // find prefix sum of length b - sum += array[i]; - - // use sliding window approach to find sum of length c with length b. - int startIdx = 1; // 1 because already calculated the subarray sum of length b in above for loop. - int endIdx = b; - - while (endIdx < len) { - - sum = sum + array[endIdx] - array[startIdx - 1]; // add array[endIdx] num and remove array[startIdx - 1] - if (sum == c) // found subarray of sum c, so return 1. - return 1; - - startIdx++; - endIdx++; - } - - - return 0; - } -} \ No newline at end of file diff --git a/Binary Search/ceil_letter.java b/Binary Search/ceil_letter.java deleted file mode 100644 index 347fd9f9..00000000 --- a/Binary Search/ceil_letter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* Ceiling of an element in a sorted array - You are given a sorted array of characheters and a target . - Find the smallest character that is greater than target. - - Note : The letters wrap around in the array - ie, for an array ['c','d'], if target = 'z', then return first element in the array('a') - - - EXAMPLES: - INPUT : nums = ['a'.'b','c''g'.'l'], target = 'k' - OUTPUT: 'l' - - INPUT : nums = ['a'.'b','c''g'.'l'], target = 'l' - OUTPUT: 'a' - - APPROACH : - Approach will be similar to that of ceil of target except we don't need to check for equality. - - We will implement this problem using BinarySearch since the array is sorted. - - */ - - - -public class CeilLetter{ - public static int ceil(char[] arr,int target){ - int start = 0,end = arr.length-1; - while(start <=end){ - int mid = start +(end-start)/2; - if(arr[mid] > target){ - end = mid-1; - } - else{ - start = mid +1; - } - } - return start % arr.length ; // returns the first element if no element is greater than the target. - } - - public static void main(String[] args){ - - char[] arr = {'a','c','d','h','m'}; - int target = 'm'; - int index= ceil(arr,target); - System.out.println(arr[index]); -} - } \ No newline at end of file diff --git a/Binary Search/peak_index_in_array.cpp b/Binary Search/peak_index_in_array.cpp deleted file mode 100644 index e8e3352c..00000000 --- a/Binary Search/peak_index_in_array.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - Questions:- An array arr a mountain if the following properties hold: - - 1.)arr.length >= 3 - 2.)There exists some i with 0 < i < arr.length - 1 such that: - 1.)arr[0] < arr[1] < ... < arr[i - 1] < arr[i] - 2.)arr[i] > arr[i + 1] > ... > arr[arr.length - 1] - Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] - < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. - - You must solve it in O(log(arr.length)) time complexity. - -Example 1: - -Input: arr = [0,1,0] -Output: 1 -Example 2: - -Input: arr = [0,2,1,0] -Output: 1 -Example 3: - -Input: arr = [0,10,5,2] -Output: 1 - - -Constraints: - -3 <= arr.length <= 105 -0 <= arr[i] <= 106 -arr is guaranteed to be a mountain array. -*/ - - class Solution { - public: - int peakIndexInMountainArray(vector& arr) { - int m=*max_element(arr.begin(),arr.end()); - int n=arr.size(); - int lo=0; - int hi=n-1; - while(lo<=hi){ - int mid=(lo+hi)/2; - if(arr[mid]>arr[mid+1]&&arr[mid]>arr[mid-1]){ - return mid; - } - if(mid-1<0&&arr[mid]n-1&&arr[mid]arr[mid+1]){ - hi=mid-1; - } - else if(arr[mid]>arr[mid-1]&&arr[mid] Date: Wed, 20 Sep 2023 22:17:35 +0530 Subject: [PATCH 1780/1894] refactor --- Stacks/max_ar_histogram.cpp | 92 ----------------------------- sorting/Heap_sort_implementation.py | 37 ++++++------ 2 files changed, 19 insertions(+), 110 deletions(-) delete mode 100644 Stacks/max_ar_histogram.cpp diff --git a/Stacks/max_ar_histogram.cpp b/Stacks/max_ar_histogram.cpp deleted file mode 100644 index 2154b8ba..00000000 --- a/Stacks/max_ar_histogram.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/*Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, -return the area of the largest rectangle in the histogram - -sample Input -1.Input: heights = [2,1,5,6,2,3] -Output: 10 -Explanation: The output represents the maximum area of a rectangle that can be formed using the heights in the given list. -The maximum area is achieved by selecting heights [2, 5, 6, 2], forming a rectangle of width 4 and height 2, resulting in -an area of 4 * 2 = 10. - -2.Input: heights = [2,4] -Output: 4 - - -Code LOGIC : -this code uses two stacks to find the left and right boundaries of each rectangle in the histogram. It then calculates the areas for each -rectangle and returns the maximum area found. - -Here's an explanation of the code: - -1.The largestRectangleArea function takes a vector a as input and returns an integer representing the largest rectangular area. - -2.The first step is to initialize some variables and containers. The variable n is assigned the size of the input vector a. If the size is 1, -the function immediately returns the single element as the largest area. - -3.Two additional vectors, l and r, are created to store the indices of the left and right boundaries of each rectangle. Two stacks, s1 and s2, -are used to keep track of elements and their corresponding indices. - -4.The first loop iterates through the elements of the vector a from left to right. For each element, it compares its value with the top element of s1. -If the top element is greater than or equal to the current element, it is popped from the stack until the stack is empty or the top element is smaller. -The index of the top element at the point of popping is assigned as the left boundary of the current element (stored in l). If the stack is empty after -the popping, it means there is no smaller element on the left, so -1 is assigned as the left boundary. Finally, the current element and its index are pushed onto s1. - -5.The second loop iterates through the elements of the vector a from right to left. It performs a similar operation as the first loop but using s2 instead of s1. -The right boundary indices are assigned to the vector r in this loop. - -6.After obtaining the left and right boundaries for each element, a new vector ans is created to store the areas of the rectangles. The area for each element is calculated -as the height of the rectangle (the value of the element) multiplied by the width (the difference between the right and left boundaries minus 1). - -7.The max_element function is used to find the maximum value in the ans vector, representing the largest area. This value is stored in the variable h. - -8.The function returns h, which is the largest rectangular area found in the histogram - -TIME and SPACE complexity -The time complexity of the code is O(n) because it involves iterating through the input vector a once, where n is the size of the vector. The space complexity is also O(n) because the code uses additional stacks and vectors to store intermediate results, each with a maximum size of n. -*/ - -class Solution { -public: - int largestRectangleArea(vector& a) { - int n = a.size(); - if(n==1){ - return a[0]; - } - vector l(n); vector r(n); - stack> s1; - stack> s2; - - for(int i=0;i 0 && (s1.top().first >= a[i])){ - s1.pop(); - } - if(s1.size()==0) l[i] = -1; - else l[i] = (s1.top().second); - - s1.push(make_pair(a[i],i)); - } - - - for(int i=a.size()-1;i>=0;i--){ - while(s2.size() > 0 && (s2.top().first >= a[i])){ - s2.pop(); - } - if(s2.size()==0) r[i] = (n); - else r[i] = (s2.top().second); - - s2.push(make_pair(a[i],i)); - } - - vector ans(n); - //int ans = -1; - for(int i=0 ;i Date: Thu, 21 Sep 2023 22:25:32 +0530 Subject: [PATCH 1781/1894] refactor naming --- sorting/bubble_sort.class | Bin 745 -> 0 bytes sorting/bucket_sort_implementation.cpp | 66 ------------------ sorting/{DutchNationalFlag.go => dnf.go} | 0 sorting/{DutchNationalFlag.java => dnf.java} | 0 ...{dutch_national_flag_problem.js => dnf.js} | 0 ...{dutch_national_flag_problem.py => dnf.py} | 0 6 files changed, 66 deletions(-) delete mode 100644 sorting/bubble_sort.class delete mode 100644 sorting/bucket_sort_implementation.cpp rename sorting/{DutchNationalFlag.go => dnf.go} (100%) rename sorting/{DutchNationalFlag.java => dnf.java} (100%) rename sorting/{dutch_national_flag_problem.js => dnf.js} (100%) rename sorting/{dutch_national_flag_problem.py => dnf.py} (100%) diff --git a/sorting/bubble_sort.class b/sorting/bubble_sort.class deleted file mode 100644 index 62afe78afe1491062a825eab65325eee7a35e256..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 745 zcmZuu%Wl&^6g?B$apJgiNJ&aaOlexE<3hYEAVPUmLP81{$taQw5;%!fxg>VwI7r?1 zAJ`)#*02DCP?s#&^D~Io9R~!6YDV`lbMHB4=6?GA{t&=5oYRnlq(auAAkV;e{inV? z@}nKw>F)-Elp)^eEw|Ye! z!@LTv<2cIyz`OgCG#C?VJf+r3HzN*X`(6@8shcK&Kfa>j1S%@3Iu>#AclR_6NA`^* z@%JYTg*2wxFxp|L3c?vorhj%$7^hHI(a>SwG{eFXJPhidU>!vy#QYzk)nkyi;$grr z-wmVS?sVJ_lKVcroMFyQ{lSwv{@$-#9{VBTkeZ``G&i0mgWy&un)zS<*A~jKOdp)1 z(Et*dm$_(<1ykfltdqn}m8M5LUsG%t4L9r-(Mr{iDE$gr&U2W9m;d5M;HjR2? zC_>XR+Lj?dZoj}Hg&VSEWT_);MRpD(_VUN)gB;n9f+&{}Sh&FMoX3Ee01nY8@ At^fc4 diff --git a/sorting/bucket_sort_implementation.cpp b/sorting/bucket_sort_implementation.cpp deleted file mode 100644 index bbdcb8a7..00000000 --- a/sorting/bucket_sort_implementation.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem. -Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently? -A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn. -Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers. -The idea is to use bucket sort. Following is bucket algorithm. - -bucketSort(arr[], n) -1) Create n empty buckets (Or lists). -2) Do following for every array element arr[i]. -.......a) Insert arr[i] into bucket[n*array[i]] -3) Sort individual buckets using insertion sort. -4) Concatenate all sorted buckets. - - - - //TIME COMPLEXITY: O(N) - //SPACE COMPLEXITY: O(N) -*/ - -// C++ program to sort an -// array using bucket sort -#include -#include -#include -using namespace std; - -// Function to sort arr[] of -// size n using bucket sort -void bucketSort(float arr[], int n) -{ - - // 1) Create n empty buckets - vector b[n]; - - // 2) Put array elements - // in different buckets - for (int i = 0; i < n; i++) { - int bi = n * arr[i]; // Index in bucket - b[bi].push_back(arr[i]); - } - - // 3) Sort individual buckets - for (int i = 0; i < n; i++) - sort(b[i].begin(), b[i].end()); - - // 4) Concatenate all buckets into arr[] - int index = 0; - for (int i = 0; i < n; i++) - for (int j = 0; j < b[i].size(); j++) - arr[index++] = b[i][j]; -} - -/* Driver program to test above function */ -int main() -{ - float arr[] - = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; - int n = sizeof(arr) / sizeof(arr[0]); - bucketSort(arr, n); - - cout << "Sorted array is \n"; - for (int i = 0; i < n; i++) - cout << arr[i] << " "; - return 0; -} \ No newline at end of file diff --git a/sorting/DutchNationalFlag.go b/sorting/dnf.go similarity index 100% rename from sorting/DutchNationalFlag.go rename to sorting/dnf.go diff --git a/sorting/DutchNationalFlag.java b/sorting/dnf.java similarity index 100% rename from sorting/DutchNationalFlag.java rename to sorting/dnf.java diff --git a/sorting/dutch_national_flag_problem.js b/sorting/dnf.js similarity index 100% rename from sorting/dutch_national_flag_problem.js rename to sorting/dnf.js diff --git a/sorting/dutch_national_flag_problem.py b/sorting/dnf.py similarity index 100% rename from sorting/dutch_national_flag_problem.py rename to sorting/dnf.py From 3a17c73c7d4bb0a654bb4c26eeb462b78b990bd2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 21 Sep 2023 22:27:46 +0530 Subject: [PATCH 1782/1894] add dnf in c++ --- sorting/dnf.c++ | 75 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 sorting/dnf.c++ diff --git a/sorting/dnf.c++ b/sorting/dnf.c++ new file mode 100644 index 00000000..98f373f3 --- /dev/null +++ b/sorting/dnf.c++ @@ -0,0 +1,75 @@ +/* + +The Dutch National Flag algorithm is used to sort an array containing elements with values of 0, 1, and 2. The goal is to rearrange the elements in-place so that all the 0s are grouped at the beginning, followed by all the 1s, and finally all the 2s. + +The algorithm uses three pointers: low, mid, and high. The low pointer represents the boundary of the 0s section, the mid pointer scans the array, and the high pointer represents the boundary of the 2s section. + +The algorithm iterates through the array and performs the following operations: + + 1. If the element at the mid pointer is 0, it is swapped with the element at the low pointer, and both pointers are incremented. + 2. If the element at the mid pointer is 1, it is already in the correct section, so the mid pointer is simply incremented. + 3. If the element at the mid pointer is 2, it is swapped with the element at the high pointer, and the high pointer is decremented. + +The iteration continues until the mid pointer crosses the high pointer, indicating that all elements have been processed. + +After the algorithm finishes, the array will be sorted according to the Dutch National Flag problem requirements, with all 0s at the beginning, followed by 1s, and finally 2s. The sorting is done in-place, meaning it does not require any additional space. + +The time complexity of the Dutch National Flag algorithm is O(n), where n is the length of the array, as we only need to iterate through the array once. The space complexity is O(1) since no extra space is used apart from the input array. + +Consider an array: [1, 2, 0, 2, 1, 0]. + +The algorithm uses three pointers: low, mid, and high. Initially, low = 0, mid = 0, and high = 5. + + Iterate while mid <= high: + If the element at mid is 0, swap it with the element at low, increment both low and mid. + If the element at mid is 1, increment mid. + If the element at mid is 2, swap it with the element at high, decrement high. + +After applying the algorithm, the sorted array will be: [0, 0, 1, 1, 2, 2]. + +In this example, the algorithm moves all the 0s to the beginning, followed by the 1s, and finally the 2s, achieving the desired sorting according to the Dutch National Flag problem requirements. +*/ + +#include +#include + +std::vector DutchNationalFlag(std::vector& array) { + int low = 0; // Initialize the low pointer to the beginning of the array + int mid = 0; // Initialize the mid pointer to the beginning of the array + int high = array.size() - 1; // Initialize the high pointer to the end of the array + + while (mid <= high) { + switch (array[mid]) { + case 0: + // If the value at mid is 0, swap it with the value at low + std::swap(array[low], array[mid]); + low++; // Increment low to move forward + mid++; // Increment mid to move forward + break; + case 1: + // If the value at mid is 1, no swapping needed, just move mid forward + mid++; + break; + case 2: + // If the value at mid is 2, swap it with the value at high + std::swap(array[mid], array[high]); + high--; // Decrement high to move backward + break; + } + } + + return array; +} + +int main() { + std::vector array = {2, 0, 1, 1, 0, 2, 2, 1, 0}; + std::vector sortedArray = DutchNationalFlag(array); + + std::cout << "Sorted Array: "; + for (int64_t num : sortedArray) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} From f99c2d012d6eed9e867c51c0db6e9b5d37614d67 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 21 Sep 2023 22:28:00 +0530 Subject: [PATCH 1783/1894] rename and refactor --- sorting/{dnf.c++ => dnf.cpp} | 0 sorting/heapSort.cpp | 66 ------------------- ...ap_sort_implementation.py => heap_sort.py} | 0 3 files changed, 66 deletions(-) rename sorting/{dnf.c++ => dnf.cpp} (100%) delete mode 100644 sorting/heapSort.cpp rename sorting/{Heap_sort_implementation.py => heap_sort.py} (100%) diff --git a/sorting/dnf.c++ b/sorting/dnf.cpp similarity index 100% rename from sorting/dnf.c++ rename to sorting/dnf.cpp diff --git a/sorting/heapSort.cpp b/sorting/heapSort.cpp deleted file mode 100644 index 649790d2..00000000 --- a/sorting/heapSort.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/*This implementation uses a vector to store the elements to be sorted. The heapify function is used to create a max heap and maintain the heap property. The heapSort function performs the heap sort algorithm by repeatedly extracting the maximum element from the heap. Finally, the printArray function is a utility function to print the elements of an array.*/ -/* time complexity O(n log n) - Space complexity O(1) */ -#include -#include - -using namespace std; - -void heapify(vector& arr, int n, int i) { - int largest = i; // Initialize largest as root - int left = 2 * i + 1; // Left child - int right = 2 * i + 2; // Right child - - // If left child is larger than root - if (left < n && arr[left] > arr[largest]) - largest = left; - - // If right child is larger than largest so far - if (right < n && arr[right] > arr[largest]) - largest = right; - - // If largest is not root - if (largest != i) { - swap(arr[i], arr[largest]); - - // Recursively heapify the affected sub-tree - heapify(arr, n, largest); - } -} - -void heapSort(vector& arr) { - int n = arr.size(); - - // Build heap (rearrange array) - for (int i = n / 2 - 1; i >= 0; i--) - heapify(arr, n, i); - - // One by one extract an element from heap - for (int i = n - 1; i > 0; i--) { - // Move current root to end - swap(arr[0], arr[i]); - - // call max heapify on the reduced heap - heapify(arr, i, 0); - } -} - -// Utility function to print an array -void printArray(const vector& arr) { - for (int i = 0; i < arr.size(); ++i) - cout << arr[i] << " "; - cout << endl; -} - -int main() { - vector arr = {12, 11, 13, 5, 6, 7}; - cout << "Original array: "; - printArray(arr); - - heapSort(arr); - - cout << "Sorted array: "; - printArray(arr); - - return 0; -} diff --git a/sorting/Heap_sort_implementation.py b/sorting/heap_sort.py similarity index 100% rename from sorting/Heap_sort_implementation.py rename to sorting/heap_sort.py From 23e1a942c86bd9ec377224b4fce029321ec232cb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 22 Sep 2023 22:37:59 +0530 Subject: [PATCH 1784/1894] add first true --- Binary Search/first_true.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Binary Search/first_true.java diff --git a/Binary Search/first_true.java b/Binary Search/first_true.java new file mode 100644 index 00000000..490070af --- /dev/null +++ b/Binary Search/first_true.java @@ -0,0 +1,22 @@ +public import java.util.Arrays; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Collectors; + +class Solution { + public static int findBoundary(List arr) { + int low = 0; + int high = arr.size() - 1; + int bv = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr.get(mid) == false) { + low = mid + 1; + } else { + bv = mid; + high = mid - 1; + } + } + return bv; + } +} From dba7fa7685a9f5d175c0e7237441cbdd419ede8e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 22 Sep 2023 22:38:56 +0530 Subject: [PATCH 1785/1894] add comments --- Binary Search/first_true.java | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Binary Search/first_true.java b/Binary Search/first_true.java index 490070af..a54f352c 100644 --- a/Binary Search/first_true.java +++ b/Binary Search/first_true.java @@ -5,18 +5,27 @@ class Solution { public static int findBoundary(List arr) { - int low = 0; - int high = arr.size() - 1; - int bv = -1; + int low = 0; // Initialize the low pointer to the beginning of the list. + int high = arr.size() - 1; // Initialize the high pointer to the end of the list. + int bv = -1; // Initialize bv (boundary value) to -1. + while (low <= high) { - int mid = low + (high - low) / 2; + int mid = low + (high - low) / 2; // Calculate the middle index. + if (arr.get(mid) == false) { - low = mid + 1; + // If the element at the middle index is 'false', + // it means that the last 'true' value should be on the right side. + low = mid + 1; // Move the low pointer to the right of mid. } else { - bv = mid; - high = mid - 1; + // If the element at the middle index is 'true', + // update bv to the current middle index and continue searching on the left side. + bv = mid; // Update bv to the current middle index. + high = mid - 1; // Move the high pointer to the left of mid. } } + + // The loop ends when low > high, indicating that the search is complete. + // bv contains the index of the last 'true' value encountered. return bv; } } From 17902982e246b919b706041eb87231c6a327b88c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 22 Sep 2023 22:39:54 +0530 Subject: [PATCH 1786/1894] add question --- Binary Search/first_true.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Binary Search/first_true.java b/Binary Search/first_true.java index a54f352c..0c3d3380 100644 --- a/Binary Search/first_true.java +++ b/Binary Search/first_true.java @@ -1,3 +1,13 @@ +/* + An array of boolean values is divided into two sections; the left section consists of all false and the + right section consists of all true. Find the First True in a Sorted Boolean Array of the + right section, i.e. the index of the first true element. If there is no true element, return -1. + + Input: arr = [false, false, true, true, true] + Output: 2 + + Explanation: first true's index is 2. +*/ public import java.util.Arrays; import java.util.List; import java.util.Scanner; From 0479b65c0edf76542ea6ee108e53a36cf1631801 Mon Sep 17 00:00:00 2001 From: Abhinav kumar <126642111+Abhinavcode13@users.noreply.github.com> Date: Sat, 23 Sep 2023 11:24:39 +0530 Subject: [PATCH 1787/1894] Create Jobassign.cpp --- Arrays/Jobassign.cpp | 95 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Arrays/Jobassign.cpp diff --git a/Arrays/Jobassign.cpp b/Arrays/Jobassign.cpp new file mode 100644 index 00000000..ddda1007 --- /dev/null +++ b/Arrays/Jobassign.cpp @@ -0,0 +1,95 @@ +#include +#include + +#define N 4 // Number of workers and tasks + +void hungarianAlgorithm(int costMatrix[N][N]); + +int main() { + int costMatrix[N][N] = { + {9, 2, 7, 8}, + {6, 4, 3, 7}, + {5, 8, 1, 8}, + {7, 6, 9, 4} + }; + + hungarianAlgorithm(costMatrix); + + return 0; +} + +void hungarianAlgorithm(int costMatrix[N][N]) { + int i, j; + int numWorkers = N, numTasks = N; + + int minCost, minCostIdx; + int rowCover[N] = {0}; + int colCover[N] = {0}; + int assignment[N][2] = {0}; // Stores the assignment + + // Step 1: Subtract the smallest value in each row from all elements in that row + for (i = 0; i < numWorkers; i++) { + minCost = INT_MAX; + for (j = 0; j < numTasks; j++) { + if (costMatrix[i][j] < minCost) { + minCost = costMatrix[i][j]; + } + } + for (j = 0; j < numTasks; j++) { + costMatrix[i][j] -= minCost; + } + } + + // Step 2: Find a zero in the cost matrix and mark the row and column + for (i = 0; i < numWorkers; i++) { + for (j = 0; j < numTasks; j++) { + if (costMatrix[i][j] == 0 && !rowCover[i] && !colCover[j]) { + assignment[i][0] = i; + assignment[i][1] = j; + rowCover[i] = 1; + colCover[j] = 1; + } + } + } + + // Step 3: Check if all rows are covered + int rowCoveredCount = 0; + for (i = 0; i < numWorkers; i++) { + rowCoveredCount += rowCover[i]; + } + + if (rowCoveredCount == numWorkers) { + // All rows are covered, we have the optimal assignment + printf("Optimal Assignment:\n"); + for (i = 0; i < numWorkers; i++) { + printf("Worker %d -> Task %d\n", assignment[i][0] + 1, assignment[i][1] + 1); + } + return; + } else { + // Proceed to step 4 + } + + // Step 4: Find the minimum uncovered value (minCost) in the cost matrix + minCost = INT_MAX; + for (i = 0; i < numWorkers; i++) { + for (j = 0; j < numTasks; j++) { + if (!rowCover[i] && !colCover[j] && costMatrix[i][j] < minCost) { + minCost = costMatrix[i][j]; + } + } + } + + // Step 5: Subtract minCost from all uncovered elements and add it to all elements at the intersection of covering lines + for (i = 0; i < numWorkers; i++) { + for (j = 0; j < numTasks; j++) { + if (!rowCover[i] && !colCover[j]) { + costMatrix[i][j] -= minCost; + } else if (rowCover[i] && colCover[j]) { + costMatrix[i][j] += minCost; + } + } + } + + // Continue to step 3 + hungarianAlgorithm(costMatrix); +} From 1e9cfb6d7c65a7708dc38773a556375c38878132 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 24 Sep 2023 20:17:14 +0530 Subject: [PATCH 1788/1894] add first ture in c++ --- Binary Search/first_true.cpp | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Binary Search/first_true.cpp diff --git a/Binary Search/first_true.cpp b/Binary Search/first_true.cpp new file mode 100644 index 00000000..6a42a624 --- /dev/null +++ b/Binary Search/first_true.cpp @@ -0,0 +1,44 @@ +/* + An array of boolean values is divided into two sections; the left section consists of all false and the + right section consists of all true. Find the First True in a Sorted Boolean Array of the + right section, i.e. the index of the first true element. If there is no true element, return -1. + + Input: arr = [false, false, true, true, true] + Output: 2 + + Explanation: first true's index is 2. +*/ +#include +#include + +int findBoundary(std::vector& arr) { + int low = 0; // Initialize the low pointer to the beginning of the vector. + int high = arr.size() - 1; // Initialize the high pointer to the end of the vector. + int bv = -1; // Initialize bv (boundary value) to -1. + + while (low <= high) { + int mid = low + (high - low) / 2; // Calculate the middle index. + + if (!arr[mid]) { + // If the element at the middle index is 'false', + // it means that the last 'true' value should be on the right side. + low = mid + 1; // Move the low pointer to the right of mid. + } else { + // If the element at the middle index is 'true', + // update bv to the current middle index and continue searching on the left side. + bv = mid; // Update bv to the current middle index. + high = mid - 1; // Move the high pointer to the left of mid. + } + } + + // The loop ends when low > high, indicating that the search is complete. + // bv contains the index of the last 'true' value encountered. + return bv; +} + +int main() { + std::vector arr = {false, false, false, true, true, true, true}; + int boundary = findBoundary(arr); + std::cout << "Boundary Index: " << boundary << std::endl; + return 0; +} From 2448f97787ed631e9dbc5cefdac6129ba6fda025 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 24 Sep 2023 20:17:19 +0530 Subject: [PATCH 1789/1894] add first ture in go --- Binary Search/first_true.go | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Binary Search/first_true.go diff --git a/Binary Search/first_true.go b/Binary Search/first_true.go new file mode 100644 index 00000000..f39c1e20 --- /dev/null +++ b/Binary Search/first_true.go @@ -0,0 +1,47 @@ +/* + An array of boolean values is divided into two sections; the left section consists of all false and the + right section consists of all true. Find the First True in a Sorted Boolean Array of the + right section, i.e. the index of the first true element. If there is no true element, return -1. + + Input: arr = [false, false, true, true, true] + Output: 2 + + Explanation: first true's index is 2. +*/ + +package main + +import ( + "fmt" +) + +func findBoundary(arr []bool) int { + low := 0 // Initialize the low pointer to the beginning of the slice. + high := len(arr) - 1 // Initialize the high pointer to the end of the slice. + bv := -1 // Initialize bv (boundary value) to -1. + + for low <= high { + mid := low + (high - low) / 2 // Calculate the middle index. + + if !arr[mid] { + // If the element at the middle index is 'false', + // it means that the last 'true' value should be on the right side. + low = mid + 1 // Move the low pointer to the right of mid. + } else { + // If the element at the middle index is 'true', + // update bv to the current middle index and continue searching on the left side. + bv = mid // Update bv to the current middle index. + high = mid - 1 // Move the high pointer to the left of mid. + } + } + + // The loop ends when low > high, indicating that the search is complete. + // bv contains the index of the last 'true' value encountered. + return bv +} + +func main() { + arr := []bool{false, false, false, true, true, true, true} + boundary := findBoundary(arr) + fmt.Println("Boundary Index:", boundary) +} From 06ecabb53bc4fcb0654b4922bb7f3129c34be2b3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 24 Sep 2023 20:17:24 +0530 Subject: [PATCH 1790/1894] add first ture in js --- Binary Search/first_true.js | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Binary Search/first_true.js diff --git a/Binary Search/first_true.js b/Binary Search/first_true.js new file mode 100644 index 00000000..5854e59a --- /dev/null +++ b/Binary Search/first_true.js @@ -0,0 +1,38 @@ +/* + An array of boolean values is divided into two sections; the left section consists of all false and the + right section consists of all true. Find the First True in a Sorted Boolean Array of the + right section, i.e. the index of the first true element. If there is no true element, return -1. + + Input: arr = [false, false, true, true, true] + Output: 2 + + Explanation: first true's index is 2. +*/ +function findBoundary(arr) { + let low = 0; // Initialize the low pointer to the beginning of the array. + let high = arr.length - 1; // Initialize the high pointer to the end of the array. + let bv = -1; // Initialize bv (boundary value) to -1. + + while (low <= high) { + let mid = low + Math.floor((high - low) / 2); // Calculate the middle index. + + if (!arr[mid]) { + // If the element at the middle index is 'false', + // it means that the last 'true' value should be on the right side. + low = mid + 1; // Move the low pointer to the right of mid. + } else { + // If the element at the middle index is 'true', + // update bv to the current middle index and continue searching on the left side. + bv = mid; // Update bv to the current middle index. + high = mid - 1; // Move the high pointer to the left of mid. + } + } + + // The loop ends when low > high, indicating that the search is complete. + // bv contains the index of the last 'true' value encountered. + return bv; +} + +const arr = [false, false, false, true, true, true, true]; +const boundary = findBoundary(arr); +console.log("Boundary Index:", boundary); From f7f546668bc0ee3adbb8153f0c5e04a24fa8bbc3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 24 Sep 2023 20:17:33 +0530 Subject: [PATCH 1791/1894] add first ture in python --- Binary Search/first_true.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Binary Search/first_true.py diff --git a/Binary Search/first_true.py b/Binary Search/first_true.py new file mode 100644 index 00000000..edc140f9 --- /dev/null +++ b/Binary Search/first_true.py @@ -0,0 +1,35 @@ +''' + An array of boolean values is divided into two sections; the left section consists of all false and the + right section consists of all true. Find the First True in a Sorted Boolean Array of the + right section, i.e. the index of the first true element. If there is no true element, return -1. + + Input: arr = [false, false, true, true, true] + Output: 2 + + Explanation: first true's index is 2. +''' +def findBoundary(arr): + low = 0 # Initialize the low pointer to the beginning of the list. + high = len(arr) - 1 # Initialize the high pointer to the end of the list. + bv = -1 # Initialize bv (boundary value) to -1. + + while low <= high: + mid = low + (high - low) // 2 # Calculate the middle index. + + if not arr[mid]: + # If the element at the middle index is 'false', + # it means that the last 'true' value should be on the right side. + low = mid + 1 # Move the low pointer to the right of mid. + else: + # If the element at the middle index is 'true', + # update bv to the current middle index and continue searching on the left side. + bv = mid # Update bv to the current middle index. + high = mid - 1 # Move the high pointer to the left of mid. + + # The loop ends when low > high, indicating that the search is complete. + # bv contains the index of the last 'true' value encountered. + return bv + +arr = [False, False, False, True, True, True, True] +boundary = findBoundary(arr) +print("Boundary Index:", boundary) From 304373b6ae91a6e92f9a4642e6796551dfe37612 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 25 Sep 2023 23:21:58 +0530 Subject: [PATCH 1792/1894] add two colorable in java --- Graphs/two_colorable.java | 89 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 Graphs/two_colorable.java diff --git a/Graphs/two_colorable.java b/Graphs/two_colorable.java new file mode 100644 index 00000000..65399330 --- /dev/null +++ b/Graphs/two_colorable.java @@ -0,0 +1,89 @@ +/* + You're given a list of edges representing a connected, unweighted, undirected graph with at least one node. + Write a function that returns a boolean representing whether the given graph is two-colorable. + + Explanation: + The code snippet implements an algorithm to determine if a given graph is two-colorable or bipartite. A graph is two-colorable if its vertices can be divided into two groups such that no two adjacent vertices have the same color. + + The function `TwoColorable(edges [][]int) bool` takes a 2D array of integers `edges`, representing the edges of the graph. Each row `edges[i]` contains the list of vertices that are connected to vertex `i`. + + The algorithm uses a stack and a map to keep track of the colors assigned to the vertices. It starts by assigning the first vertex (vertex 0) to color true and pushing it onto the stack. + + Then, it performs a depth-first traversal of the graph using the stack. For each vertex popped from the stack, it explores its adjacent vertices. If an adjacent vertex has not been colored yet (not present in the colors map), it assigns the opposite color to it (i.e., `!colors[node]`) and pushes it onto the stack. If the adjacent vertex has already been colored and its color is the same as the current vertex's color, then the graph cannot be two-colorable, and the function returns false. + + If the traversal completes without any conflicts (i.e., no adjacent vertices have the same color), the function returns true, indicating that the graph is two-colorable. + + The algorithm relies on the fact that a graph is two-colorable if and only if it is bipartite, and the two colors represent the two disjoint sets of vertices in the bipartite graph. + + Here's a step-by-step explanation of the algorithm: + + 1. Initialize the `colors` map with the first vertex (0) assigned the color true (representing one group of vertices). + 2. Initialize an empty stack and push the first vertex (0) onto it. + 3. While the stack is not empty, repeat the following steps: + a. Pop the top vertex from the stack (denoted by `node`). + b. For each vertex `connection` connected to `node` (i.e., `edges[node]`), do the following: + i. If `connection` has not been colored yet (not present in the `colors` map), assign it the opposite color of + `node` (i.e., `!colors[node]`) and push it onto the stack. + ii. If `connection` has already been colored and its color is the same as `node`'s color, return false since the + graph is not two-colorable. + 4. If the traversal completes without conflicts, return true, indicating that the graph is two-colorable. + + Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. + If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + + O(v + e) time | O(v) space - where v is the number of vertices and e is the number of edges in the graph + +*/ +import java.util.*; + +public class TwoColorable { + + public static boolean isTwoColorable(List> edges) { + // colors keeps track of the colors assigned to each vertex. + // We start by assigning the first vertex (0) the color true (denoted by 0: true). + Map colors = new HashMap<>(); + colors.put(0, true); + + // stack is used for depth-first traversal of the graph. + Stack stack = new Stack<>(); + stack.push(0); + + while (!stack.isEmpty()) { + // Pop the top vertex from the stack (denoted by 'node'). + int node = stack.pop(); + + // Explore adjacent vertices (connections) of the current vertex 'node'. + for (int connection : edges.get(node)) { + // If the adjacent vertex has not been colored yet (not present in the 'colors' map), + // assign it the opposite color of the current vertex (denoted by '!colors.get(node)'), + // and push it onto the stack. + if (!colors.containsKey(connection)) { + colors.put(connection, !colors.get(node)); + stack.push(connection); + } else { + // If the adjacent vertex has already been colored and its color is the same as the current vertex's color, + // then the graph cannot be two-colorable, return false. + if (colors.get(connection) == colors.get(node)) { + return false; + } + } + } + } + + // If the traversal completes without any conflicts (no adjacent vertices have the same color), + // return true, indicating that the graph is two-colorable. + return true; + } + + public static void main(String[] args) { + List> edges = new ArrayList<>(); + edges.add(Arrays.asList(1, 2)); + edges.add(Arrays.asList(0, 3)); + edges.add(Arrays.asList(0, 4)); + edges.add(Arrays.asList(1)); + edges.add(Arrays.asList(2)); + + boolean isTwoColorable = isTwoColorable(edges); + System.out.println("Is Two-Colorable: " + isTwoColorable); + } +} From 4ba9ed56e4c8ace91ab9bc98bd446ef9963f58ed Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 25 Sep 2023 23:22:50 +0530 Subject: [PATCH 1793/1894] add two colorable in python --- Graphs/two_colorable.py | 70 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Graphs/two_colorable.py diff --git a/Graphs/two_colorable.py b/Graphs/two_colorable.py new file mode 100644 index 00000000..b3f9f835 --- /dev/null +++ b/Graphs/two_colorable.py @@ -0,0 +1,70 @@ +''' + You're given a list of edges representing a connected, unweighted, undirected graph with at least one node. + Write a function that returns a boolean representing whether the given graph is two-colorable. + + Explanation: + The code snippet implements an algorithm to determine if a given graph is two-colorable or bipartite. A graph is two-colorable if its vertices can be divided into two groups such that no two adjacent vertices have the same color. + + The function `TwoColorable(edges [][]int) bool` takes a 2D array of integers `edges`, representing the edges of the graph. Each row `edges[i]` contains the list of vertices that are connected to vertex `i`. + + The algorithm uses a stack and a map to keep track of the colors assigned to the vertices. It starts by assigning the first vertex (vertex 0) to color true and pushing it onto the stack. + + Then, it performs a depth-first traversal of the graph using the stack. For each vertex popped from the stack, it explores its adjacent vertices. If an adjacent vertex has not been colored yet (not present in the colors map), it assigns the opposite color to it (i.e., `!colors[node]`) and pushes it onto the stack. If the adjacent vertex has already been colored and its color is the same as the current vertex's color, then the graph cannot be two-colorable, and the function returns false. + + If the traversal completes without any conflicts (i.e., no adjacent vertices have the same color), the function returns true, indicating that the graph is two-colorable. + + The algorithm relies on the fact that a graph is two-colorable if and only if it is bipartite, and the two colors represent the two disjoint sets of vertices in the bipartite graph. + + Here's a step-by-step explanation of the algorithm: + + 1. Initialize the `colors` map with the first vertex (0) assigned the color true (representing one group of vertices). + 2. Initialize an empty stack and push the first vertex (0) onto it. + 3. While the stack is not empty, repeat the following steps: + a. Pop the top vertex from the stack (denoted by `node`). + b. For each vertex `connection` connected to `node` (i.e., `edges[node]`), do the following: + i. If `connection` has not been colored yet (not present in the `colors` map), assign it the opposite color of + `node` (i.e., `!colors[node]`) and push it onto the stack. + ii. If `connection` has already been colored and its color is the same as `node`'s color, return false since the + graph is not two-colorable. + 4. If the traversal completes without conflicts, return true, indicating that the graph is two-colorable. + + Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. + If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + + O(v + e) time | O(v) space - where v is the number of vertices and e is the number of edges in the graph + +''' +def is_two_colorable(edges): + # colors keeps track of the colors assigned to each vertex. + # We start by assigning the first vertex (0) the color True (denoted by 0: True). + colors = {0: True} + + # stack is used for depth-first traversal of the graph. + stack = [0] + + while stack: + # Pop the top vertex from the stack (denoted by 'node'). + node = stack.pop() + + # Explore adjacent vertices (connections) of the current vertex 'node'. + for connection in edges[node]: + # If the adjacent vertex has not been colored yet (not present in the 'colors' dictionary), + # assign it the opposite color of the current vertex (denoted by not colors[node]), + # and push it onto the stack. + if connection not in colors: + colors[connection] = not colors[node] + stack.append(connection) + else: + # If the adjacent vertex has already been colored and its color is the same as the current vertex's color, + # then the graph cannot be two-colorable, return False. + if colors[connection] == colors[node]: + return False + + # If the traversal completes without any conflicts (no adjacent vertices have the same color), + # return True, indicating that the graph is two-colorable. + return True + +# Example usage +edges = [[1, 2], [0, 3], [0, 4], [1], [2]] +is_two_colorable_result = is_two_colorable(edges) +print("Is Two-Colorable:", is_two_colorable_result) From 2d729259473c87a6dbd3ddb781758e0158ae1655 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 25 Sep 2023 23:24:58 +0530 Subject: [PATCH 1794/1894] add two colorable in c++ --- Graphs/two_colorable.cpp | 85 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Graphs/two_colorable.cpp diff --git a/Graphs/two_colorable.cpp b/Graphs/two_colorable.cpp new file mode 100644 index 00000000..a3443fa7 --- /dev/null +++ b/Graphs/two_colorable.cpp @@ -0,0 +1,85 @@ +/* + You're given a list of edges representing a connected, unweighted, undirected graph with at least one node. + Write a function that returns a boolean representing whether the given graph is two-colorable. + + Explanation: + The code snippet implements an algorithm to determine if a given graph is two-colorable or bipartite. A graph is two-colorable if its vertices can be divided into two groups such that no two adjacent vertices have the same color. + + The function `TwoColorable(edges [][]int) bool` takes a 2D array of integers `edges`, representing the edges of the graph. Each row `edges[i]` contains the list of vertices that are connected to vertex `i`. + + The algorithm uses a stack and a map to keep track of the colors assigned to the vertices. It starts by assigning the first vertex (vertex 0) to color true and pushing it onto the stack. + + Then, it performs a depth-first traversal of the graph using the stack. For each vertex popped from the stack, it explores its adjacent vertices. If an adjacent vertex has not been colored yet (not present in the colors map), it assigns the opposite color to it (i.e., `!colors[node]`) and pushes it onto the stack. If the adjacent vertex has already been colored and its color is the same as the current vertex's color, then the graph cannot be two-colorable, and the function returns false. + + If the traversal completes without any conflicts (i.e., no adjacent vertices have the same color), the function returns true, indicating that the graph is two-colorable. + + The algorithm relies on the fact that a graph is two-colorable if and only if it is bipartite, and the two colors represent the two disjoint sets of vertices in the bipartite graph. + + Here's a step-by-step explanation of the algorithm: + + 1. Initialize the `colors` map with the first vertex (0) assigned the color true (representing one group of vertices). + 2. Initialize an empty stack and push the first vertex (0) onto it. + 3. While the stack is not empty, repeat the following steps: + a. Pop the top vertex from the stack (denoted by `node`). + b. For each vertex `connection` connected to `node` (i.e., `edges[node]`), do the following: + i. If `connection` has not been colored yet (not present in the `colors` map), assign it the opposite color of + `node` (i.e., `!colors[node]`) and push it onto the stack. + ii. If `connection` has already been colored and its color is the same as `node`'s color, return false since the + graph is not two-colorable. + 4. If the traversal completes without conflicts, return true, indicating that the graph is two-colorable. + + Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. + If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + + O(v + e) time | O(v) space - where v is the number of vertices and e is the number of edges in the graph + +*/ +#include +#include +#include +#include + +bool isTwoColorable(std::vector>& edges) { + // colors keeps track of the colors assigned to each vertex. + // We start by assigning the first vertex (0) the color true (denoted by 0: true). + std::unordered_map colors; + colors[0] = true; + + // stack is used for depth-first traversal of the graph. + std::stack stack; + stack.push(0); + + while (!stack.empty()) { + // Pop the top vertex from the stack (denoted by 'node'). + int node = stack.top(); + stack.pop(); + + // Explore adjacent vertices (connections) of the current vertex 'node'. + for (int connection : edges[node]) { + // If the adjacent vertex has not been colored yet (not present in the 'colors' map), + // assign it the opposite color of the current vertex (denoted by !colors[node]), + // and push it onto the stack. + if (colors.find(connection) == colors.end()) { + colors[connection] = !colors[node]; + stack.push(connection); + } else { + // If the adjacent vertex has already been colored and its color is the same as the current vertex's color, + // then the graph cannot be two-colorable, return false. + if (colors[connection] == colors[node]) { + return false; + } + } + } + } + + // If the traversal completes without any conflicts (no adjacent vertices have the same color), + // return true, indicating that the graph is two-colorable. + return true; +} + +int main() { + std::vector> edges = {{1, 2}, {0, 3}, {0, 4}, {1}, {2}}; + bool isTwoColorableResult = isTwoColorable(edges); + std::cout << "Is Two-Colorable: " << std::boolalpha << isTwoColorableResult << std::endl; + return 0; +} From a2b965a470de53dbf6ac347f04ab22f09e153114 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 25 Sep 2023 23:26:30 +0530 Subject: [PATCH 1795/1894] add two colorable in javascript --- Graphs/two_colorable.js | 76 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Graphs/two_colorable.js diff --git a/Graphs/two_colorable.js b/Graphs/two_colorable.js new file mode 100644 index 00000000..f7392768 --- /dev/null +++ b/Graphs/two_colorable.js @@ -0,0 +1,76 @@ +/* + You're given a list of edges representing a connected, unweighted, undirected graph with at least one node. + Write a function that returns a boolean representing whether the given graph is two-colorable. + + Explanation: + The code snippet implements an algorithm to determine if a given graph is two-colorable or bipartite. A graph is two-colorable if its vertices can be divided into two groups such that no two adjacent vertices have the same color. + + The function `TwoColorable(edges [][]int) bool` takes a 2D array of integers `edges`, representing the edges of the graph. Each row `edges[i]` contains the list of vertices that are connected to vertex `i`. + + The algorithm uses a stack and a map to keep track of the colors assigned to the vertices. It starts by assigning the first vertex (vertex 0) to color true and pushing it onto the stack. + + Then, it performs a depth-first traversal of the graph using the stack. For each vertex popped from the stack, it explores its adjacent vertices. If an adjacent vertex has not been colored yet (not present in the colors map), it assigns the opposite color to it (i.e., `!colors[node]`) and pushes it onto the stack. If the adjacent vertex has already been colored and its color is the same as the current vertex's color, then the graph cannot be two-colorable, and the function returns false. + + If the traversal completes without any conflicts (i.e., no adjacent vertices have the same color), the function returns true, indicating that the graph is two-colorable. + + The algorithm relies on the fact that a graph is two-colorable if and only if it is bipartite, and the two colors represent the two disjoint sets of vertices in the bipartite graph. + + Here's a step-by-step explanation of the algorithm: + + 1. Initialize the `colors` map with the first vertex (0) assigned the color true (representing one group of vertices). + 2. Initialize an empty stack and push the first vertex (0) onto it. + 3. While the stack is not empty, repeat the following steps: + a. Pop the top vertex from the stack (denoted by `node`). + b. For each vertex `connection` connected to `node` (i.e., `edges[node]`), do the following: + i. If `connection` has not been colored yet (not present in the `colors` map), assign it the opposite color of + `node` (i.e., `!colors[node]`) and push it onto the stack. + ii. If `connection` has already been colored and its color is the same as `node`'s color, return false since the + graph is not two-colorable. + 4. If the traversal completes without conflicts, return true, indicating that the graph is two-colorable. + + Note: The algorithm assumes that the graph is connected, meaning there is a path from any vertex to any other vertex. + If the graph is not connected, the algorithm will only determine whether the connected component containing vertex 0 is two-colorable. + + O(v + e) time | O(v) space - where v is the number of vertices and e is the number of edges in the graph + +*/ +function isTwoColorable(edges) { + // colors keeps track of the colors assigned to each vertex. + // We start by assigning the first vertex (0) the color true (denoted by 0: true). + const colors = new Map(); + colors.set(0, true); + + // stack is used for depth-first traversal of the graph. + const stack = [0]; + + while (stack.length > 0) { + // Pop the top vertex from the stack (denoted by 'node'). + const node = stack.pop(); + + // Explore adjacent vertices (connections) of the current vertex 'node'. + for (const connection of edges[node]) { + // If the adjacent vertex has not been colored yet (not present in the 'colors' map), + // assign it the opposite color of the current vertex (denoted by !colors.get(node)), + // and push it onto the stack. + if (!colors.has(connection)) { + colors.set(connection, !colors.get(node)); + stack.push(connection); + } else { + // If the adjacent vertex has already been colored and its color is the same as the current vertex's color, + // then the graph cannot be two-colorable, return false. + if (colors.get(connection) === colors.get(node)) { + return false; + } + } + } + } + + // If the traversal completes without any conflicts (no adjacent vertices have the same color), + // return true, indicating that the graph is two-colorable. + return true; +} + +// Example usage +const edges = [[1, 2], [0, 3], [0, 4], [1], [2]]; +const isTwoColorableResult = isTwoColorable(edges); +console.log("Is Two-Colorable:", isTwoColorableResult); From 5b0b3d19751792f6fb3010ac99cecbf48b391d76 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 26 Sep 2023 22:12:04 +0530 Subject: [PATCH 1796/1894] add validate bst in go --- Graphs/Validate_BST.cpp | 105 ---------------------------------------- Graphs/validate_bst.go | 35 ++++++++++++++ 2 files changed, 35 insertions(+), 105 deletions(-) delete mode 100644 Graphs/Validate_BST.cpp create mode 100644 Graphs/validate_bst.go diff --git a/Graphs/Validate_BST.cpp b/Graphs/Validate_BST.cpp deleted file mode 100644 index 30d6fb81..00000000 --- a/Graphs/Validate_BST.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/*Name : Abhinav kumar -Github username : Abhinavcode13 -Repository name : data-structures-and-algorithms -Problem : Validate BST in C++ -Issue Number : #1187 -Problem statement : - -Explanation of the below C++ code : - -First, we define the TreeNode structure, which represents a node in the BST. It has three members: val to store the node's value, and left and right pointers to the left and right child nodes, respectively. - -The isValidBSTHelper function is a recursive helper function that takes a TreeNode* as input along with the minimum and maximum values that the node's value should fall between. It performs the following checks: - -If the node is nullptr, it means we have reached the end of a subtree, so we return true (since an empty subtree is considered a valid BST). -If the node's value is less than or equal to the minimum value or greater than or equal to the maximum value, it violates the BST property, so we return false. -We recursively call isValidBSTHelper for the left and right subtrees, updating the minimum and maximum values accordingly. If both subtrees return true, the current subtree is a valid BST, so we return true. -The isValidBST function is the main function that calls the isValidBSTHelper function with the root node of the BST and the minimum and maximum values (LLONG_MIN and LLONG_MAX) as initial bounds. - -The insert function is used to dynamically construct the BST based on the user's input. It takes the root node and the value to be inserted as parameters. If the root node is nullptr, it means the tree is empty, so a new node is created with the given value and returned. Otherwise, based on the value being less than or greater than the root node's value, the function is recursively called on the left or right subtree, respectively. The function then updates the left or right child pointer of the root node accordingly. - -The deleteTree function is a recursive function that deallocates the memory allocated for the BST nodes. It takes the root node as input and performs a post-order traversal to delete the nodes. First, it recursively calls deleteTree for the left and right subtrees, and then it deletes the current node. - -In the main function, we start by declaring the root node as nullptr and a variable value to store the user's input. We prompt the user to enter values to construct the BST, and the input loop continues until the user enters -1. Inside the loop, we call the insert function to insert the entered value into the BST. - -After constructing the BST, we call the isValidBST function to check if the BST is valid. If it is, we print a message indicating that the BST is valid; otherwise, we print a message indicating that it's not valid. - -Finally, we clean up the memory allocated for the BST by calling the deleteTree function, passing the root node as the parameter. - -*/ - --------------------------------------------------------------------------//C++ code begins here------------------------------------------------------------- - -#include -#include - -struct TreeNode { - int val; - TreeNode* left; - TreeNode* right; - TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} -}; - -bool isValidBSTHelper(TreeNode* node, long long minVal, long long maxVal) { - if (node == nullptr) - return true; - - if (node->val <= minVal || node->val >= maxVal) - return false; - - return isValidBSTHelper(node->left, minVal, node->val) && - isValidBSTHelper(node->right, node->val, maxVal); -} - -bool isValidBST(TreeNode* root) { - return isValidBSTHelper(root, LLONG_MIN, LLONG_MAX); -} - -TreeNode* insert(TreeNode* root, int value) { - if (root == nullptr) - return new TreeNode(value); - - if (value < root->val) - root->left = insert(root->left, value); - else - root->right = insert(root->right, value); - - return root; -} - -void deleteTree(TreeNode* root) { - if (root == nullptr) - return; - - deleteTree(root->left); - deleteTree(root->right); - - delete root; -} - -int main() { - TreeNode* root = nullptr; - int value; - - std::cout << "Enter values to construct the BST (enter -1 to stop):" << std::endl; - - while (true) { - std::cin >> value; - - if (value == -1) - break; - - root = insert(root, value); - } - - // Check if the BST is valid - if (isValidBST(root)) - std::cout << "The BST is valid." << std::endl; - else - std::cout << "The BST is not valid." << std::endl; - - // Clean up memory - deleteTree(root); - - return 0; -} diff --git a/Graphs/validate_bst.go b/Graphs/validate_bst.go new file mode 100644 index 00000000..ce359650 --- /dev/null +++ b/Graphs/validate_bst.go @@ -0,0 +1,35 @@ +package main + +import "math" + +type BST struct { + Value int + + Left *BST + Right *BST +} + +// ValidateBst is a method of BST that checks if the binary search tree is valid +func (tree *BST) ValidateBst() bool { + return tree.validateBST(math.MinInt32, math.MaxInt32) +} + +// validateBST is a recursive helper function that checks if the binary search tree is valid +// min is the minimum value that a node in the subtree rooted at this node can have +// max is the maximum value that a node in the subtree rooted at this node can have +func (tree *BST) validateBST(min, max int) bool { + // if the current node's value is outside the allowed range, then the tree is invalid + if tree.Value < min || tree.Value >= max { + return false + } + // recursively check the left subtree, making sure all values are less than the current node's value + if tree.Left != nil && !tree.Left.validateBST(min, tree.Value) { + return false + } + // recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if tree.Right != nil && !tree.Right.validateBST(tree.Value, max) { + return false + } + // if we reach this point, then the tree is valid + return true +} From 13af4711c3d51b406cdf92c389e77448ea74cbd6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 26 Sep 2023 22:13:42 +0530 Subject: [PATCH 1797/1894] add explanation and space time complexity --- Graphs/validate_bst.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Graphs/validate_bst.go b/Graphs/validate_bst.go index ce359650..25d7a4fd 100644 --- a/Graphs/validate_bst.go +++ b/Graphs/validate_bst.go @@ -1,3 +1,27 @@ +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing + whether the BST is valid. + + Explanation: + + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can point to other + BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating whether the tree is a valid + BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree is a valid + BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum and maximum values + that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined by the min and + max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left and right + child nodes to check whether their values are within their valid ranges. The valid range for the left child node is defined by the minimum value and the parent node's value, while the valid range for the right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST +*/ package main import "math" From b6943520df7a8e94c24f0202dd4d3f08d178d3b0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 26 Sep 2023 22:16:00 +0530 Subject: [PATCH 1798/1894] add validate bst in python --- Graphs/validate_bst.py | 64 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Graphs/validate_bst.py diff --git a/Graphs/validate_bst.py b/Graphs/validate_bst.py new file mode 100644 index 00000000..81247d3b --- /dev/null +++ b/Graphs/validate_bst.py @@ -0,0 +1,64 @@ +''' + Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing + whether the BST is valid. + + Explanation: + + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can point to other + BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating whether the tree is a valid + BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree is a valid + BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum and maximum values + that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined by the min and + max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left and right + child nodes to check whether their values are within their valid ranges. The valid range for the left child node is defined by the minimum value and the parent node's value, while the valid range for the right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST +''' +import math + +class BST: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + + # Public method to check if the BST is valid + def validate_bst(self): + return self._validate_bst(-math.inf, math.inf) + + # Private recursive helper function to check if the BST is valid + def _validate_bst(self, min_val, max_val): + # Base case: if the current node's value is outside the allowed range, then the tree is invalid + if self.value < min_val or self.value >= max_val: + return False + + # Recursively check the left subtree, making sure all values are less than the current node's value + if self.left and not self.left._validate_bst(min_val, self.value): + return False + + # Recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if self.right and not self.right._validate_bst(self.value, max_val): + return False + + # If we reach this point, then the tree is valid + return True + +# Example usage: +root = BST(10) +root.left = BST(5) +root.right = BST(15) +root.left.left = BST(2) +root.left.right = BST(7) + +if root.validate_bst(): + print("The BST is valid.") +else: + print("The BST is not valid.") From 314d3ed8966c172f188904954794a49127dea160 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 26 Sep 2023 22:18:04 +0530 Subject: [PATCH 1799/1894] add valdiate bst in java --- Graphs/validate_bst.java | 80 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Graphs/validate_bst.java diff --git a/Graphs/validate_bst.java b/Graphs/validate_bst.java new file mode 100644 index 00000000..e213f5ae --- /dev/null +++ b/Graphs/validate_bst.java @@ -0,0 +1,80 @@ +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing + whether the BST is valid. + + Explanation: + + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can point to other + BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating whether the tree is a valid + BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree is a valid + BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum and maximum values + that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined by the min and + max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left and right + child nodes to check whether their values are within their valid ranges. The valid range for the left child node is defined by the minimum value and the parent node's value, while the valid range for the right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST +*/ +import java.util.*; + +class TreeNode { + int value; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + value = x; + left = null; + right = null; + } +} + +public class ValidateBST { + + // Public method to check if the BST is valid + public static boolean isValidBST(TreeNode root) { + return isValidBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + // Private recursive helper function to check if the BST is valid + private static boolean isValidBSTHelper(TreeNode node, long minVal, long maxVal) { + // Base case: if the current node's value is outside the allowed range, then the tree is invalid + if (node == null || node.value < minVal || node.value >= maxVal) { + return false; + } + + // Recursively check the left subtree, making sure all values are less than the current node's value + if (!isValidBSTHelper(node.left, minVal, node.value)) { + return false; + } + + // Recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if (!isValidBSTHelper(node.right, node.value, maxVal)) { + return false; + } + + // If we reach this point, then the tree is valid + return true; + } + + public static void main(String[] args) { + TreeNode root = new TreeNode(10); + root.left = new TreeNode(5); + root.right = new TreeNode(15); + root.left.left = new TreeNode(2); + root.left.right = new TreeNode(7); + + if (isValidBST(root)) { + System.out.println("The BST is valid."); + } else { + System.out.println("The BST is not valid."); + } + } +} From 77a654dd78804708997753015570fb2d1f6963be Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 27 Sep 2023 23:19:47 +0530 Subject: [PATCH 1800/1894] add validate bst in c++ --- Graphs/validate_bst.cpp | 83 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Graphs/validate_bst.cpp diff --git a/Graphs/validate_bst.cpp b/Graphs/validate_bst.cpp new file mode 100644 index 00000000..2a63241a --- /dev/null +++ b/Graphs/validate_bst.cpp @@ -0,0 +1,83 @@ +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing + whether the BST is valid. + + Explanation: + + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can point to other + BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating whether the tree is a valid + BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree is a valid + BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum and maximum values + that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined by the min and + max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left and right + child nodes to check whether their values are within their valid ranges. The valid range for the left child node is defined by the minimum value and the parent node's value, while the valid range for the right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST +*/ +#include +#include + +struct TreeNode { + int value; + TreeNode* left; + TreeNode* right; + + TreeNode(int x) : value(x), left(nullptr), right(nullptr) {} +}; + +// Function to check if the BST is valid +bool isValidBST(TreeNode* root) { + return isValidBSTHelper(root, std::numeric_limits::min(), std::numeric_limits::max()); +} + +// Recursive helper function to check if the BST is valid +bool isValidBSTHelper(TreeNode* node, long long minVal, long long maxVal) { + // Base case: if the current node's value is outside the allowed range, then the tree is invalid + if (!node || node->value <= minVal || node->value >= maxVal) { + return false; + } + + // Recursively check the left subtree, making sure all values are less than the current node's value + if (!isValidBSTHelper(node->left, minVal, node->value)) { + return false; + } + + // Recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if (!isValidBSTHelper(node->right, node->value, maxVal)) { + return false; + } + + // If we reach this point, then the tree is valid + return true; +} + +int main() { + TreeNode* root = new TreeNode(10); + root->left = new TreeNode(5); + root->right = new TreeNode(15); + root->left->left = new TreeNode(2); + root->left->right = new TreeNode(7); + + if (isValidBST(root)) { + std::cout << "The BST is valid." << std::endl; + } else { + std::cout << "The BST is not valid." << std::endl; + } + + // Clean up memory + delete root->left->left; + delete root->left->right; + delete root->left; + delete root->right; + delete root; + + return 0; +} From c92dceca2f4eea0ec41fb8aa885b64123cac086a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 27 Sep 2023 23:21:29 +0530 Subject: [PATCH 1801/1894] add validate bst in javascript --- Graphs/validate_bst.js | 70 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Graphs/validate_bst.js diff --git a/Graphs/validate_bst.js b/Graphs/validate_bst.js new file mode 100644 index 00000000..cb93a6af --- /dev/null +++ b/Graphs/validate_bst.js @@ -0,0 +1,70 @@ +/* + Write a function that takes in a potentially invalid Binary Search Tree (BST) and returns a boolean representing + whether the BST is valid. + + Explanation: + + This code defines a Binary Search Tree (BST) struct with an integer value and left and right nodes that can point to other + BST nodes. The struct also has a method called ValidateBst() that returns a boolean indicating whether the tree is a valid + BST or not. + + The BST struct has another method called validateBST() that is used by ValidateBst() to check whether the tree is a valid + BST or not. The validateBST() method takes in two arguments, min and max, which represent the minimum and maximum values + that the current node's value can take in order to be a valid BST. + + The validateBST() method first checks whether the current node's value is within the valid range determined by the min and + max arguments. If not, the method returns false, indicating that the tree is not a valid BST. + + If the current node's value is within the valid range, the method then recursively calls itself on the left and right + child nodes to check whether their values are within their valid ranges. The valid range for the left child node is defined by the minimum value and the parent node's value, while the valid range for the right child node is defined by the parent node's value and the maximum value. + + If all of the nodes in the tree satisfy the BST property, the method returns true, indicating that the tree is a valid BST. + + O(n) time | O(d) space - where n is the number of nodes in the BST and d is the depth (height) of the BST +*/ +class TreeNode { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +// Function to check if the BST is valid +function isValidBST(root) { + return isValidBSTHelper(root, -Infinity, Infinity); +} + +// Recursive helper function to check if the BST is valid +function isValidBSTHelper(node, minVal, maxVal) { + // Base case: if the current node's value is outside the allowed range, then the tree is invalid + if (!node || node.value <= minVal || node.value >= maxVal) { + return false; + } + + // Recursively check the left subtree, making sure all values are less than the current node's value + if (!isValidBSTHelper(node.left, minVal, node.value)) { + return false; + } + + // Recursively check the right subtree, making sure all values are greater than or equal to the current node's value + if (!isValidBSTHelper(node.right, node.value, maxVal)) { + return false; + } + + // If we reach this point, then the tree is valid + return true; +} + +// Example usage: +const root = new TreeNode(10); +root.left = new TreeNode(5); +root.right = new TreeNode(15); +root.left.left = new TreeNode(2); +root.left.right = new TreeNode(7); + +if (isValidBST(root)) { + console.log("The BST is valid."); +} else { + console.log("The BST is not valid."); +} From 6183e0df469cd4eb8a7578d3bf2535d53cc04b84 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 28 Sep 2023 22:39:02 +0530 Subject: [PATCH 1802/1894] add juice bottling in java --- Dynamic Programming/juice_bottling.java | 73 +++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Dynamic Programming/juice_bottling.java diff --git a/Dynamic Programming/juice_bottling.java b/Dynamic Programming/juice_bottling.java new file mode 100644 index 00000000..d75b27ff --- /dev/null +++ b/Dynamic Programming/juice_bottling.java @@ -0,0 +1,73 @@ +/* + + +Explanation: + +1. The function `JuiceBottling` takes an array `prices` as input, where `prices[i]` represents the price of a juice bottle of size `i`. + +2. It initializes two arrays, `maxProfit` and `dividingPoints`, both of size `numSizes` (the number of bottle sizes). +These arrays will be used to store information about maximum profit and dividing points. + +3. The outer loop iterates through each possible bottle size, from 0 to `numSizes - 1`. + +4. The inner loop iterates through possible dividing points for the current bottle size. For each combination of bottle size +and dividing point, it calculates the possible profit by adding the maximum profit from the previous bottle sizes and the +price of the bottle at the current dividing point. + +5. If the calculated possible profit is greater than the current maximum profit for the bottle size, it updates both `maxProfit` +and `dividingPoints` arrays. + +6. After completing the loops, the function reconstructs the solution by backtracking from the last bottle size to the first. +It appends the recorded dividing points to the `solution` array, which represents the optimal way to divide the bottles. + +7. The function returns the `solution` array, which contains the indices of the dividing points that maximize profit. + +In summary, the code uses dynamic programming to determine the optimal division of juice bottles to maximize profit. +It calculates the maximum profit for each bottle size and keeps track of the dividing points that lead to the maximum profit. +The solution is then reconstructed by backtracking from the end using the recorded dividing points. +*/ + +import java.util.ArrayList; +import java.util.List; + +public class JuiceBottling { + + public static List juiceBottling(int[] prices) { + int numSizes = prices.length; + int[] maxProfit = new int[numSizes]; // Array to store the maximum profit for each bottle size + int[] dividingPoints = new int[numSizes]; // Array to store the dividing points that maximize profit + + // Loop through each bottle size + for (int size = 0; size < numSizes; size++) { + // Loop through possible dividing points for the current size + for (int dividingPoint = 0; dividingPoint < size + 1; dividingPoint++) { + // Calculate the possible profit by combining the previous maximum profit + // with the price at the current dividing point + int possibleProfit = maxProfit[size - dividingPoint] + prices[dividingPoint]; + + // Update maxProfit and dividingPoints if the new possible profit is greater + if (possibleProfit > maxProfit[size]) { + maxProfit[size] = possibleProfit; + dividingPoints[size] = dividingPoint; + } + } + } + + List solution = new ArrayList<>(); + int currentDividingPoint = numSizes - 1; + // Reconstruct the solution by tracing back from the end + // using the dividing points information + while (currentDividingPoint > 0) { + solution.add(dividingPoints[currentDividingPoint]); + currentDividingPoint -= dividingPoints[currentDividingPoint]; + } + return solution; + } + + public static void main(String[] args) { + int[] prices = {3, 5, 8, 9, 10, 17, 17, 20}; + List result = juiceBottling(prices); + + System.out.println("Dividing Points for Maximum Profit: " + result); + } +} From 6812f5f44ff0b7a30ea5731c0f00f6c341d81996 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 28 Sep 2023 22:42:00 +0530 Subject: [PATCH 1803/1894] add juice bottling in cpp --- Dynamic Programming/juice_bottling.cpp | 76 ++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Dynamic Programming/juice_bottling.cpp diff --git a/Dynamic Programming/juice_bottling.cpp b/Dynamic Programming/juice_bottling.cpp new file mode 100644 index 00000000..71327506 --- /dev/null +++ b/Dynamic Programming/juice_bottling.cpp @@ -0,0 +1,76 @@ +/* + + +Explanation: + +1. The function `JuiceBottling` takes an array `prices` as input, where `prices[i]` represents the price of a juice bottle of size `i`. + +2. It initializes two arrays, `maxProfit` and `dividingPoints`, both of size `numSizes` (the number of bottle sizes). +These arrays will be used to store information about maximum profit and dividing points. + +3. The outer loop iterates through each possible bottle size, from 0 to `numSizes - 1`. + +4. The inner loop iterates through possible dividing points for the current bottle size. For each combination of bottle size +and dividing point, it calculates the possible profit by adding the maximum profit from the previous bottle sizes and the +price of the bottle at the current dividing point. + +5. If the calculated possible profit is greater than the current maximum profit for the bottle size, it updates both `maxProfit` +and `dividingPoints` arrays. + +6. After completing the loops, the function reconstructs the solution by backtracking from the last bottle size to the first. +It appends the recorded dividing points to the `solution` array, which represents the optimal way to divide the bottles. + +7. The function returns the `solution` array, which contains the indices of the dividing points that maximize profit. + +In summary, the code uses dynamic programming to determine the optimal division of juice bottles to maximize profit. +It calculates the maximum profit for each bottle size and keeps track of the dividing points that lead to the maximum profit. +The solution is then reconstructed by backtracking from the end using the recorded dividing points. +*/ + +#include +#include + +std::vector juiceBottling(std::vector& prices) { + int numSizes = prices.size(); + std::vector maxProfit(numSizes); // Vector to store the maximum profit for each bottle size + std::vector dividingPoints(numSizes); // Vector to store the dividing points that maximize profit + + // Loop through each bottle size + for (int size = 0; size < numSizes; size++) { + // Loop through possible dividing points for the current size + for (int dividingPoint = 0; dividingPoint < size + 1; dividingPoint++) { + // Calculate the possible profit by combining the previous maximum profit + // with the price at the current dividing point + int possibleProfit = maxProfit[size - dividingPoint] + prices[dividingPoint]; + + // Update maxProfit and dividingPoints if the new possible profit is greater + if (possibleProfit > maxProfit[size]) { + maxProfit[size] = possibleProfit; + dividingPoints[size] = dividingPoint; + } + } + } + + std::vector solution; + int currentDividingPoint = numSizes - 1; + // Reconstruct the solution by tracing back from the end + // using the dividing points information + while (currentDividingPoint > 0) { + solution.push_back(dividingPoints[currentDividingPoint]); + currentDividingPoint -= dividingPoints[currentDividingPoint]; + } + return solution; +} + +int main() { + std::vector prices = {3, 5, 8, 9, 10, 17, 17, 20}; + std::vector result = juiceBottling(prices); + + std::cout << "Dividing Points for Maximum Profit:"; + for (int point : result) { + std::cout << " " << point; + } + std::cout << std::endl; + + return 0; +} From 9f3ff7ee43b10cc038fcc7738ec429c695801b2c Mon Sep 17 00:00:00 2001 From: Evangelos-Dimos Date: Fri, 29 Sep 2023 16:01:12 +0300 Subject: [PATCH 1804/1894] Scheduling Algortihms --- Scheduling Algortihms/fcfs.c | 132 ++++++++++++++++++++++++++ Scheduling Algortihms/sjf.c | 162 ++++++++++++++++++++++++++++++++ Scheduling Algortihms/srtf.c | 176 +++++++++++++++++++++++++++++++++++ 3 files changed, 470 insertions(+) create mode 100644 Scheduling Algortihms/fcfs.c create mode 100644 Scheduling Algortihms/sjf.c create mode 100644 Scheduling Algortihms/srtf.c diff --git a/Scheduling Algortihms/fcfs.c b/Scheduling Algortihms/fcfs.c new file mode 100644 index 00000000..1af2fc20 --- /dev/null +++ b/Scheduling Algortihms/fcfs.c @@ -0,0 +1,132 @@ +/* + +The First-Come, First-Served (FCFS) scheduling algorithm is one of the simplest process scheduling algorithms used in operating systems. It follows the principle of serving processes in the order they arrive in the ready queue. In FCFS, the process that arrives first will be the first one to be executed, and it continues until the process completes its execution or enters a waiting state. + +Algorithm Description: + +When a process enters the ready queue, it is added to the end of the queue (at the "tail" of the queue). + +The CPU scheduler selects the process at the front of the queue (the "head" of the queue) for execution. + +The selected process runs on the CPU until it completes its execution, enters a waiting state (e.g., I/O operation), or its time quantum (if there is a time-sharing system) expires. + +Once the currently running process finishes, the CPU scheduler selects the process at the front of the queue as the next process to run. This process will continue until it completes or enters a waiting state, and so on. + +This process of selecting and executing processes continues until all processes in the queue have executed. + +Example: +Let's illustrate the FCFS algorithm with a simple example. Consider three processes, P1, P2, and P3, with their respective burst times (the time they need to complete execution): + +Process P1: Burst time = 2 ms +Process P2: Burst time = 7 ms +Process P3: Burst time = 4 ms +Here's how FCFS will schedule and execute these processes: + +Initially, the ready queue is empty. + +Process P1 arrives first, so it is added to the ready queue: + +Ready Queue: [P1] +Execution: P1 (2 ms) +Process P1 completes its execution. Now, process P2 is selected because it's at the front of the queue: + +Ready Queue: [P2] +Execution: P2 (7 ms) +Process P2 completes its execution. Finally, process P3 is selected: + +Ready Queue: [P3] +Execution: P3 (4 ms) +Process P3 completes its execution. + +The order of execution in FCFS is P1 -> P2 -> P3. FCFS is non-preemptive, meaning once a process starts execution, it continues until it finishes or enters a waiting state. It can suffer from the "convoy effect," where a long process at the head of the queue can block shorter processes behind it. + +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 2; + + arr[1].process_id = 2; + arr[1].arrival_time = 1; + arr[1].burst_time = 7; + + arr[2].process_id = 3; + arr[2].arrival_time = 3; + arr[2].burst_time = 4; + + //Sorting the struct by arrival time + process temp; + for(int i=0; i P2 -> P3. SJF aims to minimize the average waiting time for processes, making it an effective algorithm when you have information about the burst times of processes. However, it can suffer from starvation if a long job continually arrives after shorter jobs. +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 7; + + arr[1].process_id = 2; + arr[1].arrival_time = 2; + arr[1].burst_time = 3; + + arr[2].process_id = 3; + arr[2].arrival_time = 4; + arr[2].burst_time = 8; + + //Sorting the struct by arrival time + process temp; + for(int i=0; i= arr[j].arrival_time && arr[j].burst_time <= min) + { + temp = arr[k]; + arr[k] = arr[j]; + arr[j] = temp; + } + } + k++; //increase index + } + + //Variable for the sum of burst time + int sum_of_burst_time=0; + + //Calculate sum of burst time + for (int i=0; i P2 -> P1 -> P3. SRTF provides optimal turnaround times but may suffer from frequent context switches due to its preemptive nature. +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 7; + + arr[1].process_id = 2; + arr[1].arrival_time = 2; + arr[1].burst_time = 3; + + arr[2].process_id = 3; + arr[2].arrival_time = 4; + arr[2].burst_time = 8; + + //Sorting the struct by arrival time + process temp; + for (int i=0; i Date: Fri, 29 Sep 2023 18:25:37 +0300 Subject: [PATCH 1805/1894] Scheduling --- Scheduling/fcfs.c | 132 ++++++++++++++++++++++++++++++++++ Scheduling/sjf.c | 162 ++++++++++++++++++++++++++++++++++++++++++ Scheduling/srtf.c | 176 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 470 insertions(+) create mode 100644 Scheduling/fcfs.c create mode 100644 Scheduling/sjf.c create mode 100644 Scheduling/srtf.c diff --git a/Scheduling/fcfs.c b/Scheduling/fcfs.c new file mode 100644 index 00000000..1af2fc20 --- /dev/null +++ b/Scheduling/fcfs.c @@ -0,0 +1,132 @@ +/* + +The First-Come, First-Served (FCFS) scheduling algorithm is one of the simplest process scheduling algorithms used in operating systems. It follows the principle of serving processes in the order they arrive in the ready queue. In FCFS, the process that arrives first will be the first one to be executed, and it continues until the process completes its execution or enters a waiting state. + +Algorithm Description: + +When a process enters the ready queue, it is added to the end of the queue (at the "tail" of the queue). + +The CPU scheduler selects the process at the front of the queue (the "head" of the queue) for execution. + +The selected process runs on the CPU until it completes its execution, enters a waiting state (e.g., I/O operation), or its time quantum (if there is a time-sharing system) expires. + +Once the currently running process finishes, the CPU scheduler selects the process at the front of the queue as the next process to run. This process will continue until it completes or enters a waiting state, and so on. + +This process of selecting and executing processes continues until all processes in the queue have executed. + +Example: +Let's illustrate the FCFS algorithm with a simple example. Consider three processes, P1, P2, and P3, with their respective burst times (the time they need to complete execution): + +Process P1: Burst time = 2 ms +Process P2: Burst time = 7 ms +Process P3: Burst time = 4 ms +Here's how FCFS will schedule and execute these processes: + +Initially, the ready queue is empty. + +Process P1 arrives first, so it is added to the ready queue: + +Ready Queue: [P1] +Execution: P1 (2 ms) +Process P1 completes its execution. Now, process P2 is selected because it's at the front of the queue: + +Ready Queue: [P2] +Execution: P2 (7 ms) +Process P2 completes its execution. Finally, process P3 is selected: + +Ready Queue: [P3] +Execution: P3 (4 ms) +Process P3 completes its execution. + +The order of execution in FCFS is P1 -> P2 -> P3. FCFS is non-preemptive, meaning once a process starts execution, it continues until it finishes or enters a waiting state. It can suffer from the "convoy effect," where a long process at the head of the queue can block shorter processes behind it. + +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 2; + + arr[1].process_id = 2; + arr[1].arrival_time = 1; + arr[1].burst_time = 7; + + arr[2].process_id = 3; + arr[2].arrival_time = 3; + arr[2].burst_time = 4; + + //Sorting the struct by arrival time + process temp; + for(int i=0; i P2 -> P3. SJF aims to minimize the average waiting time for processes, making it an effective algorithm when you have information about the burst times of processes. However, it can suffer from starvation if a long job continually arrives after shorter jobs. +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 7; + + arr[1].process_id = 2; + arr[1].arrival_time = 2; + arr[1].burst_time = 3; + + arr[2].process_id = 3; + arr[2].arrival_time = 4; + arr[2].burst_time = 8; + + //Sorting the struct by arrival time + process temp; + for(int i=0; i= arr[j].arrival_time && arr[j].burst_time <= min) + { + temp = arr[k]; + arr[k] = arr[j]; + arr[j] = temp; + } + } + k++; //increase index + } + + //Variable for the sum of burst time + int sum_of_burst_time=0; + + //Calculate sum of burst time + for (int i=0; i P2 -> P1 -> P3. SRTF provides optimal turnaround times but may suffer from frequent context switches due to its preemptive nature. +*/ + +#include +#include + +// Struct for the info of each process +typedef struct +{ + + int process_id; + int arrival_time; + int burst_time; + +} process; + + +int main() { + + // Number of processes + int number=3; + + // Size of the array which will show the order of execution of the processes + process *arr; + arr = malloc(number * sizeof(process)); + + // Initialize for our example + arr[0].process_id = 1; + arr[0].arrival_time = 0; + arr[0].burst_time = 7; + + arr[1].process_id = 2; + arr[1].arrival_time = 2; + arr[1].burst_time = 3; + + arr[2].process_id = 3; + arr[2].arrival_time = 4; + arr[2].burst_time = 8; + + //Sorting the struct by arrival time + process temp; + for (int i=0; i Date: Fri, 29 Sep 2023 23:16:32 +0530 Subject: [PATCH 1806/1894] add juice bottling in javascript --- Dynamic Programming/juice_bottling.js | 65 +++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Dynamic Programming/juice_bottling.js diff --git a/Dynamic Programming/juice_bottling.js b/Dynamic Programming/juice_bottling.js new file mode 100644 index 00000000..67d8a71d --- /dev/null +++ b/Dynamic Programming/juice_bottling.js @@ -0,0 +1,65 @@ +/* + + +Explanation: + +1. The function `JuiceBottling` takes an array `prices` as input, where `prices[i]` represents the price of a juice bottle of size `i`. + +2. It initializes two arrays, `maxProfit` and `dividingPoints`, both of size `numSizes` (the number of bottle sizes). +These arrays will be used to store information about maximum profit and dividing points. + +3. The outer loop iterates through each possible bottle size, from 0 to `numSizes - 1`. + +4. The inner loop iterates through possible dividing points for the current bottle size. For each combination of bottle size +and dividing point, it calculates the possible profit by adding the maximum profit from the previous bottle sizes and the +price of the bottle at the current dividing point. + +5. If the calculated possible profit is greater than the current maximum profit for the bottle size, it updates both `maxProfit` +and `dividingPoints` arrays. + +6. After completing the loops, the function reconstructs the solution by backtracking from the last bottle size to the first. +It appends the recorded dividing points to the `solution` array, which represents the optimal way to divide the bottles. + +7. The function returns the `solution` array, which contains the indices of the dividing points that maximize profit. + +In summary, the code uses dynamic programming to determine the optimal division of juice bottles to maximize profit. +It calculates the maximum profit for each bottle size and keeps track of the dividing points that lead to the maximum profit. +The solution is then reconstructed by backtracking from the end using the recorded dividing points. +*/ +function juiceBottling(prices) { + const numSizes = prices.length; + const maxProfit = new Array(numSizes).fill(0); // Array to store the maximum profit for each bottle size + const dividingPoints = new Array(numSizes).fill(0); // Array to store the dividing points that maximize profit + + // Loop through each bottle size + for (let size = 0; size < numSizes; size++) { + // Loop through possible dividing points for the current size + for (let dividingPoint = 0; dividingPoint < size + 1; dividingPoint++) { + // Calculate the possible profit by combining the previous maximum profit + // with the price at the current dividing point + const possibleProfit = + maxProfit[size - dividingPoint] + prices[dividingPoint]; + + // Update maxProfit and dividingPoints if the new possible profit is greater + if (possibleProfit > maxProfit[size]) { + maxProfit[size] = possibleProfit; + dividingPoints[size] = dividingPoint; + } + } + } + + const solution = []; + let currentDividingPoint = numSizes - 1; + // Reconstruct the solution by tracing back from the end + // using the dividing points information + while (currentDividingPoint > 0) { + solution.push(dividingPoints[currentDividingPoint]); + currentDividingPoint -= dividingPoints[currentDividingPoint]; + } + return solution; +} + +// Example usage: +const prices = [3, 5, 8, 9, 10, 17, 17, 20]; +const result = juiceBottling(prices); +console.log("Dividing Points for Maximum Profit:", result); From cce771ba269fa18f1fc46b24e94d78b46ea0c88c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 29 Sep 2023 23:17:16 +0530 Subject: [PATCH 1807/1894] add juice bottling in python --- Dynamic Programming/juice_bottling.py | 58 +++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Dynamic Programming/juice_bottling.py diff --git a/Dynamic Programming/juice_bottling.py b/Dynamic Programming/juice_bottling.py new file mode 100644 index 00000000..ee834b19 --- /dev/null +++ b/Dynamic Programming/juice_bottling.py @@ -0,0 +1,58 @@ +''' +Explanation: + +1. The function `JuiceBottling` takes an array `prices` as input, where `prices[i]` represents the price of a juice bottle of size `i`. + +2. It initializes two arrays, `maxProfit` and `dividingPoints`, both of size `numSizes` (the number of bottle sizes). +These arrays will be used to store information about maximum profit and dividing points. + +3. The outer loop iterates through each possible bottle size, from 0 to `numSizes - 1`. + +4. The inner loop iterates through possible dividing points for the current bottle size. For each combination of bottle size +and dividing point, it calculates the possible profit by adding the maximum profit from the previous bottle sizes and the +price of the bottle at the current dividing point. + +5. If the calculated possible profit is greater than the current maximum profit for the bottle size, it updates both `maxProfit` +and `dividingPoints` arrays. + +6. After completing the loops, the function reconstructs the solution by backtracking from the last bottle size to the first. +It appends the recorded dividing points to the `solution` array, which represents the optimal way to divide the bottles. + +7. The function returns the `solution` array, which contains the indices of the dividing points that maximize profit. + +In summary, the code uses dynamic programming to determine the optimal division of juice bottles to maximize profit. +It calculates the maximum profit for each bottle size and keeps track of the dividing points that lead to the maximum profit. +The solution is then reconstructed by backtracking from the end using the recorded dividing points. + +''' +def juice_bottling(prices): + num_sizes = len(prices) + max_profit = [0] * num_sizes # List to store the maximum profit for each bottle size + dividing_points = [0] * num_sizes # List to store the dividing points that maximize profit + + # Loop through each bottle size + for size in range(num_sizes): + # Loop through possible dividing points for the current size + for dividing_point in range(size + 1): + # Calculate the possible profit by combining the previous maximum profit + # with the price at the current dividing point + possible_profit = max_profit[size - dividing_point] + prices[dividing_point] + + # Update max_profit and dividing_points if the new possible profit is greater + if possible_profit > max_profit[size]: + max_profit[size] = possible_profit + dividing_points[size] = dividing_point + + solution = [] + current_dividing_point = num_sizes - 1 + # Reconstruct the solution by tracing back from the end + # using the dividing points information + while current_dividing_point > 0: + solution.append(dividing_points[current_dividing_point]) + current_dividing_point -= dividing_points[current_dividing_point] + return solution + +# Example usage: +prices = [3, 5, 8, 9, 10, 17, 17, 20] +result = juice_bottling(prices) +print("Dividing Points for Maximum Profit:", result) From b90f0221b72de17b2ae766c847475b039e27444c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 30 Sep 2023 23:27:42 +0530 Subject: [PATCH 1808/1894] add min height in java --- Trees/Binary Search Trees/min_height_BST.java | 128 ++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 Trees/Binary Search Trees/min_height_BST.java diff --git a/Trees/Binary Search Trees/min_height_BST.java b/Trees/Binary Search Trees/min_height_BST.java new file mode 100644 index 00000000..89871488 --- /dev/null +++ b/Trees/Binary Search Trees/min_height_BST.java @@ -0,0 +1,128 @@ +/* + + Write a function that takes in a non-empty sorted array of distinct integers, constructs a BST from the integers, and returns the root of the BST. + The function should minimize the height of the BST. + Smple Input : [1, 2, 5, 7, 10, 13, 14, 15, 22] + Output: + + 10 + / \ + 2 14 + / \ / \ + 1 5 13 15 + \ \ + 7 22 + + Explanation: + + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. + The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling + the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, + a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + + The function follows these steps: + + Base Case: If end < start, it means there are no elements to consider in the current range, so it returns nil indicating an empty subtree. + + Calculate the mid index as the midpoint of the current range (start and end). + + Get the value from the array at the mid index. + + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. + Otherwise, insert the value into the existing bst using the Insert method. + + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. + This constructs the left subtree. + + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. + This constructs the right subtree. + + Finally, return the bst which represents the constructed minimum height BST. + + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and + Left and Right fields to point to the left and right child nodes, respectively. + + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to + insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the + array and inserting the mid-value into the BST, ensuring a balanced structure. + + Time Complexity: + + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like + operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where + n is the number of elements in the array. + + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, + as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), + where n is the number of elements in the array. + + Space Complexity: + + The space complexity is determined by the stack space used during recursive calls and the space required + to store the BST. + + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of + the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of + elements (n), the space complexity becomes O(n). + + The space required to store the BST is also O(n) in the worst case since each element in the array is + inserted into the BST. + + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. + In summary, the time complexity is O(n log n) and the space complexity is O(n). + + + +*/ +public class JuiceBottling { + + public static int[] juiceBottling(int[] prices) { + int numSizes = prices.length; + int[] maxProfit = new int[numSizes]; // Array to store the maximum profit for each bottle size + int[] dividingPoints = new int[numSizes]; // Array to store the dividing points that maximize profit + + // Loop through each bottle size + for (int size = 0; size < numSizes; size++) { + // Loop through possible dividing points for the current size + for (int dividingPoint = 0; dividingPoint < size + 1; dividingPoint++) { + // Calculate the possible profit by combining the previous maximum profit + // with the price at the current dividing point + int possibleProfit = maxProfit[size - dividingPoint] + prices[dividingPoint]; + + // Update maxProfit and dividingPoints if the new possible profit is greater + if (possibleProfit > maxProfit[size]) { + maxProfit[size] = possibleProfit; + dividingPoints[size] = dividingPoint; + } + } + } + + int[] solution = new int[numSizes]; + int currentDividingPoint = numSizes - 1; + // Reconstruct the solution by tracing back from the end + // using the dividing points information + while (currentDividingPoint > 0) { + solution[currentDividingPoint] = dividingPoints[currentDividingPoint]; + currentDividingPoint -= dividingPoints[currentDividingPoint]; + } + return solution; + } + + public static void main(String[] args) { + int[] prices = {3, 5, 8, 9, 10, 17, 17, 20}; + int[] result = juiceBottling(prices); + + System.out.print("Dividing Points for Maximum Profit:"); + for (int point : result) { + System.out.print(" " + point); + } + System.out.println(); + } +} From af0789a949ddc60f564d51a6b722b0144c4a3bab Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 1 Oct 2023 22:45:05 +0530 Subject: [PATCH 1809/1894] add min height in c++ --- Trees/Binary Search Trees/min_height_BST.cpp | 164 +++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 Trees/Binary Search Trees/min_height_BST.cpp diff --git a/Trees/Binary Search Trees/min_height_BST.cpp b/Trees/Binary Search Trees/min_height_BST.cpp new file mode 100644 index 00000000..0bc84eb9 --- /dev/null +++ b/Trees/Binary Search Trees/min_height_BST.cpp @@ -0,0 +1,164 @@ +/* + + Write a function that takes in a non-empty sorted array of distinct integers, constructs a BST from the integers, and returns the root of the BST. + The function should minimize the height of the BST. + Smple Input : [1, 2, 5, 7, 10, 13, 14, 15, 22] + Output: + + 10 + / \ + 2 14 + / \ / \ + 1 5 13 15 + \ \ + 7 22 + + Explanation: + + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. + The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling + the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, + a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + + The function follows these steps: + + Base Case: If end < start, it means there are no elements to consider in the current range, so it returns nil indicating an empty subtree. + + Calculate the mid index as the midpoint of the current range (start and end). + + Get the value from the array at the mid index. + + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. + Otherwise, insert the value into the existing bst using the Insert method. + + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. + This constructs the left subtree. + + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. + This constructs the right subtree. + + Finally, return the bst which represents the constructed minimum height BST. + + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and + Left and Right fields to point to the left and right child nodes, respectively. + + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to + insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the + array and inserting the mid-value into the BST, ensuring a balanced structure. + + Time Complexity: + + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like + operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where + n is the number of elements in the array. + + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, + as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), + where n is the number of elements in the array. + + Space Complexity: + + The space complexity is determined by the stack space used during recursive calls and the space required + to store the BST. + + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of + the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of + elements (n), the space complexity becomes O(n). + + The space required to store the BST is also O(n) in the worst case since each element in the array is + inserted into the BST. + + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. + In summary, the time complexity is O(n log n) and the space complexity is O(n). + + + +*/ +#include +#include + +struct TreeNode { + int value; + TreeNode* left; + TreeNode* right; + + TreeNode(int x) : value(x), left(nullptr), right(nullptr) {} +}; + +TreeNode* minHeightBST(std::vector& array) { + // Call helper method with start index, end index, and a nullptr root node + return constructMinHeightBST(array, nullptr, 0, array.size() - 1); +} + +TreeNode* constructMinHeightBST(std::vector& array, TreeNode* bst, int start, int end) { + // Base case + if (end < start) { + return nullptr; + } + int mid = (start + end) / 2; + int value = array[mid]; + // If the BST is empty, create a new root node + if (bst == nullptr) { + bst = new TreeNode(value); + } else { + // Insert the value into the existing BST + bst->insert(value); + } + // Recursively construct the left and right subtrees + bst->left = constructMinHeightBST(array, bst->left, start, mid - 1); + bst->right = constructMinHeightBST(array, bst->right, mid + 1, end); + return bst; +} + +class BST { +public: + int value; + BST* left; + BST* right; + + BST(int x) : value(x), left(nullptr), right(nullptr) {} + + void insert(int value) { + if (value < this->value) { + if (left == nullptr) { + left = new BST(value); + } else { + left->insert(value); + } + } else { + if (right == nullptr) { + right = new BST(value); + } else { + right->insert(value); + } + } + } +}; + +int main() { + std::vector array = {1, 2, 3, 4, 5, 6, 7}; + TreeNode* root = minHeightBST(array); + + // Printing the BST is left as an exercise + + // Clean up memory + deleteTree(root); + + return 0; +} + +void deleteTree(TreeNode* root) { + if (root == nullptr) { + return; + } + deleteTree(root->left); + deleteTree(root->right); + delete root; +} From 64176663a07d11405f40c1e268d287c8dee5c1b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 1 Oct 2023 22:45:39 +0530 Subject: [PATCH 1810/1894] add min height bst in python --- Trees/Binary Search Trees/min_height_BST.py | 131 ++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 Trees/Binary Search Trees/min_height_BST.py diff --git a/Trees/Binary Search Trees/min_height_BST.py b/Trees/Binary Search Trees/min_height_BST.py new file mode 100644 index 00000000..8c283db9 --- /dev/null +++ b/Trees/Binary Search Trees/min_height_BST.py @@ -0,0 +1,131 @@ +''' + Write a function that takes in a non-empty sorted array of distinct integers, constructs a BST from the integers, and returns the root of the BST. + The function should minimize the height of the BST. + Smple Input : [1, 2, 5, 7, 10, 13, 14, 15, 22] + Output: + + 10 + / \ + 2 14 + / \ / \ + 1 5 13 15 + \ \ + 7 22 + + Explanation: + + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. + The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling + the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, + a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + + The function follows these steps: + + Base Case: If end < start, it means there are no elements to consider in the current range, so it returns nil indicating an empty subtree. + + Calculate the mid index as the midpoint of the current range (start and end). + + Get the value from the array at the mid index. + + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. + Otherwise, insert the value into the existing bst using the Insert method. + + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. + This constructs the left subtree. + + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. + This constructs the right subtree. + + Finally, return the bst which represents the constructed minimum height BST. + + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and + Left and Right fields to point to the left and right child nodes, respectively. + + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to + insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the + array and inserting the mid-value into the BST, ensuring a balanced structure. + + Time Complexity: + + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like + operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where + n is the number of elements in the array. + + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, + as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), + where n is the number of elements in the array. + + Space Complexity: + + The space complexity is determined by the stack space used during recursive calls and the space required + to store the BST. + + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of + the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of + elements (n), the space complexity becomes O(n). + + The space required to store the BST is also O(n) in the worst case since each element in the array is + inserted into the BST. + + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. + In summary, the time complexity is O(n log n) and the space complexity is O(n). + + +''' +class TreeNode: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + +def min_height_bst(array): + # Call helper method with start index, end index, and a None root node + return construct_min_height_bst(array, None, 0, len(array) - 1) + +def construct_min_height_bst(array, bst, start, end): + # Base case + if end < start: + return None + mid = (start + end) // 2 + value = array[mid] + # If the BST is empty, create a new root node + if bst is None: + bst = TreeNode(value) + else: + # Insert the value into the existing BST + bst.insert(value) + # Recursively construct the left and right subtrees + bst.left = construct_min_height_bst(array, bst.left, start, mid - 1) + bst.right = construct_min_height_bst(array, bst.right, mid + 1, end) + return bst + +class BST: + def __init__(self, value): + self.value = value + self.left = None + self.right = None + + def insert(self, value): + if value < self.value: + if self.left is None: + self.left = BST(value) + else: + self.left.insert(value) + else: + if self.right is None: + self.right = BST(value) + else: + self.right.insert(value) + +# Example usage: +array = [1, 2, 3, 4, 5, 6, 7] +root = min_height_bst(array) + +# Printing the BST is left as an exercise From 6811f85963823576e8dcbe307b8d71c78d456d4e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 2 Oct 2023 22:36:00 +0530 Subject: [PATCH 1811/1894] add min height in javascript --- Trees/Binary Search Trees/min_height_BST.js | 148 ++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 Trees/Binary Search Trees/min_height_BST.js diff --git a/Trees/Binary Search Trees/min_height_BST.js b/Trees/Binary Search Trees/min_height_BST.js new file mode 100644 index 00000000..b7f6255c --- /dev/null +++ b/Trees/Binary Search Trees/min_height_BST.js @@ -0,0 +1,148 @@ +/* + + Write a function that takes in a non-empty sorted array of distinct integers, constructs a BST from the integers, and returns the root of the BST. + The function should minimize the height of the BST. + Smple Input : [1, 2, 5, 7, 10, 13, 14, 15, 22] + Output: + + 10 + / \ + 2 14 + / \ / \ + 1 5 13 15 + \ \ + 7 22 + + Explanation: + + The given code is used to construct a minimum height binary search tree (BST) from a sorted array. + The goal is to create a balanced BST where the difference in height between the left and right subtrees is minimized. + + The MinHeightBST function serves as a wrapper function that initializes the construction process by calling + the constructMinHeightBST helper function. + + The constructMinHeightBST function recursively constructs the minimum height BST. It takes the sorted array, + a partially constructed bst, and the start and end indices that define the range of elements from the array currently being considered. + + The function follows these steps: + + Base Case: If end < start, it means there are no elements to consider in the current range, so it returns nil indicating an empty subtree. + + Calculate the mid index as the midpoint of the current range (start and end). + + Get the value from the array at the mid index. + + If the bst is nil, indicating that there are no values in the BST yet, create a new BST node with the value. + Otherwise, insert the value into the existing bst using the Insert method. + + Recursively call constructMinHeightBST for the left half of the array by passing start and mid-1 as the new range. + This constructs the left subtree. + + Recursively call constructMinHeightBST for the right half of the array by passing mid+1 and end as the new range. + This constructs the right subtree. + + Finally, return the bst which represents the constructed minimum height BST. + + The BST struct represents a node in the binary search tree. It has a Value field to store the node's value and + Left and Right fields to point to the left and right child nodes, respectively. + + The Insert method is used to insert a new value into the BST. It recursively finds the appropriate position to + insert the value based on the comparison with the current node's value and updates the left or right child accordingly. + + Overall, this code efficiently constructs a minimum height BST from a sorted array by recursively dividing the + array and inserting the mid-value into the BST, ensuring a balanced structure. + + Time Complexity: + + The MinHeightBST function calls the constructMinHeightBST helper function, which performs a binary search-like + operation to divide the array and construct the BST. This process is recursive and takes O(log n) time, where + n is the number of elements in the array. + + The bst.Insert(value) operation in constructMinHeightBST has a time complexity of O(log n) in the worst case, + as it involves traversing the height of the BST to find the appropriate position to insert the value. + Since each element in the array is inserted into the BST once, the overall time complexity is O(n log n), + where n is the number of elements in the array. + + Space Complexity: + + The space complexity is determined by the stack space used during recursive calls and the space required + to store the BST. + + The recursive calls in constructMinHeightBST consume additional stack space proportional to the height of + the tree. In the worst case scenario, where the BST is skewed and its height is equal to the number of + elements (n), the space complexity becomes O(n). + + The space required to store the BST is also O(n) in the worst case since each element in the array is + inserted into the BST. + + Therefore, the overall space complexity is O(n) due to the stack space and the BST storage. + In summary, the time complexity is O(n log n) and the space complexity is O(n). + + + +*/ +class TreeNode { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } +} + +// Function to construct a minimum-height BST +function minHeightBST(array) { + // Call the helper method with start index, end index, and a null root node + return constructMinHeightBST(array, null, 0, array.length - 1); +} + +// Recursive helper function to construct a minimum-height BST +function constructMinHeightBST(array, bst, start, end) { + // Base case + if (end < start) { + return null; + } + const mid = Math.floor((start + end) / 2); + const value = array[mid]; + // If the BST is empty, create a new root node + if (bst === null) { + bst = new TreeNode(value); + } else { + // Insert the value into the existing BST + bst.insert(value); + } + // Recursively construct the left and right subtrees + bst.left = constructMinHeightBST(array, bst.left, start, mid - 1); + bst.right = constructMinHeightBST(array, bst.right, mid + 1, end); + return bst; +} + +// Class for Binary Search Tree (BST) +class BST { + constructor(value) { + this.value = value; + this.left = null; + this.right = null; + } + + insert(value) { + if (value < this.value) { + if (this.left === null) { + this.left = new BST(value); + } else { + this.left.insert(value); + } + } else { + if (this.right === null) { + this.right = new BST(value); + } else { + this.right.insert(value); + } + } + } +} + +// Example usage: +const array = [1, 2, 3, 4, 5, 6, 7]; +const root = minHeightBST(array); + +// Printing the BST is left as an exercise From 82a451cb192eb221ab53af6fef95314c88bc0d2e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 2 Oct 2023 22:42:27 +0530 Subject: [PATCH 1812/1894] add reconstruct bst in java --- .../Binary Search Trees/reconstruct_bst.java | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 Trees/Binary Search Trees/reconstruct_bst.java diff --git a/Trees/Binary Search Trees/reconstruct_bst.java b/Trees/Binary Search Trees/reconstruct_bst.java new file mode 100644 index 00000000..4e2b8575 --- /dev/null +++ b/Trees/Binary Search Trees/reconstruct_bst.java @@ -0,0 +1,113 @@ +/* + Reconstruct BST + The pre-order traversal of a Binary Tree is a traversal technique that starts at the tree's root node and visits nodes in the following order: + Current Node + Left Subtree + Right Subtree + + Given a non-empty array of integers representing the pre-order traversal of a Binary Search Tree (BST), + write a function that creates the relevant BST and returns its root node. + + The input array will contain the values of BST nodes in the order in which these nodes would be visited with a pre-order traversal. + + Sample Input: [10, 4, 2, 1, 5, 17, 19, 18] + Sample Output: + 10 + / \ + 4 17 + / \ \ + 2 5 19 + / / +1 18 + + The ReconstructBst function takes a slice preOrderTraversalValues which represents the pre-order traversal of a binary search tree. + It reconstructs the BST using a range-based approach. Here's how the algorithm works: + + The ReconstructBst function initializes a treeInfo struct to keep track of the current root index. + + The ReconstructBst function calls the reconstructBSTFromRange helper function, passing the minimum and maximum integer values + as the initial range, the pre-order traversal values, and the treeInfo struct. + + The reconstructBSTFromRange function first checks if the current root index has reached the end of the pre-order traversal values. + If so, it returns nil indicating an empty subtree. + + It retrieves the value of the current root from the pre-order traversal values. + + It checks if the root value is outside the valid range defined by the lower and upper bounds. If so, it returns + + The time complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function processes each node exactly once. + + The space complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function creates BST nodes and recursively calls itself to construct the left and right subtrees. + The space complexity is determined by the height of the BST, which can be at most n in the worst case for a skewed BST. + +*/ +class TreeNode { + int value; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + value = x; + left = null; + right = null; + } +} + +class TreeInfo { + int rootIdx; + + TreeInfo(int idx) { + rootIdx = idx; + } +} + +public class ReconstructBST { + + public static TreeNode reconstructBst(int[] preOrderTraversalValues) { + // Create a TreeInfo object to keep track of the current root index. + TreeInfo treeInfo = new TreeInfo(0); + + // Call the helper function to reconstruct the BST from the given range and return the result. + return reconstructBstFromRange(Integer.MIN_VALUE, Integer.MAX_VALUE, preOrderTraversalValues, treeInfo); + } + + private static TreeNode reconstructBstFromRange(int lowerBound, int upperBound, int[] preOrderTraversalValues, TreeInfo currentSubtreeInfo) { + // Check if the root index has reached the end of the pre-order traversal values. If so, return null indicating an empty subtree. + if (currentSubtreeInfo.rootIdx == preOrderTraversalValues.length) { + return null; + } + + // Get the value of the current root from the pre-order traversal values. + int rootValue = preOrderTraversalValues[currentSubtreeInfo.rootIdx]; + + // Check if the root value is out of the valid range defined by the lower and upper bounds. If so, return null indicating an invalid subtree. + if (rootValue < lowerBound || rootValue >= upperBound) { + return null; + } + + // Increment the root index to move to the next element in the pre-order traversal values. + currentSubtreeInfo.rootIdx++; + + // Recursively reconstruct the left subtree within the range (lowerBound, rootValue) using the updated root index. + TreeNode leftSubtree = reconstructBstFromRange(lowerBound, rootValue, preOrderTraversalValues, currentSubtreeInfo); + + // Recursively reconstruct the right subtree within the range (rootValue, upperBound) using the updated root index. + TreeNode rightSubtree = reconstructBstFromRange(rootValue, upperBound, preOrderTraversalValues, currentSubtreeInfo); + + // Create a new TreeNode with the current root value and the reconstructed left and right subtrees. + TreeNode rootNode = new TreeNode(rootValue); + rootNode.left = leftSubtree; + rootNode.right = rightSubtree; + + return rootNode; + } + + public static void main(String[] args) { + int[] preOrderTraversalValues = {10, 5, 2, 7, 15, 12, 20}; + TreeNode root = reconstructBst(preOrderTraversalValues); + + // Printing the reconstructed BST is left as an exercise + } +} From fceca38525c0cfad60481c1d9fea4de057e0ae2d Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 2 Oct 2023 22:44:50 +0530 Subject: [PATCH 1813/1894] add reconstruct bst in c++ --- Trees/Binary Search Trees/reconstruct_bst.cpp | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 Trees/Binary Search Trees/reconstruct_bst.cpp diff --git a/Trees/Binary Search Trees/reconstruct_bst.cpp b/Trees/Binary Search Trees/reconstruct_bst.cpp new file mode 100644 index 00000000..e7821732 --- /dev/null +++ b/Trees/Binary Search Trees/reconstruct_bst.cpp @@ -0,0 +1,127 @@ +/* + Reconstruct BST + The pre-order traversal of a Binary Tree is a traversal technique that starts at the tree's root node and visits nodes in the following order: + Current Node + Left Subtree + Right Subtree + + Given a non-empty array of integers representing the pre-order traversal of a Binary Search Tree (BST), + write a function that creates the relevant BST and returns its root node. + + The input array will contain the values of BST nodes in the order in which these nodes would be visited with a pre-order traversal. + + Sample Input: [10, 4, 2, 1, 5, 17, 19, 18] + Sample Output: + 10 + / \ + 4 17 + / \ \ + 2 5 19 + / / +1 18 + + The ReconstructBst function takes a slice preOrderTraversalValues which represents the pre-order traversal of a binary search tree. + It reconstructs the BST using a range-based approach. Here's how the algorithm works: + + The ReconstructBst function initializes a treeInfo struct to keep track of the current root index. + + The ReconstructBst function calls the reconstructBSTFromRange helper function, passing the minimum and maximum integer values + as the initial range, the pre-order traversal values, and the treeInfo struct. + + The reconstructBSTFromRange function first checks if the current root index has reached the end of the pre-order traversal values. + If so, it returns nil indicating an empty subtree. + + It retrieves the value of the current root from the pre-order traversal values. + + It checks if the root value is outside the valid range defined by the lower and upper bounds. If so, it returns + + The time complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function processes each node exactly once. + + The space complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function creates BST nodes and recursively calls itself to construct the left and right subtrees. + The space complexity is determined by the height of the BST, which can be at most n in the worst case for a skewed BST. + +*/ +#include +#include +#include + +// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} +}; + +// A helper class to keep track of the current root index during reconstruction. +class TreeInfo { +public: + int rootIdx; + TreeInfo(int idx) : rootIdx(idx) {} +}; + +// Function to reconstruct the BST from a pre-order traversal. +TreeNode* reconstructBst(std::vector& preOrderTraversalValues) { + // Create a TreeInfo object to keep track of the current root index. + TreeInfo treeInfo(0); + + // Call the helper function to reconstruct the BST from the given range and return the result. + return reconstructBstFromRange(INT_MIN, INT_MAX, preOrderTraversalValues, treeInfo); +} + +// Recursive helper function to reconstruct the BST within a given range. +TreeNode* reconstructBstFromRange(int lowerBound, int upperBound, std::vector& preOrderTraversalValues, TreeInfo& currentSubtreeInfo) { + // Check if the root index has reached the end of the pre-order traversal values. If so, return nullptr indicating an empty subtree. + if (currentSubtreeInfo.rootIdx == preOrderTraversalValues.size()) { + return nullptr; + } + + // Get the value of the current root from the pre-order traversal values. + int rootValue = preOrderTraversalValues[currentSubtreeInfo.rootIdx]; + + // Check if the root value is out of the valid range defined by the lower and upper bounds. If so, return nullptr indicating an invalid subtree. + if (rootValue < lowerBound || rootValue >= upperBound) { + return nullptr; + } + + // Increment the root index to move to the next element in the pre-order traversal values. + currentSubtreeInfo.rootIdx++; + + // Recursively reconstruct the left subtree within the range (lowerBound, rootValue) using the updated root index. + TreeNode* leftSubtree = reconstructBstFromRange(lowerBound, rootValue, preOrderTraversalValues, currentSubtreeInfo); + + // Recursively reconstruct the right subtree within the range (rootValue, upperBound) using the updated root index. + TreeNode* rightSubtree = reconstructBstFromRange(rootValue, upperBound, preOrderTraversalValues, currentSubtreeInfo); + + // Create a new TreeNode with the current root value and the reconstructed left and right subtrees. + TreeNode* rootNode = new TreeNode(rootValue); + rootNode->left = leftSubtree; + rootNode->right = rightSubtree; + + return rootNode; +} + +// Function to delete the BST and free memory. +void deleteBst(TreeNode* root) { + if (root == nullptr) { + return; + } + deleteBst(root->left); + deleteBst(root->right); + delete root; +} + +int main() { + std::vector preOrderTraversalValues = {10, 5, 2, 7, 15, 12, 20}; + TreeInfo treeInfo(0); // Initialize treeInfo with root index 0 + TreeNode* root = reconstructBstFromRange(INT_MIN, INT_MAX, preOrderTraversalValues, treeInfo); + + // Printing the reconstructed BST is left as an exercise + + // Clean up memory + deleteBst(root); + + return 0; +} From 51711fd8ac8aaf446c6a740448209c3a530dff81 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 3 Oct 2023 22:27:22 +0530 Subject: [PATCH 1814/1894] add reconstruct bst in python --- Trees/Binary Search Trees/reconstruct_bst.py | 96 ++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Trees/Binary Search Trees/reconstruct_bst.py diff --git a/Trees/Binary Search Trees/reconstruct_bst.py b/Trees/Binary Search Trees/reconstruct_bst.py new file mode 100644 index 00000000..35b5ee6a --- /dev/null +++ b/Trees/Binary Search Trees/reconstruct_bst.py @@ -0,0 +1,96 @@ +''' + Reconstruct BST + The pre-order traversal of a Binary Tree is a traversal technique that starts at the tree's root node and visits nodes in the following order: + Current Node + Left Subtree + Right Subtree + + Given a non-empty array of integers representing the pre-order traversal of a Binary Search Tree (BST), + write a function that creates the relevant BST and returns its root node. + + The input array will contain the values of BST nodes in the order in which these nodes would be visited with a pre-order traversal. + + Sample Input: [10, 4, 2, 1, 5, 17, 19, 18] + Sample Output: + 10 + / \ + 4 17 + / \ \ + 2 5 19 + / / +1 18 + + The ReconstructBst function takes a slice preOrderTraversalValues which represents the pre-order traversal of a binary search tree. + It reconstructs the BST using a range-based approach. Here's how the algorithm works: + + The ReconstructBst function initializes a treeInfo struct to keep track of the current root index. + + The ReconstructBst function calls the reconstructBSTFromRange helper function, passing the minimum and maximum integer values + as the initial range, the pre-order traversal values, and the treeInfo struct. + + The reconstructBSTFromRange function first checks if the current root index has reached the end of the pre-order traversal values. + If so, it returns nil indicating an empty subtree. + + It retrieves the value of the current root from the pre-order traversal values. + + It checks if the root value is outside the valid range defined by the lower and upper bounds. If so, it returns + + The time complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function processes each node exactly once. + + The space complexity of the ReconstructBst function is O(n), where n is the number of nodes in the reconstructed BST. + This is because the function creates BST nodes and recursively calls itself to construct the left and right subtrees. + The space complexity is determined by the height of the BST, which can be at most n in the worst case for a skewed BST. + +''' +class TreeNode: + def __init__(self, val): + self.val = val + self.left = None + self.right = None + +class TreeInfo: + def __init__(self, root_idx): + self.root_idx = root_idx + +def reconstruct_bst(pre_order_traversal_values): + # Create a TreeInfo object to keep track of the current root index. + tree_info = TreeInfo(0) + + # Call the helper function to reconstruct the BST from the given range and return the result. + return reconstruct_bst_from_range(float('-inf'), float('inf'), pre_order_traversal_values, tree_info) + +def reconstruct_bst_from_range(lower_bound, upper_bound, pre_order_traversal_values, current_subtree_info): + # Check if the root index has reached the end of the pre-order traversal values. If so, return None indicating an empty subtree. + if current_subtree_info.root_idx == len(pre_order_traversal_values): + return None + + # Get the value of the current root from the pre-order traversal values. + root_value = pre_order_traversal_values[current_subtree_info.root_idx] + + # Check if the root value is out of the valid range defined by the lower and upper bounds. If so, return None indicating an invalid subtree. + if root_value < lower_bound or root_value >= upper_bound: + return None + + # Increment the root index to move to the next element in the pre-order traversal values. + current_subtree_info.root_idx += 1 + + # Recursively reconstruct the left subtree within the range (lower_bound, root_value) using the updated root index. + left_subtree = reconstruct_bst_from_range(lower_bound, root_value, pre_order_traversal_values, current_subtree_info) + + # Recursively reconstruct the right subtree within the range (root_value, upper_bound) using the updated root index. + right_subtree = reconstruct_bst_from_range(root_value, upper_bound, pre_order_traversal_values, current_subtree_info) + + # Create a new TreeNode with the current root value and the reconstructed left and right subtrees. + root_node = TreeNode(root_value) + root_node.left = left_subtree + root_node.right = right_subtree + + return root_node + +# Example usage: +pre_order_traversal_values = [10, 5, 2, 7, 15, 12, 20] +tree_info = TreeInfo(0) # Initialize tree_info with root index 0 +root = reconstruct_bst_from_range(float('-inf'), float('inf'), pre_order_traversal_values, tree_info) + +# Printing the reconstructed BST is left as an exercise From 5ce2844b15fa451817faf0f0380fef7c3bdb23a0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 4 Oct 2023 21:13:15 +0530 Subject: [PATCH 1815/1894] add river sizes in java --- Graphs/river_sizes.java | 176 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 Graphs/river_sizes.java diff --git a/Graphs/river_sizes.java b/Graphs/river_sizes.java new file mode 100644 index 00000000..92d15dc7 --- /dev/null +++ b/Graphs/river_sizes.java @@ -0,0 +1,176 @@ +/* + + You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only + 0's and 1's. Each 0 represent land and each 1 represent part of river. A river consists of any number of 1's + that are either horizontally or vertically adjacent (but not diagonally adjacent). + The number of adjacent 1's forming a river determine its size. + + Note that a river can twist. In other words, it doesn't have to be a straight vertical line or a straight + horizontal line; it can be L-shaped, for example. + + Write a function that returns an array of the sizes of all rivers represented in the input matrix. + The sizes don't need to be in any particular order. + + Sample Input:[ + [1, 0, 0, 1, 0], + [1, 0, 1, 0, 0], + [0, 0, 1, 0, 1], + [1, 0, 1, 0, 1], + [1, 0, 1, 1, 0], + ] + Output: [1, 2, 2, 2, 5] + + Explanation: + + 1. The function `RiverSizes` initializes an empty slice `sizes` to store the sizes of rivers found in the matrix. It also creates a 2D `visited` matrix of the same size as the input matrix to keep track of visited nodes. + + 2. The function then iterates over each cell in the matrix using nested loops. + + 3. If a cell has already been visited (marked as `true` in the `visited` matrix), the code continues to the next iteration to avoid processing it again. + + 4. If a cell has not been visited, the code calls the `traverseNode` function to explore the river connected to that cell and updates the `sizes` slice with the size of the river. + + 5. The `traverseNode` function takes the starting position (i, j) of a river, the matrix, the `visited` matrix, and the `sizes` slice as input. + + 6. It initializes a variable `currentRiverSize` to 0 to keep track of the size of the river being explored. + + 7. It maintains a queue (`nodesToExplore`) to store the nodes that need to be visited. It starts with the initial node (i, j). + + 8. The function enters a loop that continues until there are no more nodes to explore in the queue. + + 9. In each iteration, it dequeues the first node from the `nodesToExplore` queue and updates the current position (i, j) accordingly. + + 10. If the current node has already been visited, the code continues to the next iteration. + + 11. If the current node contains a value of 0 (indicating land), the code continues to the next iteration, as it's not part of the river. + + 12. If the current node contains a value of 1 (indicating a river), it increments the `currentRiverSize` by 1. + + 13. It then retrieves the unvisited neighboring nodes of the current node using the `getUnvisitedNeighbors` function and adds them to the `nodesToExplore` queue. + + 14. Once the loop finishes, if the `currentRiverSize` is greater than 0, it appends it to the `sizes` slice. + + 15. Finally, the `sizes` slice containing the sizes of all rivers is returned. + + 16. The `getUnvisitedNeighbors` function takes the current position (i, j), the matrix, and the `visited` matrix as input. + + 17. It checks the four neighboring cells (up, down, left, right) of the current cell and adds the unvisited neighbors to the `unvisitedNeighbors` slice. + + 18. The function returns the `unvisitedNeighbors` slice. + + The code essentially performs a depth-first search (DFS) traversal on the matrix to find connected regions of 1s (rivers) and keeps track of their sizes. The `visited` matrix helps avoid revisiting nodes that have already been processed, ensuring each river is counted only once. +*/ +import java.util.ArrayList; +import java.util.List; + +public class RiverSizes { + + public static List riverSizes(int[][] matrix) { + List sizes = new ArrayList<>(); + int numRows = matrix.length; + int numCols = matrix[0].length; + boolean[][] visited = new boolean[numRows][numCols]; + + // Iterate over each cell in the matrix + for (int i = 0; i < numRows; i++) { + for (int j = 0; j < numCols; j++) { + // If the cell has already been visited, continue to the next iteration + if (visited[i][j]) { + continue; + } + + // Explore the river connected to the current cell and update sizes + sizes = traverseNode(i, j, matrix, visited, sizes); + } + } + + return sizes; + } + + private static List traverseNode(int i, int j, int[][] matrix, boolean[][] visited, List sizes) { + int currentRiverSize = 0; + List nodesToExplore = new ArrayList<>(); + nodesToExplore.add(new int[]{i, j}); + + while (!nodesToExplore.isEmpty()) { + int[] currentNode = nodesToExplore.remove(0); + i = currentNode[0]; + j = currentNode[1]; + + // If the current node has already been visited, continue to the next iteration + if (visited[i][j]) { + continue; + } + + // Mark the current node as visited + visited[i][j] = true; + + // If the current node is land (0), continue to the next iteration + if (matrix[i][j] == 0) { + continue; + } + + // Increment the size of the current river + currentRiverSize++; + + // Get the unvisited neighboring nodes of the current node + List unvisitedNeighbors = getUnvisitedNeighbors(i, j, matrix, visited); + + // Add the unvisited neighbors to the nodesToExplore list + nodesToExplore.addAll(unvisitedNeighbors); + } + + // If the current river size is greater than 0, add it to the sizes list + if (currentRiverSize > 0) { + sizes.add(currentRiverSize); + } + + return sizes; + } + + private static List getUnvisitedNeighbors(int i, int j, int[][] matrix, boolean[][] visited) { + List unvisitedNeighbors = new ArrayList<>(); + + // Check the four neighboring cells (up, down, left, right) of the current cell + // and add unvisited neighbors to the unvisitedNeighbors list + + // Up neighbor + if (i > 0 && !visited[i - 1][j]) { + unvisitedNeighbors.add(new int[]{i - 1, j}); + } + + // Down neighbor + if (i < matrix.length - 1 && !visited[i + 1][j]) { + unvisitedNeighbors.add(new int[]{i + 1, j}); + } + + // Left neighbor + if (j > 0 && !visited[i][j - 1]) { + unvisitedNeighbors.add(new int[]{i, j - 1}); + } + + // Right neighbor + if (j < matrix[0].length - 1 && !visited[i][j + 1]) { + unvisitedNeighbors.add(new int[]{i, j + 1}); + } + + return unvisitedNeighbors; + } + + public static void main(String[] args) { + int[][] matrix = { + {1, 0, 0, 1, 0}, + {1, 0, 1, 0, 0}, + {0, 0, 1, 0, 1}, + {1, 0, 1, 0, 1}, + {1, 0, 1, 1, 0} + }; + + List sizes = riverSizes(matrix); + + // Printing the sizes of rivers + for (int size : sizes) { + System.out.print(size + " "); + } + } +} From 2a0c13fabc244e84e378d9e53c561a39fa98bf6f Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 5 Oct 2023 23:32:04 +0530 Subject: [PATCH 1816/1894] add min jumps in c++ --- Dynamic Programming/min_number_of_jumps.cpp | 77 +++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Dynamic Programming/min_number_of_jumps.cpp diff --git a/Dynamic Programming/min_number_of_jumps.cpp b/Dynamic Programming/min_number_of_jumps.cpp new file mode 100644 index 00000000..1fd064b6 --- /dev/null +++ b/Dynamic Programming/min_number_of_jumps.cpp @@ -0,0 +1,77 @@ +/* + The given code snippet calculates the minimum number of jumps required to reach the end of an array of integers. + Each element in the array represents the maximum distance you can jump from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an integer array `array` as input and returns the minimum number of jumps + required to reach the last element. + + 2. The code first checks if the length of the `array` is 1. If so, it means there's only one element, and we don't + need any jumps to reach the end. In this case, the function returns 0. + + 3. If the array has more than one element, the code proceeds with the jump calculation. + + 4. The variables `jumps`, `maxreach`, and `steps` are initialized. `jumps` keeps track of the total number of jumps + taken, `maxreach` represents the farthest position that can be reached in a single jump, and `steps` represents the + remaining steps until a new jump is required. + + 5. The loop starts from the second element (index 1) and iterates until the second-to-last element (index `len(array) - 1`). + The reason for stopping at the second-to-last element is that we don't need to take any additional jumps from there, as + we are already at the end. + + 6. For each iteration, the code checks if the current index plus the value at that index (`i + array[i]`) is greater + than the current `maxreach`. If so, it updates `maxreach` to the new value, representing the farthest position that + can be reached in a single jump. + + 7. It then decrements `steps` by 1, representing the steps taken in the current jump. + + 8. If `steps` becomes 0, it means the current jump is completed, and a new jump is required. So, it increments `jumps` + by 1 and updates `steps` with the number of steps required to reach the farthest position (i.e., `maxreach - i`). + + 9. After the loop completes, the function returns `jumps + 1`. The `+1` is added because the loop doesn't consider the + last element in the array (as we don't need an additional jump from there), so we need to add one more jump to reach the last element. + + In summary, the code efficiently calculates the minimum number of jumps required to reach the last element in the array + by simulating the jumps and keeping track of the farthest position that can be reached in each jump. The final result + is the total number of jumps taken to reach the end. +*/ +#include +#include + +int MinNumberOfJumpsOptimal(std::vector& array) { + // If the array has only one element, no jumps are needed. + if (array.size() == 1) { + return 0; + } + + // Initialize variables to keep track of jumps, maximum reachable position, and remaining steps in a jump. + int jumps = 0; + int maxreach = array[0]; + int steps = array[0]; + + // Iterate through the array to calculate the minimum number of jumps. + // We stop at the second-to-last element as we don't need an additional jump from there. + for (int i = 1; i < array.size() - 1; i++) { + // Update the maximum reachable position if the current position plus the value at that index is greater. + if (i + array[i] > maxreach) { + maxreach = i + array[i]; + } + + // Decrement the remaining steps in the current jump. + steps--; + + // If the current jump is completed (steps becomes 0), calculate the new jump. + if (steps == 0) { + // Increment jumps to count the completed jump. + jumps++; + + // Update steps to the number of steps required to reach the farthest position. + steps = maxreach - i; + } + } + + // The minimum number of jumps to reach the last element is the total number of jumps taken plus one + // because the loop doesn't consider the last element (as we don't need an additional jump from there). + return jumps + 1; +} From 6cabf7aace2e92b54f67bfca9e895a26755f0b02 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 5 Oct 2023 23:32:18 +0530 Subject: [PATCH 1817/1894] add min jumps in java --- Dynamic Programming/min_number_of_jumps.java | 77 ++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Dynamic Programming/min_number_of_jumps.java diff --git a/Dynamic Programming/min_number_of_jumps.java b/Dynamic Programming/min_number_of_jumps.java new file mode 100644 index 00000000..d2ab7a74 --- /dev/null +++ b/Dynamic Programming/min_number_of_jumps.java @@ -0,0 +1,77 @@ +public class min_number_of_jumps { + +} +/* + The given code snippet calculates the minimum number of jumps required to reach the end of an array of integers. + Each element in the array represents the maximum distance you can jump from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an integer array `array` as input and returns the minimum number of jumps + required to reach the last element. + + 2. The code first checks if the length of the `array` is 1. If so, it means there's only one element, and we don't + need any jumps to reach the end. In this case, the function returns 0. + + 3. If the array has more than one element, the code proceeds with the jump calculation. + + 4. The variables `jumps`, `maxreach`, and `steps` are initialized. `jumps` keeps track of the total number of jumps + taken, `maxreach` represents the farthest position that can be reached in a single jump, and `steps` represents the + remaining steps until a new jump is required. + + 5. The loop starts from the second element (index 1) and iterates until the second-to-last element (index `len(array) - 1`). + The reason for stopping at the second-to-last element is that we don't need to take any additional jumps from there, as + we are already at the end. + + 6. For each iteration, the code checks if the current index plus the value at that index (`i + array[i]`) is greater + than the current `maxreach`. If so, it updates `maxreach` to the new value, representing the farthest position that + can be reached in a single jump. + + 7. It then decrements `steps` by 1, representing the steps taken in the current jump. + + 8. If `steps` becomes 0, it means the current jump is completed, and a new jump is required. So, it increments `jumps` + by 1 and updates `steps` with the number of steps required to reach the farthest position (i.e., `maxreach - i`). + + 9. After the loop completes, the function returns `jumps + 1`. The `+1` is added because the loop doesn't consider the + last element in the array (as we don't need an additional jump from there), so we need to add one more jump to reach the last element. + + In summary, the code efficiently calculates the minimum number of jumps required to reach the last element in the array + by simulating the jumps and keeping track of the farthest position that can be reached in each jump. The final result + is the total number of jumps taken to reach the end. +*/ +public static int minNumberOfJumpsOptimal(int[] array) { + // If the array has only one element, no jumps are needed. + if (array.length == 1) { + return 0; + } + + // Initialize variables to keep track of jumps, maximum reachable position, and remaining steps in a jump. + int jumps = 0; + int maxReach = array[0]; + int steps = array[0]; + + // Iterate through the array to calculate the minimum number of jumps. + // We stop at the second-to-last element as we don't need an additional jump from there. + for (int i = 1; i < array.length - 1; i++) { + // Update the maximum reachable position if the current position plus the value at that index is greater. + if (i + array[i] > maxReach) { + maxReach = i + array[i]; + } + + // Decrement the remaining steps in the current jump. + steps--; + + // If the current jump is completed (steps becomes 0), calculate the new jump. + if (steps == 0) { + // Increment jumps to count the completed jump. + jumps++; + + // Update steps to the number of steps required to reach the farthest position. + steps = maxReach - i; + } + } + + // The minimum number of jumps to reach the last element is the total number of jumps taken plus one + // because the loop doesn't consider the last element (as we don't need an additional jump from there). + return jumps + 1; +} From b8f56d51bd2b1ee48164b09ed17d3d336a759813 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 5 Oct 2023 23:32:25 +0530 Subject: [PATCH 1818/1894] add min jumps in js --- Dynamic Programming/min_number_of_jumps.js | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Dynamic Programming/min_number_of_jumps.js diff --git a/Dynamic Programming/min_number_of_jumps.js b/Dynamic Programming/min_number_of_jumps.js new file mode 100644 index 00000000..a19ec60b --- /dev/null +++ b/Dynamic Programming/min_number_of_jumps.js @@ -0,0 +1,74 @@ +/* + The given code snippet calculates the minimum number of jumps required to reach the end of an array of integers. + Each element in the array represents the maximum distance you can jump from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an integer array `array` as input and returns the minimum number of jumps + required to reach the last element. + + 2. The code first checks if the length of the `array` is 1. If so, it means there's only one element, and we don't + need any jumps to reach the end. In this case, the function returns 0. + + 3. If the array has more than one element, the code proceeds with the jump calculation. + + 4. The variables `jumps`, `maxreach`, and `steps` are initialized. `jumps` keeps track of the total number of jumps + taken, `maxreach` represents the farthest position that can be reached in a single jump, and `steps` represents the + remaining steps until a new jump is required. + + 5. The loop starts from the second element (index 1) and iterates until the second-to-last element (index `len(array) - 1`). + The reason for stopping at the second-to-last element is that we don't need to take any additional jumps from there, as + we are already at the end. + + 6. For each iteration, the code checks if the current index plus the value at that index (`i + array[i]`) is greater + than the current `maxreach`. If so, it updates `maxreach` to the new value, representing the farthest position that + can be reached in a single jump. + + 7. It then decrements `steps` by 1, representing the steps taken in the current jump. + + 8. If `steps` becomes 0, it means the current jump is completed, and a new jump is required. So, it increments `jumps` + by 1 and updates `steps` with the number of steps required to reach the farthest position (i.e., `maxreach - i`). + + 9. After the loop completes, the function returns `jumps + 1`. The `+1` is added because the loop doesn't consider the + last element in the array (as we don't need an additional jump from there), so we need to add one more jump to reach the last element. + + In summary, the code efficiently calculates the minimum number of jumps required to reach the last element in the array + by simulating the jumps and keeping track of the farthest position that can be reached in each jump. The final result + is the total number of jumps taken to reach the end. +*/ +function minNumberOfJumpsOptimal(array) { + // If the array has only one element, no jumps are needed. + if (array.length === 1) { + return 0; + } + + // Initialize variables to keep track of jumps, maximum reachable position, and remaining steps in a jump. + let jumps = 0; + let maxReach = array[0]; + let steps = array[0]; + + // Iterate through the array to calculate the minimum number of jumps. + // We stop at the second-to-last element as we don't need an additional jump from there. + for (let i = 1; i < array.length - 1; i++) { + // Update the maximum reachable position if the current position plus the value at that index is greater. + if (i + array[i] > maxReach) { + maxReach = i + array[i]; + } + + // Decrement the remaining steps in the current jump. + steps--; + + // If the current jump is completed (steps becomes 0), calculate the new jump. + if (steps === 0) { + // Increment jumps to count the completed jump. + jumps++; + + // Update steps to the number of steps required to reach the farthest position. + steps = maxReach - i; + } + } + + // The minimum number of jumps to reach the last element is the total number of jumps taken plus one + // because the loop doesn't consider the last element (as we don't need an additional jump from there). + return jumps + 1; +} From d422b93ede15328ac87a50d71747c91cdb757870 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 5 Oct 2023 23:32:33 +0530 Subject: [PATCH 1819/1894] add min jumps in py --- Dynamic Programming/min_number_of_jumps.py | 69 ++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Dynamic Programming/min_number_of_jumps.py diff --git a/Dynamic Programming/min_number_of_jumps.py b/Dynamic Programming/min_number_of_jumps.py new file mode 100644 index 00000000..c6a83340 --- /dev/null +++ b/Dynamic Programming/min_number_of_jumps.py @@ -0,0 +1,69 @@ +''' + The given code snippet calculates the minimum number of jumps required to reach the end of an array of integers. + Each element in the array represents the maximum distance you can jump from that position. + + Here's a step-by-step explanation of the code: + + 1. The function `MinNumberOfJumps` takes an integer array `array` as input and returns the minimum number of jumps + required to reach the last element. + + 2. The code first checks if the length of the `array` is 1. If so, it means there's only one element, and we don't + need any jumps to reach the end. In this case, the function returns 0. + + 3. If the array has more than one element, the code proceeds with the jump calculation. + + 4. The variables `jumps`, `maxreach`, and `steps` are initialized. `jumps` keeps track of the total number of jumps + taken, `maxreach` represents the farthest position that can be reached in a single jump, and `steps` represents the + remaining steps until a new jump is required. + + 5. The loop starts from the second element (index 1) and iterates until the second-to-last element (index `len(array) - 1`). + The reason for stopping at the second-to-last element is that we don't need to take any additional jumps from there, as + we are already at the end. + + 6. For each iteration, the code checks if the current index plus the value at that index (`i + array[i]`) is greater + than the current `maxreach`. If so, it updates `maxreach` to the new value, representing the farthest position that + can be reached in a single jump. + + 7. It then decrements `steps` by 1, representing the steps taken in the current jump. + + 8. If `steps` becomes 0, it means the current jump is completed, and a new jump is required. So, it increments `jumps` + by 1 and updates `steps` with the number of steps required to reach the farthest position (i.e., `maxreach - i`). + + 9. After the loop completes, the function returns `jumps + 1`. The `+1` is added because the loop doesn't consider the + last element in the array (as we don't need an additional jump from there), so we need to add one more jump to reach the last element. + + In summary, the code efficiently calculates the minimum number of jumps required to reach the last element in the array + by simulating the jumps and keeping track of the farthest position that can be reached in each jump. The final result + is the total number of jumps taken to reach the end. +''' +def min_number_of_jumps_optimal(array): + # If the array has only one element, no jumps are needed. + if len(array) == 1: + return 0 + + # Initialize variables to keep track of jumps, maximum reachable position, and remaining steps in a jump. + jumps = 0 + max_reach = array[0] + steps = array[0] + + # Iterate through the array to calculate the minimum number of jumps. + # We stop at the second-to-last element as we don't need an additional jump from there. + for i in range(1, len(array) - 1): + # Update the maximum reachable position if the current position plus the value at that index is greater. + if i + array[i] > max_reach: + max_reach = i + array[i] + + # Decrement the remaining steps in the current jump. + steps -= 1 + + # If the current jump is completed (steps becomes 0), calculate the new jump. + if steps == 0: + # Increment jumps to count the completed jump. + jumps += 1 + + # Update steps to the number of steps required to reach the farthest position. + steps = max_reach - i + + # The minimum number of jumps to reach the last element is the total number of jumps taken plus one + # because the loop doesn't consider the last element (as we don't need an additional jump from there). + return jumps + 1 From 0c57b02f4d87e0b0ae687d7b0e5b79cc39d7d09a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 7 Oct 2023 20:58:50 +0530 Subject: [PATCH 1820/1894] add min ways to make string pallindrome in java --- .../min_steps_to_make_string_palindrome.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Dynamic Programming/min_steps_to_make_string_palindrome.java diff --git a/Dynamic Programming/min_steps_to_make_string_palindrome.java b/Dynamic Programming/min_steps_to_make_string_palindrome.java new file mode 100644 index 00000000..7ab3e585 --- /dev/null +++ b/Dynamic Programming/min_steps_to_make_string_palindrome.java @@ -0,0 +1,75 @@ +/* + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) +*/ +import java.util.Scanner; + +public class Main { + + // Function to calculate the length of the Longest Common Subsequence (LCS) of two strings + public static int lcs(String s1, String s2) { + int n = s1.length(); + int m = s2.length(); + + // Create a 2D array dp to store the lengths of LCS + int[][] dp = new int[n+1][m+1]; + + // Initialize the first row and first column to 0 + for (int i = 0; i <= n; i++) { + dp[i][0] = 0; + } + for (int j = 0; j <= m; j++) { + dp[0][j] = 0; + } + + // Fill the dp array using dynamic programming + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (s1.charAt(i-1) == s2.charAt(j-1)) { + // If characters at the current positions match, increase the length of LCS by 1 + dp[i][j] = 1 + dp[i-1][j-1]; + } else { + // Take the maximum length from the previous positions + dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); + } + } + } + + // Return the length of the LCS of s1 and s2 + return dp[n][m]; + } + + // Function to calculate the minimum number of insertions required to make a string palindrome + public static int minInsertions(String s) { + StringBuilder reverseSb = new StringBuilder(s); + reverseSb.reverse(); // Reverse the string s + String reverseS = reverseSb.toString(); + + int lcsLength = lcs(s, reverseS); // Find the length of the LCS of s and its reverse + return s.length() - lcsLength; // Return the number of insertions required to make s a palindrome + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + String s = scanner.nextLine(); // Read input string + int ans = minInsertions(s); // Calculate the minimum number of insertions required + System.out.println(ans); // Print the result + scanner.close(); + } +} From 0bffac3014716ed9ec75c5d0aab3ad14d1d126f6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 8 Oct 2023 21:30:39 +0530 Subject: [PATCH 1821/1894] add min steps to makle string pallindrome --- .../min_steps_to_make_string_palindrome.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Dynamic Programming/min_steps_to_make_string_palindrome.py diff --git a/Dynamic Programming/min_steps_to_make_string_palindrome.py b/Dynamic Programming/min_steps_to_make_string_palindrome.py new file mode 100644 index 00000000..e79d1cde --- /dev/null +++ b/Dynamic Programming/min_steps_to_make_string_palindrome.py @@ -0,0 +1,51 @@ +''' + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) +''' +# Function to calculate the length of the Longest Common Subsequence (LCS) of two strings +def lcs(s1, s2): + n, m = len(s1), len(s2) + + # Create a 2D list dp to store the lengths of LCS + dp = [[0] * (m + 1) for _ in range(n + 1)] + + # Fill the dp array using dynamic programming + for i in range(1, n + 1): + for j in range(1, m + 1): + if s1[i - 1] == s2[j - 1]: + # If characters at the current positions match, increase the length of LCS by 1 + dp[i][j] = 1 + dp[i - 1][j - 1] + else: + # Take the maximum length from the previous positions + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + + # Return the length of the LCS of s1 and s2 + return dp[n][m] + +# Function to calculate the minimum number of insertions required to make a string palindrome +def min_insertions(s): + reverse_s = s[::-1] # Reverse the string s + + lcs_length = lcs(s, reverse_s) # Find the length of the LCS of s and its reverse + return len(s) - lcs_length # Return the number of insertions required to make s a palindrome + +if __name__ == "__main__": + s = input() # Read input string + ans = min_insertions(s) # Calculate the minimum number of insertions required + print(ans) # Print the result From 949689fc82b805e42a52c98986d509699295a296 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 9 Oct 2023 23:17:07 +0530 Subject: [PATCH 1822/1894] add min steps to make string pallindrome in js --- .../min_steps_to_make_string_pallindrome.js | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Dynamic Programming/min_steps_to_make_string_pallindrome.js diff --git a/Dynamic Programming/min_steps_to_make_string_pallindrome.js b/Dynamic Programming/min_steps_to_make_string_pallindrome.js new file mode 100644 index 00000000..772cfc9d --- /dev/null +++ b/Dynamic Programming/min_steps_to_make_string_pallindrome.js @@ -0,0 +1,57 @@ +/* + Given a string, find the minimum number of insertions needed to make it a palindrome. + + Sample Input: "abcde" + Sample Output: 4 + Explanation: The minimum insertions required are 'edcb' -> "abcdecb", resulting in a palindrome. + + Approach: + We can solve this problem using dynamic programming. + Let's define a 2D table, dp, where dp[i][j] represents the minimum number of insertions needed to make the substring from index i to j a palindrome. + If the characters at indices i and j are equal, then dp[i][j] = dp[i+1][j-1]. + Otherwise, we have two options: + 1. Insert the character at index i at the end, i.e., dp[i][j] = dp[i][j-1] + 1. + 2. Insert the character at index j at the beginning, i.e., dp[i][j] = dp[i+1][j] + 1. + We take the minimum of these two options as the minimum number of insertions required for the substring from index i to j. + Finally, the minimum number of insertions needed for the entire string is dp[0][n-1], where n is the length of the string. + + Time complexity: O(n^2) + Space complexity: O(n^2) +*/ +// Function to calculate the length of the Longest Common Subsequence (LCS) of two strings +function lcs(s1, s2) { + const n = s1.length; + const m = s2.length; + + // Create a 2D array dp to store the lengths of LCS + const dp = new Array(n + 1).fill(0).map(() => new Array(m + 1).fill(0)); + + // Fill the dp array using dynamic programming + for (let i = 1; i <= n; i++) { + for (let j = 1; j <= m; j++) { + if (s1[i - 1] === s2[j - 1]) { + // If characters at the current positions match, increase the length of LCS by 1 + dp[i][j] = 1 + dp[i - 1][j - 1]; + } else { + // Take the maximum length from the previous positions + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + // Return the length of the LCS of s1 and s2 + return dp[n][m]; +} + +// Function to calculate the minimum number of insertions required to make a string palindrome +function minInsertions(s) { + const reverseS = s.split("").reverse().join(""); // Reverse the string s + + const lcsLength = lcs(s, reverseS); // Find the length of the LCS of s and its reverse + return s.length - lcsLength; // Return the number of insertions required to make s a palindrome +} + +// Example usage: +const input = "abcde"; +const result = minInsertions(input); // Calculate the minimum number of insertions required +console.log(result); // Print the result From f3992912b5c13934ea5e59610ce83c91d8caf0db Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 10 Oct 2023 22:46:54 +0530 Subject: [PATCH 1823/1894] add documentation --- .../longest_pallindromic_substring.go | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/Dynamic Programming/longest_pallindromic_substring.go b/Dynamic Programming/longest_pallindromic_substring.go index d923ec7e..6995afc6 100644 --- a/Dynamic Programming/longest_pallindromic_substring.go +++ b/Dynamic Programming/longest_pallindromic_substring.go @@ -21,35 +21,46 @@ import ( "fmt" ) +// LongestPalindromicSubstring finds the length of the longest palindromic substring in a given string. func LongestPalindromicSubstring(Array string) int { n := len(Array) + + // Create a 2D boolean array L to store whether substrings are palindromes. L := make([][]bool, n) for i := range L { - L[i] = make([]bool, n) // defaults to false + L[i] = make([]bool, n) // Defaults to false } - max := 1 - for i := 0; i < n - 1; i++ { - L[i][i] = true - if Array[i] == Array[i + 1] { - L[i][i + 1] = true - max = 2 + + max := 1 // Initialize the maximum palindrome length to 1 (single characters are palindromes) + + // Initialize the base cases for substrings of length 1 and 2. + for i := 0; i < n-1; i++ { + L[i][i] = true // Single characters are palindromes + if Array[i] == Array[i+1] { + L[i][i+1] = true // Check for palindromes of length 2 + max = 2 // Update the maximum palindrome length } } + + // Check for palindromes of length 3 and greater. for k := 3; k <= n; k++ { - for i := 1; i < n - k + 1; i++ { + for i := 0; i < n-k+1; i++ { j := i + k - 1 - if Array[i] == Array[j] && L[i + 1][j - 1] { - L[i][j] = true - max = k + + // Check if the characters at the ends of the current substring match and if the substring inside is a palindrome. + if Array[i] == Array[j] && L[i+1][j-1] { + L[i][j] = true // Mark the current substring as a palindrome + max = k // Update the maximum palindrome length } else { - L[i][j] = false + L[i][j] = false // Mark the current substring as not a palindrome } } } - return max + + return max // Return the length of the longest palindromic substring } func main() { + // Example usage: fmt.Print(LongestPalindromicSubstring("babad")) - -} \ No newline at end of file +} From a3ab2660df913355199f073535b1073fda7f8fc8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 10 Oct 2023 22:48:16 +0530 Subject: [PATCH 1824/1894] add longest palliondromic substring in js --- .../longest_pallindromic_substring.js | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Dynamic Programming/longest_pallindromic_substring.js diff --git a/Dynamic Programming/longest_pallindromic_substring.js b/Dynamic Programming/longest_pallindromic_substring.js new file mode 100644 index 00000000..6e4d7310 --- /dev/null +++ b/Dynamic Programming/longest_pallindromic_substring.js @@ -0,0 +1,54 @@ +/* + Given a string s, return the longest palindromic substring in s. + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +*/ +function longestPalindromicSubstring(Array) { + const n = Array.length; + + // Create a 2D boolean array L to store whether substrings are palindromes. + const L = Array.from({ length: n }, () => Array(n).fill(false)); + + let max_length = 1; // Initialize the maximum palindrome length to 1 (single characters are palindromes) + + // Initialize the base cases for substrings of length 1 and 2. + for (let i = 0; i < n - 1; i++) { + L[i][i] = true; // Single characters are palindromes + if (Array[i] === Array[i + 1]) { + L[i][i + 1] = true; // Check for palindromes of length 2 + max_length = 2; // Update the maximum palindrome length + } + } + + // Check for palindromes of length 3 and greater. + for (let k = 3; k <= n; k++) { + for (let i = 0; i < n - k + 1; i++) { + const j = i + k - 1; + + // Check if the characters at the ends of the current substring match + // and if the substring inside is a palindrome. + if (Array[i] === Array[j] && L[i + 1][j - 1]) { + L[i][j] = true; // Mark the current substring as a palindrome + max_length = k; // Update the maximum palindrome length + } + } + } + + return max_length; // Return the length of the longest palindromic substring +} + +// Example usage: +const result = longestPalindromicSubstring("babad"); +console.log(result); // Output: 3 ("bab" or "aba" is the longest palindromic substring) From 95f8f40e50fc0b24514d442c88dcca938f1b1e28 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 10 Oct 2023 22:48:26 +0530 Subject: [PATCH 1825/1894] add longest pallindromic substring in py --- .../longest_pallindromic_substring.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Dynamic Programming/longest_pallindromic_substring.py diff --git a/Dynamic Programming/longest_pallindromic_substring.py b/Dynamic Programming/longest_pallindromic_substring.py new file mode 100644 index 00000000..ea203c50 --- /dev/null +++ b/Dynamic Programming/longest_pallindromic_substring.py @@ -0,0 +1,48 @@ +''' + Given a string s, return the longest palindromic substring in s. + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +''' +def longest_palindromic_substring(Array): + n = len(Array) + + # Create a 2D boolean array L to store whether substrings are palindromes. + L = [[False] * n for _ in range(n)] + + max_length = 1 # Initialize the maximum palindrome length to 1 (single characters are palindromes) + + # Initialize the base cases for substrings of length 1 and 2. + for i in range(n - 1): + L[i][i] = True # Single characters are palindromes + if Array[i] == Array[i + 1]: + L[i][i + 1] = True # Check for palindromes of length 2 + max_length = 2 # Update the maximum palindrome length + + # Check for palindromes of length 3 and greater. + for k in range(3, n + 1): + for i in range(n - k + 1): + j = i + k - 1 + + # Check if the characters at the ends of the current substring match + # and if the substring inside is a palindrome. + if Array[i] == Array[j] and L[i + 1][j - 1]: + L[i][j] = True # Mark the current substring as a palindrome + max_length = k # Update the maximum palindrome length + + return max_length # Return the length of the longest palindromic substring + +# Example usage: +result = longest_palindromic_substring("babad") +print(result) # Output: 3 ("bab" or "aba" is the longest palindromic substring) From f1b27285a8e62c25af8f583b3094ab6e1b3b867e Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 11 Oct 2023 21:29:26 +0530 Subject: [PATCH 1826/1894] add longest pallindromic substring in c++ --- .../longest_pallindromic_substring.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Dynamic Programming/longest_pallindromic_substring.cpp diff --git a/Dynamic Programming/longest_pallindromic_substring.cpp b/Dynamic Programming/longest_pallindromic_substring.cpp new file mode 100644 index 00000000..8b82976a --- /dev/null +++ b/Dynamic Programming/longest_pallindromic_substring.cpp @@ -0,0 +1,63 @@ +/* + Given a string s, return the longest palindromic substring in s. + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +*/ +#include +#include +#include + +// Function to find the length of the longest palindromic substring +int longestPalindromicSubstring(const std::string& Array) { + int n = Array.length(); + + // Create a 2D boolean array L to store whether substrings are palindromes. + std::vector> L(n, std::vector(n, false)); + + int max_length = 1; // Initialize the maximum palindrome length to 1 (single characters are palindromes) + + // Initialize the base cases for substrings of length 1 and 2. + for (int i = 0; i < n - 1; i++) { + L[i][i] = true; // Single characters are palindromes + if (Array[i] == Array[i + 1]) { + L[i][i + 1] = true; // Check for palindromes of length 2 + max_length = 2; // Update the maximum palindrome length + } + } + + // Check for palindromes of length 3 and greater. + for (int k = 3; k <= n; k++) { + for (int i = 0; i < n - k + 1; i++) { + int j = i + k - 1; + + // Check if the characters at the ends of the current substring match + // and if the substring inside is a palindrome. + if (Array[i] == Array[j] && L[i + 1][j - 1]) { + L[i][j] = true; // Mark the current substring as a palindrome + max_length = k; // Update the maximum palindrome length + } + } + } + + return max_length; // Return the length of the longest palindromic substring +} + +int main() { + // Example usage: + std::string input = "babad"; + int result = longestPalindromicSubstring(input); + std::cout << result << std::endl; // Output: 3 ("bab" or "aba" is the longest palindromic substring) + return 0; +} From 80e982ebf6031f46be9f8c16c39edea9a40cc1c2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 11 Oct 2023 21:29:58 +0530 Subject: [PATCH 1827/1894] add ongest pallindromic substring in java --- .../longest_pallindromic_substring.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Dynamic Programming/longest_pallindromic_substring.java diff --git a/Dynamic Programming/longest_pallindromic_substring.java b/Dynamic Programming/longest_pallindromic_substring.java new file mode 100644 index 00000000..5f0e61d3 --- /dev/null +++ b/Dynamic Programming/longest_pallindromic_substring.java @@ -0,0 +1,60 @@ +/* + Given a string s, return the longest palindromic substring in s. + + Example 1: + Input: s = "babad" + Output: "bab" + Explanation: "aba" is also a valid answer. + + Example 2: + Input: s = "cbbd" + Output: "bb" + + + Constraints: + 1 <= s.length <= 1000 + s consist of only digits and English letters. +*/ +public class LongestPalindromicSubstring { + // Function to find the length of the longest palindromic substring + public static int longestPalindromicSubstring(String Array) { + int n = Array.length(); + + // Create a 2D boolean array L to store whether substrings are palindromes. + boolean[][] L = new boolean[n][n]; + + int max_length = 1; // Initialize the maximum palindrome length to 1 (single characters are palindromes) + + // Initialize the base cases for substrings of length 1 and 2. + for (int i = 0; i < n - 1; i++) { + L[i][i] = true; // Single characters are palindromes + if (Array.charAt(i) == Array.charAt(i + 1)) { + L[i][i + 1] = true; // Check for palindromes of length 2 + max_length = 2; // Update the maximum palindrome length + } + } + + // Check for palindromes of length 3 and greater. + for (int k = 3; k <= n; k++) { + for (int i = 0; i < n - k + 1; i++) { + int j = i + k - 1; + + // Check if the characters at the ends of the current substring match + // and if the substring inside is a palindrome. + if (Array.charAt(i) == Array.charAt(j) && L[i + 1][j - 1]) { + L[i][j] = true; // Mark the current substring as a palindrome + max_length = k; // Update the maximum palindrome length + } + } + } + + return max_length; // Return the length of the longest palindromic substring + } + + public static void main(String[] args) { + // Example usage: + String input = "babad"; + int result = longestPalindromicSubstring(input); + System.out.println(result); // Output: 3 ("bab" or "aba" is the longest palindromic substring) + } +} From 20611c3bae9ae6127c2173b46b3adfe79aa17261 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 12 Oct 2023 22:27:02 +0530 Subject: [PATCH 1828/1894] add comments --- Dynamic Programming/edit_distance_dp.cpp | 32 ++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/Dynamic Programming/edit_distance_dp.cpp b/Dynamic Programming/edit_distance_dp.cpp index f6ba8eca..14e70c51 100644 --- a/Dynamic Programming/edit_distance_dp.cpp +++ b/Dynamic Programming/edit_distance_dp.cpp @@ -13,40 +13,52 @@ // Porgram Author : Abhisek Kumar Gupta #include using namespace std; + +// Function to find the minimum edit distance between two strings int find_edit_distance(string s1, string s2, int l1, int l2){ + // Create a 2D array dp to store the edit distances int dp[100][100] = {}; + + // Initialize the base cases for empty strings for(int i = 0; i <= l1; i++){ - dp[i][0] = i; + dp[i][0] = i; // Minimum edit distance for transforming s1[0...i] to an empty string } for(int i = 0; i <= l2; i++){ - dp[0][i] = i; + dp[0][i] = i; // Minimum edit distance for transforming an empty string to s2[0...i] } + + // Calculate the edit distance for the rest of the strings for(int i = 1; i <= l1; i++){ for(int j = 1; j <= l2; j++){ if(s1[i] == s2[j]) - dp[i][j] = dp[i - 1][j - 1]; + dp[i][j] = dp[i - 1][j - 1]; // No edit required if characters match else{ - int del = dp[i][j - 1]; - int replace = dp[i - 1][j - 1]; - int insert = dp[i - 1][j]; - dp[i][j] = min(del, min(replace, insert)) + 1; + int del = dp[i][j - 1]; // Deletion (from s2) + int replace = dp[i - 1][j - 1]; // Replacement (of s1[i] with s2[j]) + int insert = dp[i - 1][j]; // Insertion (into s1) + dp[i][j] = min(del, min(replace, insert)) + 1; // Choose the minimum of the three operations } } } + + // Print the edit distance matrix (optional) for(int i = 0; i <= l1; i++){ for(int j = 0; j <= l2; j++){ - cout << setw(5) < Date: Thu, 12 Oct 2023 22:28:30 +0530 Subject: [PATCH 1829/1894] add edit distance in go --- Dynamic Programming/edit_distance_dp.go | 68 +++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Dynamic Programming/edit_distance_dp.go diff --git a/Dynamic Programming/edit_distance_dp.go b/Dynamic Programming/edit_distance_dp.go new file mode 100644 index 00000000..22aea047 --- /dev/null +++ b/Dynamic Programming/edit_distance_dp.go @@ -0,0 +1,68 @@ +/* + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Dynamic Programming Solution : TC O(n^2) +package main + +import ( + "fmt" +) + +// findEditDistance finds the minimum edit distance between two strings. +func findEditDistance(s1, s2 string) int { + l1, l2 := len(s1), len(s2) + + // Create a 2D array dp to store the edit distances. + dp := make([][]int, l1+1) + for i := range dp { + dp[i] = make([]int, l2+1) + } + + // Initialize the base cases for empty strings. + for i := 0; i <= l1; i++ { + dp[i][0] = i // Minimum edit distance for transforming s1[0...i] to an empty string. + } + for i := 0; i <= l2; i++ { + dp[0][i] = i // Minimum edit distance for transforming an empty string to s2[0...i]. + } + + // Calculate the edit distance for the rest of the strings. + for i := 1; i <= l1; i++ { + for j := 1; j <= l2; j++ { + if s1[i-1] == s2[j-1] { + dp[i][j] = dp[i-1][j-1] // No edit required if characters match. + } else { + del := dp[i][j-1] // Deletion (from s2). + replace := dp[i-1][j-1] // Replacement (of s1[i] with s2[j]). + insert := dp[i-1][j] // Insertion (into s1). + dp[i][j] = min(del, min(replace, insert)) + 1 // Choose the minimum of the three operations. + } + } + } + + // Print the edit distance matrix (optional). + for i := 0; i <= l1; i++ { + for j := 0; j <= l2; j++ { + fmt.Printf("%5d ", dp[i][j]) + } + fmt.Println() + } + + return dp[l1][l2] // Return the minimum edit distance. +} + +func main() { + s1 := "abhisek" + s2 := "tsunade" + + result := findEditDistance(s1, s2) + fmt.Printf("Minimum Edit Distance: %d\n", result) +} From 008b13bd03b6ca1470c718d15133f0c420da576a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 12 Oct 2023 22:29:38 +0530 Subject: [PATCH 1830/1894] add edit distance in java --- Dynamic Programming/edit_distance_dp.java | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Dynamic Programming/edit_distance_dp.java diff --git a/Dynamic Programming/edit_distance_dp.java b/Dynamic Programming/edit_distance_dp.java new file mode 100644 index 00000000..897015e9 --- /dev/null +++ b/Dynamic Programming/edit_distance_dp.java @@ -0,0 +1,63 @@ +/* + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Dynamic Programming Solution : TC O(n^2) +public class EditDistance { + + // Function to find the minimum edit distance between two strings + public static int findEditDistance(String s1, String s2) { + int l1 = s1.length(); + int l2 = s2.length(); + + // Create a 2D array dp to store the edit distances + int[][] dp = new int[l1 + 1][l2 + 1]; + + // Initialize the base cases for empty strings + for (int i = 0; i <= l1; i++) { + dp[i][0] = i; // Minimum edit distance for transforming s1[0...i] to an empty string + } + for (int i = 0; i <= l2; i++) { + dp[0][i] = i; // Minimum edit distance for transforming an empty string to s2[0...i] + } + + // Calculate the edit distance for the rest of the strings + for (int i = 1; i <= l1; i++) { + for (int j = 1; j <= l2; j++) { + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; // No edit required if characters match + } else { + int del = dp[i][j - 1]; // Deletion (from s2) + int replace = dp[i - 1][j - 1]; // Replacement (of s1[i] with s2[j]) + int insert = dp[i - 1][j]; // Insertion (into s1) + dp[i][j] = Math.min(del, Math.min(replace, insert)) + 1; // Choose the minimum of the three operations + } + } + } + + // Print the edit distance matrix (optional) + for (int i = 0; i <= l1; i++) { + for (int j = 0; j <= l2; j++) { + System.out.printf("%5d ", dp[i][j]); + } + System.out.println(); + } + + return dp[l1][l2]; // Return the minimum edit distance + } + + public static void main(String[] args) { + String s1 = "abhisek"; + String s2 = "tsunade"; + + int result = findEditDistance(s1, s2); + System.out.println("Minimum Edit Distance: " + result); + } +} From 545f24fbb95d962f5e14597a9db545793583ddc0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 13 Oct 2023 23:03:27 +0530 Subject: [PATCH 1831/1894] add edit distance in javascript --- Dynamic Programming/edit_distance_dp.js | 58 +++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Dynamic Programming/edit_distance_dp.js diff --git a/Dynamic Programming/edit_distance_dp.js b/Dynamic Programming/edit_distance_dp.js new file mode 100644 index 00000000..3718aa57 --- /dev/null +++ b/Dynamic Programming/edit_distance_dp.js @@ -0,0 +1,58 @@ +/* + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Dynamic Programming Solution : TC O(n^2) +// Function to find the minimum edit distance between two strings +function findEditDistance(s1, s2) { + const l1 = s1.length; + const l2 = s2.length; + + // Create a 2D array dp to store the edit distances + const dp = Array.from({ length: l1 + 1 }, () => Array(l2 + 1).fill(0)); + + // Initialize the base cases for empty strings + for (let i = 0; i <= l1; i++) { + dp[i][0] = i; // Minimum edit distance for transforming s1[0...i] to an empty string + } + for (let i = 0; i <= l2; i++) { + dp[0][i] = i; // Minimum edit distance for transforming an empty string to s2[0...i] + } + + // Calculate the edit distance for the rest of the strings + for (let i = 1; i <= l1; i++) { + for (let j = 1; j <= l2; j++) { + if (s1[i - 1] === s2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1]; // No edit required if characters match + } else { + const del = dp[i][j - 1]; // Deletion (from s2) + const replace = dp[i - 1][j - 1]; // Replacement (of s1[i] with s2[j]) + const insert = dp[i - 1][j]; // Insertion (into s1) + dp[i][j] = Math.min(del, Math.min(replace, insert)) + 1; // Choose the minimum of the three operations + } + } + } + + // Print the edit distance matrix (optional) + for (let i = 0; i <= l1; i++) { + console.log( + dp[i].map((value) => value.toString().padStart(5, " ")).join(" ") + ); + } + + return dp[l1][l2]; // Return the minimum edit distance +} + +// Example usage +const s1 = "abhisek"; +const s2 = "tsunade"; + +const result = findEditDistance(s1, s2); +console.log("Minimum Edit Distance:", result); From 5a60f1e2090484f36ac02e0e38cc5c975e40a6c5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 13 Oct 2023 23:03:35 +0530 Subject: [PATCH 1832/1894] add edit distance in python --- Dynamic Programming/edit_distance_dp.py | 49 +++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Dynamic Programming/edit_distance_dp.py diff --git a/Dynamic Programming/edit_distance_dp.py b/Dynamic Programming/edit_distance_dp.py new file mode 100644 index 00000000..435946a5 --- /dev/null +++ b/Dynamic Programming/edit_distance_dp.py @@ -0,0 +1,49 @@ +''' + Given two strings str1 and str2 and following three operations that can performed on str1. + 1) Insert + 2) Remove + 3) Replace + Find minimum number of operations required to convert ‘str1’ into ‘str2’. + For example if input strings are CAT AND CAR the edit distance is 1. + + Input : s1 : saturday s2 : sunday + Output : 3 +*/ +// Dynamic Programming Solution : TC O(n^2) +''' +# Function to find the minimum edit distance between two strings +def find_edit_distance(s1, s2): + l1, l2 = len(s1), len(s2) + + # Create a 2D list dp to store the edit distances + dp = [[0] * (l2 + 1) for _ in range(l1 + 1)] + + # Initialize the base cases for empty strings + for i in range(l1 + 1): + dp[i][0] = i # Minimum edit distance for transforming s1[0...i] to an empty string + for i in range(l2 + 1): + dp[0][i] = i # Minimum edit distance for transforming an empty string to s2[0...i] + + # Calculate the edit distance for the rest of the strings + for i in range(1, l1 + 1): + for j in range(1, l2 + 1): + if s1[i - 1] == s2[j - 1]: + dp[i][j] = dp[i - 1][j - 1] # No edit required if characters match + else: + del_op = dp[i][j - 1] # Deletion (from s2) + replace_op = dp[i - 1][j - 1] # Replacement (of s1[i] with s2[j]) + insert_op = dp[i - 1][j] # Insertion (into s1) + dp[i][j] = min(del_op, min(replace_op, insert_op)) + 1 # Choose the minimum of the three operations + + # Print the edit distance matrix (optional) + for i in range(l1 + 1): + print(" ".join(map(lambda value: f"{value:5}", dp[i]))) + + return dp[l1][l2] # Return the minimum edit distance + +# Example usage +s1 = "abhisek" +s2 = "tsunade" + +result = find_edit_distance(s1, s2) +print("Minimum Edit Distance:", result) From 23b3b2334da7a7dacb5a947da6c25b08b46598e3 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 16 Oct 2023 22:48:11 +0530 Subject: [PATCH 1833/1894] add climbing stairs in java --- Dynamic Programming/climb_stairs.java | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Dynamic Programming/climb_stairs.java diff --git a/Dynamic Programming/climb_stairs.java b/Dynamic Programming/climb_stairs.java new file mode 100644 index 00000000..aecec826 --- /dev/null +++ b/Dynamic Programming/climb_stairs.java @@ -0,0 +1,47 @@ +// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 +// or 2 steps. In how many distinct ways can the child climb to the top? +public class StairClimbing { + // ClimbStairs: returns the number of ways in which a child can climb stairs + // Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair + // ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) + public static int climbStairs(int n) { + // Base case + if (n < 3) { + return n; + } + int[] cache = new int[n]; + // Initialize initial 2 values + cache[0] = 1; + cache[1] = 2; + for (int i = 2; i < n; i++) { + // Add previous 2 values + cache[i] = cache[i - 1] + cache[i - 2]; + } + return cache[n - 1]; + } + + // Variatiom: A child is climbing up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. + // Implement a method to count how many possible ways the child can jump up the stairs. + // Approach similar to the above problem + public static int climbStairsVariation(int n) { + // Base case + if (n < 3) { + return n; + } + int[] cache = new int[n]; + // Initialize initial 3 values + cache[0] = 1; + cache[1] = 2; + cache[2] = 4; + for (int i = 3; i < n; i++) { + // Add previous 3 values + cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3]; + } + return cache[n - 1]; + } + + public static void main(String[] args) { + System.out.println(climbStairs(5)); + System.out.println(climbStairsVariation(5)); + } +} From 18327302844170ee16d9b8834543ac97c2582936 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 16 Oct 2023 22:49:38 +0530 Subject: [PATCH 1834/1894] add climbing stairs in javascript --- Dynamic Programming/climb_stairs.js | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Dynamic Programming/climb_stairs.js diff --git a/Dynamic Programming/climb_stairs.js b/Dynamic Programming/climb_stairs.js new file mode 100644 index 00000000..38cdc85c --- /dev/null +++ b/Dynamic Programming/climb_stairs.js @@ -0,0 +1,44 @@ +// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 +// or 2 steps. In how many distinct ways can the child climb to the top? + +// ClimbStairs: returns the number of ways in which a child can climb stairs +// Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair +// ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) +function climbStairs(n) { + // Base case + if (n < 3) { + return n; + } + const cache = new Array(n); + // Initialize initial 2 values + cache[0] = 1; + cache[1] = 2; + for (let i = 2; i < n; i++) { + // Add previous 2 values + cache[i] = cache[i - 1] + cache[i - 2]; + } + return cache[n - 1]; +} + +// Variation: A child is climbing up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. +// Implement a method to count how many possible ways the child can jump up the stairs. +// Approach similar to the above problem +function climbStairsVariation(n) { + // Base case + if (n < 3) { + return n; + } + const cache = new Array(n); + // Initialize initial 3 values + cache[0] = 1; + cache[1] = 2; + cache[2] = 4; + for (let i = 3; i < n; i++) { + // Add previous 3 values + cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3]; + } + return cache[n - 1]; +} + +console.log(climbStairs(5)); +console.log(climbStairsVariation(5)); From 74bb25b670d51fa935cc80fdbaeceffcd4a0d76a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 17 Oct 2023 22:58:31 +0530 Subject: [PATCH 1835/1894] add climbing staits in c++ --- Dynamic Programming/climb_stairs.cpp | 49 ++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Dynamic Programming/climb_stairs.cpp diff --git a/Dynamic Programming/climb_stairs.cpp b/Dynamic Programming/climb_stairs.cpp new file mode 100644 index 00000000..ff79f163 --- /dev/null +++ b/Dynamic Programming/climb_stairs.cpp @@ -0,0 +1,49 @@ +// A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 +// or 2 steps. In how many distinct ways can the child climb to the top? +#include +using namespace std; + +// ClimbStairs: returns the number of ways in which a child can climb stairs +// Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair +// ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) +int climbStairs(int n) { + // Base case + if (n < 3) { + return n; + } + int cache[n]; + // Initialize initial 2 values + cache[0] = 1; + cache[1] = 2; + for (int i = 2; i < n; i++) { + // Add previous 2 values + cache[i] = cache[i - 1] + cache[i - 2]; + } + return cache[n - 1]; +} + +// Variation: A child is climbing up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. +// Implement a method to count how many possible ways the child can jump up the stairs. +// Approach similar to the above problem +int climbStairsVariation(int n) { + // Base case + if (n < 3) { + return n; + } + int cache[n]; + // Initialize initial 3 values + cache[0] = 1; + cache[1] = 2; + cache[2] = 4; + for (int i = 3; i < n; i++) { + // Add previous 3 values + cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3]; + } + return cache[n - 1]; +} + +int main() { + cout << climbStairs(5) << endl; + cout << climbStairsVariation(5) << endl; + return 0; +} From fa47cfba174651a6798c8bf3ef84fa64352a03cd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 17 Oct 2023 22:58:43 +0530 Subject: [PATCH 1836/1894] add climbing stairs in python --- Dynamic Programming/climb_stairs.py | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Dynamic Programming/climb_stairs.py diff --git a/Dynamic Programming/climb_stairs.py b/Dynamic Programming/climb_stairs.py new file mode 100644 index 00000000..047fe829 --- /dev/null +++ b/Dynamic Programming/climb_stairs.py @@ -0,0 +1,37 @@ +''' +A child is climbing a stair case. It takes n steps to reach to the top. Each time child can either climb 1 \ +or 2 steps. In how many distinct ways can the child climb to the top? +''' +# ClimbStairs: returns the number of ways in which a child can climb stairs +# Approach: Number of ways to reach kth stair = Number of ways to reach k − 1th stair + Number of ways to reach k − 2th stair +# ClimbStairs(k) = ClimbStairs(k-1) + ClimbStairs(k-2) +def climb_stairs(n): + # Base case + if n < 3: + return n + cache = [0] * n + # Initialize initial 2 values + cache[0], cache[1] = 1, 2 + for i in range(2, n): + # Add previous 2 values + cache[i] = cache[i - 1] + cache[i - 2] + return cache[n - 1] + +# Variation: A child is climbing up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. +# Implement a method to count how many possible ways the child can jump up the stairs. +# Approach similar to the above problem +def climb_stairs_variation(n): + # Base case + if n < 3: + return n + cache = [0] * n + # Initialize initial 3 values + cache[0], cache[1], cache[2] = 1, 2, 4 + for i in range(3, n): + # Add previous 3 values + cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3] + return cache[n - 1] + +if __name__ == "__main__": + print(climb_stairs(5)) + print(climb_stairs_variation(5)) From 1364f1d2ecae21d152b03864c31e12cbb0bca238 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 18 Oct 2023 23:49:51 +0530 Subject: [PATCH 1837/1894] add distance of nearest 0 in go --- Dynamic Programming/distane_of_nearest_0.go | 82 +++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Dynamic Programming/distane_of_nearest_0.go diff --git a/Dynamic Programming/distane_of_nearest_0.go b/Dynamic Programming/distane_of_nearest_0.go new file mode 100644 index 00000000..4d88dd0c --- /dev/null +++ b/Dynamic Programming/distane_of_nearest_0.go @@ -0,0 +1,82 @@ +// Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell in Java + +// Solution +// // This solution uses a breadth-first search (BFS) approach to calculate the distance of the nearest 0 for each cell in the matrix. +// // The idea is to initialize a distances matrix with all values set to the maximum integer value, except for the cells that contain 0s, +// // which are set to 0 and added to a queue. We then perform a BFS on the queue, updating the distances of neighboring cells as we go. +// // Finally, we return the updated distances matrix. + +// Time Complexity: + +// We traverse the entire matrix in the worst case to fill the distances matrix with initial values, which takes O(m * n) time. +// We use Breadth-First Search (BFS) to update the distances matrix, which in the worst case can visit each cell once, taking O(m * n) time. +// Therefore, the total time complexity of this solution is O(m * n). + +// Space Complexity: + +// We store the distances matrix, which requires O(m * n) space. +// We use a queue to implement the BFS algorithm, which can store at most m * n cells in the worst case, taking O(m * n) space. +// Therefore, the total space complexity of this solution is O(m * n). + +package main + +import ( + "container/list" + "math" +) + +var directions = [][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} + +func updateMatrix(mat [][]int) [][]int { + m := len(mat) + n := len(mat[0]) + distances := make([][]int, m) // Initialize a distances matrix + + // Initialize distances to math.MaxInt32 except for cells with 0 + for i := range distances { + distances[i] = make([]int, n) + for j := range distances[i] { + distances[i][j] = math.MaxInt32 + if mat[i][j] == 0 { + distances[i][j] = 0 + } + } + } + + queue := list.New() // Initialize a queue for BFS + + // Perform BFS + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 0 { + queue.PushBack([2]int{i, j}) // Add the cell to the queue + } + } + } + + for queue.Len() > 0 { + element := queue.Front() + queue.Remove(element) + cell := element.Value.([2]int) + i, j := cell[0], cell[1] + + for _, direction := range directions { + x, y := i+direction[0], j+direction[1] + + // Check if cell is out of bounds + if x < 0 || x >= m || y < 0 || y >= n { + continue + } + + // Check if distance is already smaller + if distances[x][y] <= distances[i][j]+1 { + continue + } + + distances[x][y] = distances[i][j] + 1 // Update the distance + queue.PushBack([2]int{x, y}) // Add the cell to the queue + } + } + + return distances // Return the updated distances matrix +} From 0ecb5e09ba4befcf8b4ea765449154ff9818ad33 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 18 Oct 2023 23:50:46 +0530 Subject: [PATCH 1838/1894] rename file --- .../{distance_of_nearest_zero.js => distane_of_nearest_0.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Dynamic Programming/{distance_of_nearest_zero.js => distane_of_nearest_0.js} (100%) diff --git a/Dynamic Programming/distance_of_nearest_zero.js b/Dynamic Programming/distane_of_nearest_0.js similarity index 100% rename from Dynamic Programming/distance_of_nearest_zero.js rename to Dynamic Programming/distane_of_nearest_0.js From c72353c1c76cfcf95b0080ecaea58ada0613e168 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 19 Oct 2023 23:01:26 +0530 Subject: [PATCH 1839/1894] add queue using stack in go --- Stacks/queue using stack.go | 60 +++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Stacks/queue using stack.go diff --git a/Stacks/queue using stack.go b/Stacks/queue using stack.go new file mode 100644 index 00000000..d279209f --- /dev/null +++ b/Stacks/queue using stack.go @@ -0,0 +1,60 @@ +// Queue using stack +package main + +import "fmt" + +// Queue represents a queue data structure using two stacks. +type Queue struct { + enqueueStack []int // Stack for enqueue operations + dequeueStack []int // Stack for dequeue operations +} + +// Enqueue adds an element to the back of the queue. +func (q *Queue) Enqueue(value int) { + q.enqueueStack = append(q.enqueueStack, value) +} + +// Dequeue removes and returns the front element of the queue. +func (q *Queue) Dequeue() int { + // If the dequeue stack is empty, transfer elements from the enqueue stack + if len(q.dequeueStack) == 0 { + for len(q.enqueueStack) > 0 { + // Pop an element from the enqueue stack and push it onto the dequeue stack + element := q.enqueueStack[len(q.enqueueStack)-1] + q.enqueueStack = q.enqueueStack[:len(q.enqueueStack)-1] + q.dequeueStack = append(q.dequeueStack, element) + } + } + + // If the dequeue stack is still empty, the queue is empty + if len(q.dequeueStack) == 0 { + panic("Queue is empty") + } + + // Pop and return the front element from the dequeue stack + element := q.dequeueStack[len(q.dequeueStack)-1] + q.dequeueStack = q.dequeueStack[:len(q.dequeueStack)-1] + return element +} + +func main() { + queue := Queue{} + + // Enqueue elements + queue.Enqueue(1) + queue.Enqueue(2) + queue.Enqueue(3) + + // Dequeue elements + fmt.Println(queue.Dequeue()) // Output: 1 + fmt.Println(queue.Dequeue()) // Output: 2 + + // Enqueue more elements + queue.Enqueue(4) + queue.Enqueue(5) + + // Dequeue the remaining elements + fmt.Println(queue.Dequeue()) // Output: 3 + fmt.Println(queue.Dequeue()) // Output: 4 + fmt.Println(queue.Dequeue()) // Output: 5 +} From 2708c8c0f2425bea6e8063f9060ba9fd91ae3549 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 20 Oct 2023 23:02:06 +0530 Subject: [PATCH 1840/1894] add queue using stack in js --- Stacks/queue using stack.js | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Stacks/queue using stack.js diff --git a/Stacks/queue using stack.js b/Stacks/queue using stack.js new file mode 100644 index 00000000..1473391a --- /dev/null +++ b/Stacks/queue using stack.js @@ -0,0 +1,45 @@ +// Queue using stack +class Queue { + constructor() { + this.enqueueStack = []; // Stack for enqueue operations + this.dequeueStack = []; // Stack for dequeue operations + } + + enqueue(value) { + // Enqueue: Add an element to the back of the queue. + this.enqueueStack.push(value); + } + + dequeue() { + // Dequeue: Remove and return the front element of the queue. + // If the dequeue stack is empty, transfer elements from the enqueue stack + if (this.dequeueStack.length === 0) { + while (this.enqueueStack.length > 0) { + // Pop an element from the enqueue stack and push it onto the dequeue stack + const element = this.enqueueStack.pop(); + this.dequeueStack.push(element); + } + } + + // If the dequeue stack is still empty, the queue is empty + if (this.dequeueStack.length === 0) { + throw new Error("Queue is empty"); + } + + // Pop and return the front element from the dequeue stack + return this.dequeueStack.pop(); + } +} + +// Example usage +const queue = new Queue(); +queue.enqueue(1); +queue.enqueue(2); +queue.enqueue(3); +console.log(queue.dequeue()); // Output: 1 +console.log(queue.dequeue()); // Output: 2 +queue.enqueue(4); +queue.enqueue(5); +console.log(queue.dequeue()); // Output: 3 +console.log(queue.dequeue()); // Output: 4 +console.log(queue.dequeue()); // Output: 5 From c7e323cf81b8e7a17f8ec18e0a54f9f0e80e0773 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 20 Oct 2023 23:02:29 +0530 Subject: [PATCH 1841/1894] add queue using stack in python --- Stacks/queue using stack.py | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Stacks/queue using stack.py diff --git a/Stacks/queue using stack.py b/Stacks/queue using stack.py new file mode 100644 index 00000000..802cacfd --- /dev/null +++ b/Stacks/queue using stack.py @@ -0,0 +1,38 @@ +# Queue using stack +class Queue: + def __init__(self): + self.enqueue_stack = [] # Stack for enqueue operations + self.dequeue_stack = [] # Stack for dequeue operations + + def enqueue(self, value): + """Enqueue: Add an element to the back of the queue.""" + self.enqueue_stack.append(value) + + def dequeue(self): + """Dequeue: Remove and return the front element of the queue.""" + # If the dequeue stack is empty, transfer elements from the enqueue stack + if not self.dequeue_stack: + while self.enqueue_stack: + # Pop an element from the enqueue stack and push it onto the dequeue stack + element = self.enqueue_stack.pop() + self.dequeue_stack.append(element) + + # If the dequeue stack is still empty, the queue is empty + if not self.dequeue_stack: + raise IndexError("Queue is empty") + + # Pop and return the front element from the dequeue stack + return self.dequeue_stack.pop() + +# Example usage +queue = Queue() +queue.enqueue(1) +queue.enqueue(2) +queue.enqueue(3) +print(queue.dequeue()) # Output: 1 +print(queue.dequeue()) # Output: 2 +queue.enqueue(4) +queue.enqueue(5) +print(queue.dequeue()) # Output: 3 +print(queue.dequeue()) # Output: 4 +print(queue.dequeue()) # Output: 5 From c93b20a668e5d6f8652f53eb5302071f0f3d6fbb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 21 Oct 2023 22:58:14 +0530 Subject: [PATCH 1842/1894] add stack using queue --- Stacks/stack_using_queue.go | 84 +++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Stacks/stack_using_queue.go diff --git a/Stacks/stack_using_queue.go b/Stacks/stack_using_queue.go new file mode 100644 index 00000000..d5f21dfe --- /dev/null +++ b/Stacks/stack_using_queue.go @@ -0,0 +1,84 @@ +// stack using queue +package main + +import ( + "container/list" + "fmt" +) + +// Stack represents a stack data structure using two queues. +type Stack struct { + queue1 *list.List // Primary queue + queue2 *list.List // Temporary queue for operations +} + +// Constructor creates a new stack. +func NewStack() *Stack { + return &Stack{ + queue1: list.New(), + queue2: list.New(), + } +} + +// Push adds an element to the top of the stack. +func (s *Stack) Push(value int) { + // Add the element to the primary queue + s.queue1.PushBack(value) +} + +// Pop removes and returns the top element of the stack. +func (s *Stack) Pop() int { + // Move elements from the primary queue to the temporary queue except the last one + for s.queue1.Len() > 1 { + element := s.queue1.Front() + s.queue1.Remove(element) + s.queue2.PushBack(element.Value) + } + + // Get the last element from the primary queue (top of the stack) + topElement := s.queue1.Front().Value + + // Swap the primary and temporary queues + s.queue1, s.queue2 = s.queue2, s.queue1 + + return topElement.(int) +} + +// Top returns the top element of the stack without removing it. +func (s *Stack) Top() int { + // Similar to Pop, but don't remove the last element + topElement := s.Pop() + + // Add the top element back to the stack + s.Push(topElement) + + return topElement +} + +// IsEmpty checks if the stack is empty. +func (s *Stack) IsEmpty() bool { + return s.queue1.Len() == 0 +} + +func main() { + stack := NewStack() + + // Push elements onto the stack + stack.Push(1) + stack.Push(2) + stack.Push(3) + + // Pop elements from the stack + fmt.Println(stack.Pop()) // Output: 3 + fmt.Println(stack.Pop()) // Output: 2 + + // Push more elements + stack.Push(4) + stack.Push(5) + + // Peek at the top element + fmt.Println(stack.Top()) // Output: 5 + + // Check if the stack is empty + fmt.Println(stack.IsEmpty()) // Output: false +} From 45ff67c2671b63302fe15b9bbec677c118166f40 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 22 Oct 2023 22:58:17 +0530 Subject: [PATCH 1843/1894] add stack using queue in java --- Stacks/stack_using_queue.java | 79 +++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Stacks/stack_using_queue.java diff --git a/Stacks/stack_using_queue.java b/Stacks/stack_using_queue.java new file mode 100644 index 00000000..4c0ff111 --- /dev/null +++ b/Stacks/stack_using_queue.java @@ -0,0 +1,79 @@ +// stack using queue +import java.util.LinkedList; +import java.util.Queue; + +public class StackUsingQueues { + private Queue primaryQueue; + private Queue tempQueue; + + public StackUsingQueues() { + primaryQueue = new LinkedList<>(); + tempQueue = new LinkedList<>(); + } + + public void push(int value) { + // Add the element to the primary queue + primaryQueue.offer(value); + } + + public int pop() { + if (isEmpty()) { + throw new IllegalStateException("Stack is empty."); + } + + // Move elements from the primary queue to the temporary queue except the last one + while (primaryQueue.size() > 1) { + tempQueue.offer(primaryQueue.poll()); + } + + // Get the last element from the primary queue (top of the stack) + int topElement = primaryQueue.poll(); + + // Swap the primary and temporary queues + Queue swap = primaryQueue; + primaryQueue = tempQueue; + tempQueue = swap; + + return topElement; + } + + public int top() { + if (isEmpty()) { + throw new IllegalStateException("Stack is empty."); + } + + int topElement = pop(); + + // Add the top element back to the stack + push(topElement); + + return topElement; + } + + public boolean isEmpty() { + return primaryQueue.isEmpty(); + } + + public static void main(String[] args) { + StackUsingQueues stack = new StackUsingQueues(); + + // Push elements onto the stack + stack.push(1); + stack.push(2); + stack.push(3); + + // Pop elements from the stack + System.out.println(stack.pop()); // Output: 3 + System.out.println(stack.pop()); // Output: 2 + + // Push more elements + stack.push(4); + stack.push(5); + + // Peek at the top element + System.out.println(stack.top()); // Output: 5 + + // Check if the stack is empty + System.out.println(stack.isEmpty()); // Output: false + } +} From 804151af5113b816ab75970ace15e7839a263201 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 23 Oct 2023 22:43:14 +0530 Subject: [PATCH 1844/1894] add stack using queue --- Stacks/stack_using_queue.cpp | 87 ++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Stacks/stack_using_queue.cpp diff --git a/Stacks/stack_using_queue.cpp b/Stacks/stack_using_queue.cpp new file mode 100644 index 00000000..fc1cfc89 --- /dev/null +++ b/Stacks/stack_using_queue.cpp @@ -0,0 +1,87 @@ +// stack using queue +#include +#include + +class StackUsingQueues { +public: + StackUsingQueues() {} + + // Push an element onto the stack. + void push(int x) { + // Add the element to the primary queue. + primaryQueue.push(x); + } + + // Remove and return the top element of the stack. + int pop() { + if (isEmpty()) { + throw std::runtime_error("Stack is empty"); + } + + // Move elements from the primary queue to the temporary queue except the last one. + while (primaryQueue.size() > 1) { + tempQueue.push(primaryQueue.front()); + primaryQueue.pop(); + } + + // Get the last element from the primary queue (top of the stack). + int topElement = primaryQueue.front(); + primaryQueue.pop(); + + // Swap the primary and temporary queues. + primaryQueue = tempQueue; + while (!tempQueue.empty()) { + tempQueue.pop(); + } + + return topElement; + } + + // Return the top element of the stack without removing it. + int top() { + if (isEmpty()) { + throw std::runtime_error("Stack is empty"); + } + + int topElement = pop(); + + // Add the top element back to the stack. + push(topElement); + + return topElement; + } + + // Check if the stack is empty. + bool isEmpty() { + return primaryQueue.empty(); + } + +private: + std::queue primaryQueue; + std::queue tempQueue; +}; + +int main() { + StackUsingQueues stack; + + // Push elements onto the stack. + stack.push(1); + stack.push(2); + stack.push(3); + + // Pop elements from the stack. + std::cout << stack.pop() << std::endl; // Output: 3 + std::cout << stack.pop() << std::endl; // Output: 2 + + // Push more elements. + stack.push(4); + stack.push(5); + + // Peek at the top element. + std::cout << stack.top() << std::endl; // Output: 5 + + // Check if the stack is empty. + std::cout << stack.isEmpty() << std::endl; // Output: 0 (false) + + return 0; +} From 81cb75429ef50d4056fd412dfb91a840389280ec Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 24 Oct 2023 19:22:30 +0530 Subject: [PATCH 1845/1894] add stack using queues --- Stacks/stack_using_queue.js | 73 +++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Stacks/stack_using_queue.js diff --git a/Stacks/stack_using_queue.js b/Stacks/stack_using_queue.js new file mode 100644 index 00000000..cfcf0f64 --- /dev/null +++ b/Stacks/stack_using_queue.js @@ -0,0 +1,73 @@ +// Stack using queues +class StackUsingQueues { + constructor() { + this.primaryQueue = []; + this.tempQueue = []; + } + + // Push an element onto the stack. + push(x) { + // Add the element to the primary queue. + this.primaryQueue.push(x); + } + + // Remove and return the top element of the stack. + pop() { + if (this.isEmpty()) { + throw new Error("Stack is empty"); + } + + // Move elements from the primary queue to the temporary queue except the last one. + while (this.primaryQueue.length > 1) { + this.tempQueue.push(this.primaryQueue.shift()); + } + + // Get the last element from the primary queue (top of the stack). + const topElement = this.primaryQueue.shift(); + + // Swap the primary and temporary queues. + [this.primaryQueue, this.tempQueue] = [this.tempQueue, this.primaryQueue]; + + return topElement; + } + + // Return the top element of the stack without removing it. + top() { + if (this.isEmpty()) { + throw new Error("Stack is empty"); + } + + const topElement = this.pop(); + + // Add the top element back to the stack. + this.push(topElement); + + return topElement; + } + + // Check if the stack is empty. + isEmpty() { + return this.primaryQueue.length === 0; + } +} + +const stack = new StackUsingQueues(); + +// Push elements onto the stack. +stack.push(1); +stack.push(2); +stack.push(3); + +// Pop elements from the stack. +console.log(stack.pop()); // Output: 3 +console.log(stack.pop()); // Output: 2 + +// Push more elements. +stack.push(4); +stack.push(5); + +// Peek at the top element. +console.log(stack.top()); // Output: 5 + +// Check if the stack is empty. +console.log(stack.isEmpty()); // Output: false From df8fa9ceb0ffcb1cd9a408f7cea4e2770eb03248 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 24 Oct 2023 19:23:09 +0530 Subject: [PATCH 1846/1894] modify comment --- Stacks/stack_using_queue.cpp | 2 +- Stacks/stack_using_queue.go | 2 +- Stacks/stack_using_queue.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Stacks/stack_using_queue.cpp b/Stacks/stack_using_queue.cpp index fc1cfc89..f58ed22b 100644 --- a/Stacks/stack_using_queue.cpp +++ b/Stacks/stack_using_queue.cpp @@ -1,4 +1,4 @@ -// stack using queue +// stack using queues #include #include diff --git a/Stacks/stack_using_queue.go b/Stacks/stack_using_queue.go index d5f21dfe..13676064 100644 --- a/Stacks/stack_using_queue.go +++ b/Stacks/stack_using_queue.go @@ -1,4 +1,4 @@ -// stack using queue +// stack using queues package main import ( diff --git a/Stacks/stack_using_queue.java b/Stacks/stack_using_queue.java index 4c0ff111..20acafad 100644 --- a/Stacks/stack_using_queue.java +++ b/Stacks/stack_using_queue.java @@ -1,4 +1,4 @@ -// stack using queue +// stack using queues import java.util.LinkedList; import java.util.Queue; From 90ec3b7085d3a704b7c82f1f2812d0bf259d54bb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 25 Oct 2023 11:54:33 +0530 Subject: [PATCH 1847/1894] add hashtable implementation in java --- Hash Table/HashTable.java | 131 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 Hash Table/HashTable.java diff --git a/Hash Table/HashTable.java b/Hash Table/HashTable.java new file mode 100644 index 00000000..fac65528 --- /dev/null +++ b/Hash Table/HashTable.java @@ -0,0 +1,131 @@ +/* + + 1. **Class Structure:** + - The `HashTable` class represents a hash table for storing key-value pairs. + - It uses a nested `Node` class to encapsulate key-value pairs and handle collisions using a linked list. + - The hash table is initialized with a default size of 7, but this size can be modified as needed. + + 2. **Node Class:** + - The `Node` class is a private nested class within the `HashTable`. + - Each `Node` contains a key, an associated integer value, and a reference to the next `Node` in case of collisions. + + 3. **Constructor:** + - The `HashTable` constructor initializes the data map, an array of `Node` objects, with the default size. + + 4. **`printTable` Method:** + - `printTable` is used to display the contents of the hash table. + - It iterates through the data map and prints the key-value pairs for each index. + - If there are collisions, it prints all elements using the linked list structure. + + 5. **`hash` Method:** + - `hash` is a helper method to map a given key to an index in the data map. + - It computes a hash code for the key by summing the ASCII values of its characters and applying a modulo operation based on the data map size. + + 6. **`set` Method:** + - The `set` method adds a new key-value pair to the hash table. + - It computes the index for the given key using the `hash` method and creates a new `Node` for the key-value pair. + - If there's no collision at the computed index, it directly assigns the new `Node`. If a collision occurs, it appends the new `Node` to the linked list. + + 7. **`get` Method:** + - The `get` method retrieves the value associated with a given key. + - It computes the index for the key using the `hash` method and searches for the key in the linked list at that index. + - If found, it returns the associated value; otherwise, it returns 0. + + 8. **`keys` Method:** + - The `keys` method returns a list of all keys stored in the hash table. + - It iterates through the data map, collecting all keys, even in the presence of collisions. + + In summary, the `HashTable` class provides a basic implementation of a hash table for key-value storage. + It handles collisions through linked lists, allowing multiple key-value pairs to exist at the same index. + The class offers methods to set key-value pairs, retrieve values by keys, list all keys, and print the + contents of the hash table. + * +*/ +import java.util.ArrayList; + +public class HashTable { + private int size = 7; + private Node[] dataMap; + + // Nested Node class to represent key-value pairs + class Node { + String key; + int value; + Node next; + + // Constructor to create a new Node + Node(String key, int value) { + this.key = key; + this.value = value; + } + } + + // Constructor to create the HashTable with an initial size + public HashTable() { + dataMap = new Node[size]; + } + + // Method to print the contents of the HashTable + public void printTable() { + for (int i = 0; i < dataMap.length; i++) { + System.out.println(i + ":"); + Node temp = dataMap[i]; + while (temp != null) { + System.out.println("{" + temp.key + "=" + temp.value + "}"); + temp = temp.next; + } + } + } + + // A hash function to map a key to an index in the dataMap array + public int hash(String key) { + int hash = 0; + char[] keyChars = key.toCharArray(); + for (int i = 0; i < keyChars.length; i++) { + int asciiValue = keyChars[i]; + hash = (hash + asciiValue * 23) % dataMap.length; + } + return hash; + } + + // Add a key-value pair to the hash table + public void set(String key, int value) { + int index = hash(key); + Node newNode = new Node(key, value); + if (dataMap[index] == null) { + dataMap[index] = newNode; + } else { + Node temp = dataMap[index]; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + } + } + + // Get the value associated with a key + public int get(String key) { + int index = hash(key); + Node temp = dataMap[index]; + while (temp != null) { + if (temp.key.equals(key)) { // Use .equals() to compare strings + return temp.value; + } + temp = temp.next; + } + return 0; // Return 0 if the key is not found + } + + // Get a list of all keys in the hash table + public ArrayList keys() { + ArrayList allKeys = new ArrayList<>(); + for (int i = 0; i < dataMap.length; i++) { + Node temp = dataMap[i]; + while (temp != null) { + allKeys.add(temp.key); + temp = temp.next; + } + } + return allKeys; + } +} From 1dd3a4d4ce56f20a2b0e035dc7257017f05dd35a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 26 Oct 2023 14:28:01 +0530 Subject: [PATCH 1848/1894] add adjacency matrix in java --- Graphs/adjacency_matrix.java | 102 +++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 Graphs/adjacency_matrix.java diff --git a/Graphs/adjacency_matrix.java b/Graphs/adjacency_matrix.java new file mode 100644 index 00000000..57f6c141 --- /dev/null +++ b/Graphs/adjacency_matrix.java @@ -0,0 +1,102 @@ +/* + This code snippet is a Java implementation of a graph using an adjacency matrix to represent the connections between nodes. Here's an explanation of the code: + + 1. `GraphNode` Class: + - `GraphNode` represents a node or vertex in the graph. + - It has two attributes: `name` to store the name of the node and `index` to store the index of the node. + - The constructor initializes these attributes. + + 2. `AdjacencyMatrix` Class: + - `AdjacencyMatrix` represents the graph using an adjacency matrix. + - It has the following attributes: + - `nodeList`: An `ArrayList` that stores all the nodes in the graph. + - `adjacencyMatrix`: A 2D array that represents the connections between nodes. + - The constructor takes an `ArrayList` of `GraphNode` objects and initializes the `nodeList` and `adjacencyMatrix` based on the size of the node list. + + 3. `addUndirectedEdge` Method: + - This method is used to add an undirected edge between two nodes. + - It takes two indices `i` and `j` to represent the nodes between which the edge is added. + - It sets the corresponding values in the adjacency matrix to 1, indicating an edge exists between nodes `i` and `j`. Since it's an undirected graph, it sets both `adjacencyMatrix[i][j]` and `adjacencyMatrix[j][i]` to 1. + + 4. `printGraph` Method: + - This method generates a human-readable string representation of the graph, including the adjacency matrix. + - It first prints the node names as column headers and then iterates through the adjacency matrix to display the connections between nodes. + + 5. `Main` Class: + - In the `Main` class, a list of `GraphNode` objects (`nodeList`) is created, each representing a node with a name and an index. + - An `AdjacencyMatrix` object (`am`) is created, passing the `nodeList` to its constructor. + - Undirected edges are added between nodes using the `addUndirectedEdge` method. + - Finally, the graph is printed using the `printGraph` method. + + The example in the `main` method demonstrates the creation of a simple graph with five nodes and several edges. When you run this program, it will print a representation of the graph showing the connections between the nodes based on the adjacency matrix. + + Output: + A B C D E + A: 0 1 1 1 0 + B: 1 0 0 0 1 + C: 1 0 0 1 0 + D: 1 0 1 0 1 + E: 0 1 0 1 0 + +*/ +import java.util.ArrayList; + +public class GraphNode { + public String name; + public int index; + GraphNode(String name, int index) { + this.name = name; + this.index = index; + } +} + +public class AdjacencyMatrix { + ArrayList nodeList = new ArrayList(); + int[][] adjacencyMatrix; + public AdjacencyMatrix(ArrayList nodeList) { + this.nodeList = nodeList; + adjacencyMatrix = new int[nodeList.size()][nodeList.size()]; + } + + public void addUndirectedEdge(int i, int j) { + adjacencyMatrix[i][j] = 1; + adjacencyMatrix[j][i] = 1; + } + public String printGraph() { + StringBuilder s = new StringBuilder(); + s.append(" "); + for (int i = 0; i < nodeList.size(); i++) { + s.append(nodeList.get(i).name + " "); + } + s.append("\n"); + for (int i = 0; i < nodeList.size(); i++) { + s.append(nodeList.get(i).name + ": "); + for (int j : adjacencyMatrix[i]) { + s.append((j) + " "); + } + s.append("\n"); + } + return s.toString(); + } + +} + + +public class Main { + public static void main(String[] args) { + ArrayList nodeList = new ArrayList(); + nodeList.add(new GraphNode("A", 0)); + nodeList.add(new GraphNode("B", 1)); + nodeList.add(new GraphNode("C", 2)); + nodeList.add(new GraphNode("D", 3)); + nodeList.add(new GraphNode("E", 4)); + AdjacencyMatrix am = new AdjacencyMatrix(nodeList); + am.addUndirectedEdge(0, 1); // A-B + am.addUndirectedEdge(0, 2); // A-C + am.addUndirectedEdge(0, 3); // A-D + am.addUndirectedEdge(1, 4); // B-E + am.addUndirectedEdge(2, 3); // C-D + am.addUndirectedEdge(3, 4); // D-E + System.out.println(am.printGraph()); + } +} \ No newline at end of file From 33f4f5406720f24259ee44f115a5a2f48b4e8ccd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 26 Oct 2023 14:30:34 +0530 Subject: [PATCH 1849/1894] add comments --- Graphs/adjacency_matrix.java | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/Graphs/adjacency_matrix.java b/Graphs/adjacency_matrix.java index 57f6c141..12815a94 100644 --- a/Graphs/adjacency_matrix.java +++ b/Graphs/adjacency_matrix.java @@ -41,34 +41,47 @@ */ import java.util.ArrayList; +// Class to represent a graph node public class GraphNode { public String name; public int index; + + // Constructor to initialize name and index GraphNode(String name, int index) { this.name = name; this.index = index; } } +// Class to represent a graph using an adjacency matrix public class AdjacencyMatrix { ArrayList nodeList = new ArrayList(); int[][] adjacencyMatrix; + + // Constructor to initialize nodeList and adjacencyMatrix public AdjacencyMatrix(ArrayList nodeList) { this.nodeList = nodeList; adjacencyMatrix = new int[nodeList.size()][nodeList.size()]; } - + + // Method to add an undirected edge between two nodes public void addUndirectedEdge(int i, int j) { adjacencyMatrix[i][j] = 1; adjacencyMatrix[j][i] = 1; } + + // Method to print a human-readable representation of the graph public String printGraph() { StringBuilder s = new StringBuilder(); + + // Print column headers (node names) s.append(" "); for (int i = 0; i < nodeList.size(); i++) { s.append(nodeList.get(i).name + " "); } s.append("\n"); + + // Print node names and adjacency matrix for (int i = 0; i < nodeList.size(); i++) { s.append(nodeList.get(i).name + ": "); for (int j : adjacencyMatrix[i]) { @@ -78,10 +91,9 @@ public String printGraph() { } return s.toString(); } - } - +// Main class to demonstrate the graph creation public class Main { public static void main(String[] args) { ArrayList nodeList = new ArrayList(); @@ -91,12 +103,16 @@ public static void main(String[] args) { nodeList.add(new GraphNode("D", 3)); nodeList.add(new GraphNode("E", 4)); AdjacencyMatrix am = new AdjacencyMatrix(nodeList); - am.addUndirectedEdge(0, 1); // A-B - am.addUndirectedEdge(0, 2); // A-C - am.addUndirectedEdge(0, 3); // A-D - am.addUndirectedEdge(1, 4); // B-E - am.addUndirectedEdge(2, 3); // C-D - am.addUndirectedEdge(3, 4); // D-E + + // Adding undirected edges + am.addUndirectedEdge(0, 1); + am.addUndirectedEdge(0, 2); + am.addUndirectedEdge(0, 3); + am.addUndirectedEdge(1, 4); + am.addUndirectedEdge(2, 3); + am.addUndirectedEdge(3, 4); + + // Printing the graph System.out.println(am.printGraph()); } -} \ No newline at end of file +} From 5ef257f7e57a5f3db2169a54c3b6cb8cf21664bd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 26 Oct 2023 16:53:55 +0530 Subject: [PATCH 1850/1894] add adjacencylist representation of graph in java --- Graphs/adjacency_list.java | 101 +++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Graphs/adjacency_list.java diff --git a/Graphs/adjacency_list.java b/Graphs/adjacency_list.java new file mode 100644 index 00000000..312e1a22 --- /dev/null +++ b/Graphs/adjacency_list.java @@ -0,0 +1,101 @@ +/* + This code is an implementation of a graph data structure using an adjacency list representation in Java. Let's break down the code and explain it step by step: + + 1. `GraphNode` Class: + - This class represents a node in the graph. + - It has three attributes: + - `name`: A string that represents the name or label of the node. + - `index`: An integer that serves as a unique identifier/index for the node. + - `neighbors`: An ArrayList of `GraphNode` objects that stores the neighboring nodes of the current node. + + 2. `AdjacencyList` Class: + - This class represents the graph using an adjacency list. + - It has the following attributes: + - `nodeList`: An ArrayList of `GraphNode` objects that stores all the nodes in the graph. + - The constructor takes an ArrayList of `GraphNode` objects and initializes the `nodeList` attribute with it. + - The class provides the following methods: + - `addUndirectedEdge(int i, int j)`: This method takes two indices (`i` and `j`) representing two nodes in the graph and + adds an undirected edge between them. It does so by retrieving the corresponding `GraphNode` objects from the `nodeList` + and adding each node to the `neighbors` list of the other. + - `printGraph()`: This method returns a human-readable representation of the graph. It iterates through the `nodeList`, + prints the name of each node, and lists its neighboring nodes. + + 3. `main` Class: + - This is the main class to demonstrate the graph creation and printing. + - Inside the `main` method: + - An ArrayList of `GraphNode` objects (`nodeList`) is created, and five nodes are added to it, each with a name and index. + - An `AdjacencyList` object (`al`) is created, passing the `nodeList` to its constructor. + - Several undirected edges are added using the `addUndirectedEdge` method to establish connections between nodes. + - Finally, the `printGraph` method is called on the `al` object to print the graph's structure. + + The code demonstrates how to create a graph using an adjacency list and provides a readable representation of the graph, including its nodes and edges. +*/ + + +import java.util.ArrayList; + +public class GraphNode { + public String name; + public int index; + // An ArrayList to store neighboring nodes + public ArrayList neighbors = new ArrayList(); + + public GraphNode(String name, int index) { + this.name = name; + this.index = index; + } +} + +public class AdjacencyList { + // An ArrayList to store all nodes in the graph + ArrayList nodeList = new ArrayList(); + + public AdjacencyList(ArrayList nodeList) { + this.nodeList = nodeList; + } + + // Method to add an undirected edge between two nodes + public void addUndirectedEdge(int i, int j) { + GraphNode first = nodeList.get(i); + GraphNode second = nodeList.get(j); + first.neighbors.add(second); + second.neighbors.add(first); + } + + // Method to print a human-readable representation of the graph + public String printGraph() { + StringBuilder s = new StringBuilder(); + for (int i = 0; i < nodeList.size(); i++) { + s.append(nodeList.get(i).name + ": "); + for (int j = 0; j < nodeList.get(i).neighbors.size(); j++) { + if (j == nodeList.get(i).neighbors.size() - 1) { + s.append(nodeList.get(i).neighbors.get(j).name); + } else { + s.append(nodeList.get(i).neighbors.get(j).name + " --> "); + } + } + s.append("\n"); + } + return s.toString(); + } +} + +public class Main { + public static void main(String[] args) { + ArrayList nodeList = new ArrayList(); + nodeList.add(new GraphNode("A", 0)); + nodeList.add(new GraphNode("B", 1)); + nodeList add(new GraphNode("C", 2)); + nodeList.add(new GraphNode("D", 3)); + nodeList.add(new GraphNode("E", 4)); + + AdjacencyList al = new AdjacencyList(nodeList); + al.addUndirectedEdge(0, 1); + al.addUndirectedEdge(0, 2); + al.addUndirectedEdge(0, 3); + al.addUndirectedEdge(1, 4); + al.addUndirectedEdge(2, 3); + al.addUndirectedEdge(3, 4); + System.out.println(al.printGraph()); + } +} From 03fdadbb54f5bdaa45e4920371804c7a191b8441 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 27 Oct 2023 23:02:48 +0530 Subject: [PATCH 1851/1894] add tic tac toe --- Misc/tictactoe.java | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Misc/tictactoe.java diff --git a/Misc/tictactoe.java b/Misc/tictactoe.java new file mode 100644 index 00000000..d28356d2 --- /dev/null +++ b/Misc/tictactoe.java @@ -0,0 +1,80 @@ +public class TicTacToe { + public static final int X = 1, O = -1; + public static final int EMPTY = 0; + private int board[][] = new int[3][3]; + private int player; + + public TicTacToe() { + clearBoard(); + } + public void clearBoard() { + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) + board[i][j] = EMPTY; + player = X; + } + + public void putMark(int i, int j) throws IllegalArgumentException { + if ((i < 0) || (i > 2) || (j < 0) || (j > 2)) + throw new IllegalArgumentException("Invalid board position"); + if (board[i][j] != EMPTY) + throw new IllegalArgumentException("Board Position occupied"); + board[i][j] = player; + player = -player; // switch players + } + + public boolean isWin(int mark) { + return ((board[0][0] + board[0][1] + board[0][2] == mark * 3) + || (board[1][0] + board[1][1] + board[1][2] == mark * 3) + || (board[2][0] + board[2][1] + board[2][2] == mark * 3) + || (board[0][0] + board[1][0] + board[2][0] == mark * 3) + || (board[0][1] + board[1][1] + board[2][1] == mark * 3) + || (board[0][2] + board[1][2] + board[2][2] == mark * 3) + || (board[0][0] + board[1][1] + board[2][2] == mark * 3) + || (board[2][0] + board[1][1] + board[0][2] == mark * 3) + ); + } + public int winner() { + if(isWin(X)) + return (X); + else if (isWin(O)) + return (O); + else + return (0); + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + switch (board[i][j]) { + case X: sb.append("X"); break; + case O: sb.append("O"); break; + case EMPTY: sb.append(" "); break; + } + if (j < 2) sb.append("|"); + } + if(i < 2) sb.append("\n-----\n"); + } + return sb.toString(); + } + + public static void main(String[] args) { + TicTacToe game = new TicTacToe(); + game.putMark(0, 0); game.putMark(0, 2); + game.putMark(2, 2); game.putMark(1, 2); + game.putMark(2, 0); game.putMark(1, 1); + game.putMark(1, 0); + + + System.out.println(game); + int winningPlayer = game.winner(); + String[] outcome = {"O wins", "Tie", "X wins"}; + System.out.println(outcome[1 + winningPlayer]); + } + + +} + { + +} From 914049b453f2e49162eeb6f68371339ce69cfe5c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 27 Oct 2023 23:03:10 +0530 Subject: [PATCH 1852/1894] add comments --- Misc/tictactoe.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Misc/tictactoe.java b/Misc/tictactoe.java index d28356d2..3d2bd98c 100644 --- a/Misc/tictactoe.java +++ b/Misc/tictactoe.java @@ -1,3 +1,41 @@ +/* + This Java code defines a simple command-line Tic-Tac-Toe game that allows two players (X and O) to take turns making moves on a 3x3 game board. Here's an explanation of the code: + +1. Constants: + - `X` and `O` are integer constants representing the two players, with `X` assigned the value `1` and `O` assigned the value `-1`. + - `EMPTY` is an integer constant representing an empty cell on the game board, with a value of `0`. + +2. Game Board: + - The game board is represented by a 3x3 integer array called `board`. + - The `player` variable indicates which player's turn it is. It is initially set to `X`. + +3. Constructor: + - The `TicTacToe` class has a constructor that initializes a new game by clearing the board and setting the `player` to `X`. + +4. `clearBoard` Method: + - The `clearBoard` method initializes the game board by setting all cells to `EMPTY` and resets the `player` to `X`. + +5. `putMark` Method: + - The `putMark` method allows a player to make a move at a specified position (i, j). + - It checks for valid coordinates and an empty cell. If the move is valid, the player's mark is placed, and the turn is switched to the other player. + - If the move is invalid, an `IllegalArgumentException` is thrown. + +6. `isWin` Method: + - The `isWin` method checks if a player has won the game. It returns `true` if any of the winning conditions (e.g., a row, column, or diagonal with all marks of the same player) are met. Otherwise, it returns `false`. + +7. `winner` Method: + - The `winner` method determines the winner of the game. It checks for both `X` and `O` as potential winners using the `isWin` method and returns the result (positive for `X`, negative for `O`, or `0` for a tie). + +8. `toString` Method: + - The `toString` method converts the current game state to a human-readable string, representing the game board. It uses "X" and "O" to denote player marks and empty spaces as " " (space). + +9. `main` Method: + - In the `main` method, a new Tic-Tac-Toe game is created. + - A series of moves are made using `putMark`, and the game state is printed after each move. + - The final outcome of the game is determined using the `winner` method, and the result is displayed as "X wins," "O wins," or "Tie." + +The code provides a basic implementation of a command-line Tic-Tac-Toe game with validation for player moves and win conditions. It demonstrates how to represent the game board, make moves, and check for a win or tie in the game. + */ public class TicTacToe { public static final int X = 1, O = -1; public static final int EMPTY = 0; From 5121d75a4e082fc606935843e9dad889abb278f2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 28 Oct 2023 22:26:37 +0530 Subject: [PATCH 1853/1894] add LongestSubstringWithKDistinctChars --- ...ngest_substring_with_k_distinct_chars.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Sliding Window/longest_substring_with_k_distinct_chars.java diff --git a/Sliding Window/longest_substring_with_k_distinct_chars.java b/Sliding Window/longest_substring_with_k_distinct_chars.java new file mode 100644 index 00000000..1f410568 --- /dev/null +++ b/Sliding Window/longest_substring_with_k_distinct_chars.java @@ -0,0 +1,35 @@ + +/* + * Given a string, find the length of the longest substring in it with no more than K distinct characters. + + */ +public class LongestSubstringWithKDistinctChars { + public int longestSubstringWithKDistinctChars(String s, int k) { + if (s.length() == 0 || s == null || k ==0) { + return 0; + } + int startWindow = 0; + int maxlen = 0; + HashMap mp = new HashMap<>(); + for(int endWindow = 0; endWindow < s.length(); endWindow++) { + char right = s.charAt(endWindow); + mp.put(right, mp.getOrDefault(right, 0) + 1); + while (mp.size() > k) { + char left = s.charAt(startWindow); + mp.put(left, mp.get(left) - 1); + startWindow++; + if(mp.get(left) == 0) { + mp.remove(left); + } + } + maxlen = Math.max(maxlen, endWindow - startWindow + 1); + } + return maxlen; + } + public static void main(String[] args) { + LongestSubstringWithKDistinctChars l = new LongestSubstringWithKDistinctChars(); + System.out.println(l.longestSubstringWithKDistinctChars("araaci", 2)); + System.out.println(l.longestSubstringWithKDistinctChars("araaci", 1)); + System.out.println(l.longestSubstringWithKDistinctChars("cbbebi", 3)); + } +} From e14ac6637e3b534f02eb551f7d21db4be71fcb35 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 29 Oct 2023 18:41:25 +0530 Subject: [PATCH 1854/1894] add subarray sum equals k in java --- Sliding Window/subaray_sum_equals_k.java | 88 ++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Sliding Window/subaray_sum_equals_k.java diff --git a/Sliding Window/subaray_sum_equals_k.java b/Sliding Window/subaray_sum_equals_k.java new file mode 100644 index 00000000..f1e0d988 --- /dev/null +++ b/Sliding Window/subaray_sum_equals_k.java @@ -0,0 +1,88 @@ +/* + Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. + + A subarray is a contiguous non-empty sequence of elements within an array. + + + + Example 1: + + Input: nums = [1,1,1], k = 2 + Output: 2 + Example 2: + + Input: nums = [1,2,3], k = 3 + Output: 2 + + + ### Explanation: + + The code is designed to count the number of subarrays within the 'nums' array whose elements sum to a given target integer 'k'. + It uses a hashmap to efficiently keep track of cumulative sums and their counts. + + Here's the code's key logic: + + 1. It initializes a hashmap `sumIndex` to store cumulative sums as keys and their counts as values. + + 2. It initializes variables `result` and `currentSum`. + + 3. It adds a key-value pair of `(0, 1)` to the `sumIndex` hashmap to represent the sum of an empty subarray (0) and its count (1). + + 4. It iterates through the elements of the 'nums' array. + + 5. For each element, it adds the element's value to `currentSum`. + + 6. It calculates the value to find in the hashmap by subtracting 'k' from the current cumulative sum, which is stored in the `toFind` variable. + + 7. It checks if the hashmap contains the value 'toFind' and, if found, adds the count of subarrays that sum to 'toFind' to the 'result'. + + 8. It updates the hashmap with the current cumulative sum. If the sum is already in the hashmap, it increments its count by 1. If it's not in the hashmap, + it adds it with a count of 1. + + 9. Finally, it returns the 'result,' which represents the total number of subarrays with a sum of 'k'. + + ### Time Complexity: + + The time complexity of this code is O(n), where 'n' is the length of the 'nums' array. This is because the code iterates through the 'nums' + array once, and each iteration consists of constant-time operations (e.g., hashmap lookups and additions). + + ### Space Complexity: + + The space complexity of this code is O(n), where 'n' is the length of the 'nums' array. The space is primarily used for the hashmap `sumIndex`, + which can have up to 'n' distinct cumulative sums. In the worst case, all elements are unique, resulting in 'n' distinct cumulative sums, + each with a count of 1. + + In summary, this code efficiently counts subarrays with a sum of 'k' in O(n) time and uses O(n) space to store cumulative sums and their counts. + */ +public int subarraySum(int[] nums, int k) { + // Create a hashmap to store cumulative sums as keys and their counts as values. + HashMap sumIndex = new HashMap<>(); + // Initialize the result to 0. + int result = 0; + // Initialize a variable to track the current cumulative sum. + int currentSum = 0; + // Initialize the hashmap with a key-value pair representing the sum of an empty subarray (0) and its count (1). + sumIndex.put(0, 1); + + // Iterate through the elements of the 'nums' array. + for (int i = 0; i < nums.length; i++) { + // Add the current element to the cumulative sum. + currentSum += nums[i]; + // Calculate the value to find in the hashmap by subtracting 'k' from the current cumulative sum. + int toFind = currentSum - k; + + // Check if the hashmap contains the value 'toFind'. + if (sumIndex.containsKey(toFind)) { + // If found, add the count of subarrays that sum to 'toFind' to the 'result'. + result += sumIndex.get(toFind); + } + + // Update the hashmap with the current cumulative sum. + // If it's already in the hashmap, increment its count by 1. + // If it's not in the hashmap, add it with a count of 1. + sumIndex.put(currentSum, sumIndex.getOrDefault(currentSum, 0) + 1); + } + + // Return the final result, which represents the total number of subarrays with a sum of 'k'. + return result; +} From da3d7c644760cfc8747619125681a38360c5bc79 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 30 Oct 2023 23:46:57 +0530 Subject: [PATCH 1855/1894] add fruits into basket --- Sliding Window/fruits_into_basket.java | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Sliding Window/fruits_into_basket.java diff --git a/Sliding Window/fruits_into_basket.java b/Sliding Window/fruits_into_basket.java new file mode 100644 index 00000000..ffaaa730 --- /dev/null +++ b/Sliding Window/fruits_into_basket.java @@ -0,0 +1,28 @@ +/* + Fruits into basket +*/ +class Solution { + public int totalFruit(int[] fruits) { + int longest = 0; // Initialize a variable to track the longest subarray length + int max = 0; // Initialize a variable to store the maximum number of fruits + int startWindow = 0; // Initialize the left boundary of the window + HashMap basket = new HashMap<>(); // Create a HashMap to track fruit counts + + for(int endWindow = 0; endWindow < fruits.length; endWindow++) { + basket.put(fruits[endWindow], basket.getOrDefault(fruits[endWindow], 0) + 1); + // Add the current fruit to the basket and increment its count + + while(basket.size() > 2) { + basket.put(fruits[startWindow], basket.get(fruits[startWindow]) - 1); + basket.remove(fruits[startWindow], 0); + // Adjust the window to maintain at most two fruit types + startWindow++; // Move the left boundary of the window to the right + } + + max = Math.max(max, (endWindow - startWindow) + 1); + // Update max with the maximum window size seen so far + } + + return max; // Return the maximum number of fruits that can be collected + } +} From 9b6f88c09082f44b3a30b54a29133891a5f4885c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 30 Oct 2023 23:48:09 +0530 Subject: [PATCH 1856/1894] add comments --- Sliding Window/fruits_into_basket.java | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Sliding Window/fruits_into_basket.java b/Sliding Window/fruits_into_basket.java index ffaaa730..fd2d8649 100644 --- a/Sliding Window/fruits_into_basket.java +++ b/Sliding Window/fruits_into_basket.java @@ -1,5 +1,40 @@ /* Fruits into basket + Summary: + The given code defines a Java class `Solution` with a method `totalFruit` that solves a problem related to collecting fruits + from fruit trees while adhering to a constraint of collecting fruits from at most two different types of fruit trees. + The code uses a sliding window approach to find the maximum number of fruits that can be collected from the trees under + this constraint. + + - The `fruits` array represents the types of fruit trees, where each element represents a type of fruit. + + - The code initializes variables `longest` and `max` to keep track of the length of the longest subarray with at + most two distinct elements and the maximum number of fruits collected, respectively. + + - The `startWindow` variable represents the left boundary of the sliding window. + + - A `HashMap` called `basket` is used to keep track of the count of each type of fruit in the current window. + + - The code iterates through the `fruits` array using two pointers, `startWindow` and `endWindow`, to traverse + the array from left to right. + + - Within the loop, the code updates the `basket` map with the count of fruit types in the current window, and it + ensures that there are at most two different types of fruits in the window by adjusting the window as needed. + + - The `max` variable is updated with the maximum window size seen so far. + + - Finally, the method returns `max`, which represents the maximum number of fruits that can be collected under + the given constraint. + + Space Complexity: + - The space complexity of this code is O(1) in addition to the input `fruits` array. This is because the space used + for variables such as `longest`, `max`, `startWindow`, and `basket` remains constant and does not depend on the size + of the `fruits` array. + + Time Complexity: + - The time complexity of this code is O(n), where 'n' is the length of the `fruits` array. The code iterates through the + `fruits` array once with two pointers, and the work done within each iteration is constant time. Therefore, the overall + time complexity is linear in the size of the input array. */ class Solution { public int totalFruit(int[] fruits) { From e09ee60384d058408a47e0dafa70dced1034937c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Oct 2023 23:41:27 +0530 Subject: [PATCH 1857/1894] add fruits intobaskets in js --- Sliding Window/fruits_into_basket.js | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Sliding Window/fruits_into_basket.js diff --git a/Sliding Window/fruits_into_basket.js b/Sliding Window/fruits_into_basket.js new file mode 100644 index 00000000..76fd3006 --- /dev/null +++ b/Sliding Window/fruits_into_basket.js @@ -0,0 +1,63 @@ +/* + Fruits into basket + Summary: + The given code defines a Java class `Solution` with a method `totalFruit` that solves a problem related to collecting fruits + from fruit trees while adhering to a constraint of collecting fruits from at most two different types of fruit trees. + The code uses a sliding window approach to find the maximum number of fruits that can be collected from the trees under + this constraint. + + - The `fruits` array represents the types of fruit trees, where each element represents a type of fruit. + + - The code initializes variables `longest` and `max` to keep track of the length of the longest subarray with at + most two distinct elements and the maximum number of fruits collected, respectively. + + - The `startWindow` variable represents the left boundary of the sliding window. + + - A `HashMap` called `basket` is used to keep track of the count of each type of fruit in the current window. + + - The code iterates through the `fruits` array using two pointers, `startWindow` and `endWindow`, to traverse + the array from left to right. + + - Within the loop, the code updates the `basket` map with the count of fruit types in the current window, and it + ensures that there are at most two different types of fruits in the window by adjusting the window as needed. + + - The `max` variable is updated with the maximum window size seen so far. + + - Finally, the method returns `max`, which represents the maximum number of fruits that can be collected under + the given constraint. + + Space Complexity: + - The space complexity of this code is O(1) in addition to the input `fruits` array. This is because the space used + for variables such as `longest`, `max`, `startWindow`, and `basket` remains constant and does not depend on the size + of the `fruits` array. + + Time Complexity: + - The time complexity of this code is O(n), where 'n' is the length of the `fruits` array. The code iterates through the + `fruits` array once with two pointers, and the work done within each iteration is constant time. Therefore, the overall + time complexity is linear in the size of the input array. + */ +var totalFruit = function (fruits) { + let longest = 0; // Initialize a variable to track the longest subarray length + let maxFruits = 0; // Initialize a variable to store the maximum number of fruits + let startWindow = 0; // Initialize the left boundary of the window + const basket = new Map(); // Create a Map to track fruit counts + + for (let endWindow = 0; endWindow < fruits.length; endWindow++) { + basket.set(fruits[endWindow], (basket.get(fruits[endWindow]) || 0) + 1); + // Add the current fruit to the basket and increment its count + + while (basket.size > 2) { + basket.set(fruits[startWindow], basket.get(fruits[startWindow]) - 1); + if (basket.get(fruits[startWindow]) === 0) { + basket.delete(fruits[startWindow]); + } + // Adjust the window to maintain at most two fruit types + startWindow++; // Move the left boundary of the window to the right + } + + maxFruits = Math.max(maxFruits, endWindow - startWindow + 1); + // Update maxFruits with the maximum window size seen so far + } + + return maxFruits; // Return the maximum number of fruits that can be collected +}; From 4a9c9a412dcc24601624498c6f0eb444bf9e9713 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 31 Oct 2023 23:41:35 +0530 Subject: [PATCH 1858/1894] add fruits into baskets in python --- Sliding Window/fruits_into_basket.py | 60 ++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Sliding Window/fruits_into_basket.py diff --git a/Sliding Window/fruits_into_basket.py b/Sliding Window/fruits_into_basket.py new file mode 100644 index 00000000..123c184a --- /dev/null +++ b/Sliding Window/fruits_into_basket.py @@ -0,0 +1,60 @@ +''' + Fruits into basket + Summary: + The given code defines a Java class `Solution` with a method `totalFruit` that solves a problem related to collecting fruits + from fruit trees while adhering to a constraint of collecting fruits from at most two different types of fruit trees. + The code uses a sliding window approach to find the maximum number of fruits that can be collected from the trees under + this constraint. + + - The `fruits` array represents the types of fruit trees, where each element represents a type of fruit. + + - The code initializes variables `longest` and `max` to keep track of the length of the longest subarray with at + most two distinct elements and the maximum number of fruits collected, respectively. + + - The `startWindow` variable represents the left boundary of the sliding window. + + - A `HashMap` called `basket` is used to keep track of the count of each type of fruit in the current window. + + - The code iterates through the `fruits` array using two pointers, `startWindow` and `endWindow`, to traverse + the array from left to right. + + - Within the loop, the code updates the `basket` map with the count of fruit types in the current window, and it + ensures that there are at most two different types of fruits in the window by adjusting the window as needed. + + - The `max` variable is updated with the maximum window size seen so far. + + - Finally, the method returns `max`, which represents the maximum number of fruits that can be collected under + the given constraint. + + Space Complexity: + - The space complexity of this code is O(1) in addition to the input `fruits` array. This is because the space used + for variables such as `longest`, `max`, `startWindow`, and `basket` remains constant and does not depend on the size + of the `fruits` array. + + Time Complexity: + - The time complexity of this code is O(n), where 'n' is the length of the `fruits` array. The code iterates through the + `fruits` array once with two pointers, and the work done within each iteration is constant time. Therefore, the overall + time complexity is linear in the size of the input array. +''' +class Solution: + def totalFruit(self, fruits): + longest = 0 # Initialize a variable to track the longest subarray length + max_fruits = 0 # Initialize a variable to store the maximum number of fruits + start_window = 0 # Initialize the left boundary of the window + basket = {} # Create a dictionary to track fruit counts + + for end_window in range(len(fruits)): + basket[fruits[end_window]] = basket.get(fruits[end_window], 0) + 1 + # Add the current fruit to the basket and increment its count + + while len(basket) > 2: + basket[fruits[start_window]] -= 1 + if basket[fruits[start_window]] == 0: + del basket[fruits[start_window]] + # Adjust the window to maintain at most two fruit types + start_window += 1 # Move the left boundary of the window to the right + + max_fruits = max(max_fruits, (end_window - start_window) + 1) + # Update max_fruits with the maximum window size seen so far + + return max_fruits # Return the maximum number of fruits that can be collected From 72c1f54d61ad203a5624697a541fcbedce39a480 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Nov 2023 23:38:38 +0530 Subject: [PATCH 1859/1894] add fruits into basket in c++ --- Sliding Window/fruits_into_basket.cpp | 79 +++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Sliding Window/fruits_into_basket.cpp diff --git a/Sliding Window/fruits_into_basket.cpp b/Sliding Window/fruits_into_basket.cpp new file mode 100644 index 00000000..cf5571a1 --- /dev/null +++ b/Sliding Window/fruits_into_basket.cpp @@ -0,0 +1,79 @@ +/* + Fruits into basket + Summary: + The given code defines a Java class `Solution` with a method `totalFruit` that solves a problem related to collecting fruits + from fruit trees while adhering to a constraint of collecting fruits from at most two different types of fruit trees. + The code uses a sliding window approach to find the maximum number of fruits that can be collected from the trees under + this constraint. + + - The `fruits` array represents the types of fruit trees, where each element represents a type of fruit. + + - The code initializes variables `longest` and `max` to keep track of the length of the longest subarray with at + most two distinct elements and the maximum number of fruits collected, respectively. + + - The `startWindow` variable represents the left boundary of the sliding window. + + - A `HashMap` called `basket` is used to keep track of the count of each type of fruit in the current window. + + - The code iterates through the `fruits` array using two pointers, `startWindow` and `endWindow`, to traverse + the array from left to right. + + - Within the loop, the code updates the `basket` map with the count of fruit types in the current window, and it + ensures that there are at most two different types of fruits in the window by adjusting the window as needed. + + - The `max` variable is updated with the maximum window size seen so far. + + - Finally, the method returns `max`, which represents the maximum number of fruits that can be collected under + the given constraint. + + Space Complexity: + - The space complexity of this code is O(1) in addition to the input `fruits` array. This is because the space used + for variables such as `longest`, `max`, `startWindow`, and `basket` remains constant and does not depend on the size + of the `fruits` array. + + Time Complexity: + - The time complexity of this code is O(n), where 'n' is the length of the `fruits` array. The code iterates through the + `fruits` array once with two pointers, and the work done within each iteration is constant time. Therefore, the overall + time complexity is linear in the size of the input array. +*/ +#include +#include +#include + +using namespace std; + +int totalFruit(vector& fruits) { + int longest = 0; // Initialize a variable to track the longest subarray length + int maxFruits = 0; // Initialize a variable to store the maximum number of fruits + int startWindow = 0; // Initialize the left boundary of the window + unordered_map basket; // Create an unordered_map to track fruit counts + + for (int endWindow = 0; endWindow < fruits.size(); endWindow++) { + basket[fruits[endWindow]]++; + // Add the current fruit to the basket and increment its count + + while (basket.size() > 2) { + basket[fruits[startWindow]]--; + if (basket[fruits[startWindow]] == 0) { + basket.erase(fruits[startWindow]); + } + // Adjust the window to maintain at most two fruit types + startWindow++; // Move the left boundary of the window to the right + } + + maxFruits = max(maxFruits, endWindow - startWindow + 1); + // Update maxFruits with the maximum window size seen so far + } + + return maxFruits; // Return the maximum number of fruits that can be collected +} + +int main() { + vector fruits = {1, 2, 1, 2, 3}; + + int result = totalFruit(fruits); + + cout << result << endl; + + return 0; +} From 30cb48d5b49a991895dfb8202fe30166c904b292 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 1 Nov 2023 23:38:43 +0530 Subject: [PATCH 1860/1894] add fruits into basket in go --- Sliding Window/fruits_into_basket.go | 77 ++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Sliding Window/fruits_into_basket.go diff --git a/Sliding Window/fruits_into_basket.go b/Sliding Window/fruits_into_basket.go new file mode 100644 index 00000000..aedb3758 --- /dev/null +++ b/Sliding Window/fruits_into_basket.go @@ -0,0 +1,77 @@ +/* + Fruits into basket + Summary: + The given code defines a Java class `Solution` with a method `totalFruit` that solves a problem related to collecting fruits + from fruit trees while adhering to a constraint of collecting fruits from at most two different types of fruit trees. + The code uses a sliding window approach to find the maximum number of fruits that can be collected from the trees under + this constraint. + + - The `fruits` array represents the types of fruit trees, where each element represents a type of fruit. + + - The code initializes variables `longest` and `max` to keep track of the length of the longest subarray with at + most two distinct elements and the maximum number of fruits collected, respectively. + + - The `startWindow` variable represents the left boundary of the sliding window. + + - A `HashMap` called `basket` is used to keep track of the count of each type of fruit in the current window. + + - The code iterates through the `fruits` array using two pointers, `startWindow` and `endWindow`, to traverse + the array from left to right. + + - Within the loop, the code updates the `basket` map with the count of fruit types in the current window, and it + ensures that there are at most two different types of fruits in the window by adjusting the window as needed. + + - The `max` variable is updated with the maximum window size seen so far. + + - Finally, the method returns `max`, which represents the maximum number of fruits that can be collected under + the given constraint. + + Space Complexity: + - The space complexity of this code is O(1) in addition to the input `fruits` array. This is because the space used + for variables such as `longest`, `max`, `startWindow`, and `basket` remains constant and does not depend on the size + of the `fruits` array. + + Time Complexity: + - The time complexity of this code is O(n), where 'n' is the length of the `fruits` array. The code iterates through the + `fruits` array once with two pointers, and the work done within each iteration is constant time. Therefore, the overall + time complexity is linear in the size of the input array. +*/ +package main + +import "fmt" + +func totalFruit(fruits []int) int { + longest := 0 // Initialize a variable to track the longest subarray length + maxFruits := 0 // Initialize a variable to store the maximum number of fruits + startWindow := 0 // Initialize the left boundary of the window + basket := make(map[int]int) // Create a map to track fruit counts + + for endWindow := 0; endWindow < len(fruits); endWindow++ { + basket[fruits[endWindow]]++ + // Add the current fruit to the basket and increment its count + + for len(basket) > 2 { + basket[fruits[startWindow]]-- + if basket[fruits[startWindow]] == 0 { + delete(basket, fruits[startWindow]) + } + // Adjust the window to maintain at most two fruit types + startWindow++ // Move the left boundary of the window to the right + } + + if endWindow-startWindow+1 > maxFruits { + maxFruits = endWindow - startWindow + 1 + } + // Update maxFruits with the maximum window size seen so far + } + + return maxFruits // Return the maximum number of fruits that can be collected +} + +func main() { + fruits := []int{1, 2, 1, 2, 3} + + result := totalFruit(fruits) + + fmt.Println(result) +} From c0cd8be8718fbeefe42a9bb61f0223546816acd2 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Nov 2023 23:25:03 +0530 Subject: [PATCH 1861/1894] add comments --- ...ngest_substring_with_k_distinct_chars.java | 34 ++++++++++++------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/Sliding Window/longest_substring_with_k_distinct_chars.java b/Sliding Window/longest_substring_with_k_distinct_chars.java index 1f410568..59e4b554 100644 --- a/Sliding Window/longest_substring_with_k_distinct_chars.java +++ b/Sliding Window/longest_substring_with_k_distinct_chars.java @@ -5,27 +5,35 @@ */ public class LongestSubstringWithKDistinctChars { public int longestSubstringWithKDistinctChars(String s, int k) { - if (s.length() == 0 || s == null || k ==0) { + // Check for edge cases where s is empty, null, or k is 0. + if (s.length() == 0 || s == null || k == 0) { return 0; } - int startWindow = 0; - int maxlen = 0; - HashMap mp = new HashMap<>(); - for(int endWindow = 0; endWindow < s.length(); endWindow++) { - char right = s.charAt(endWindow); - mp.put(right, mp.getOrDefault(right, 0) + 1); + + int startWindow = 0; // Initialize the start of the sliding window. + int maxlen = 0; // Initialize the maximum length of the substring. + HashMap mp = new HashMap(); // Create a HashMap to store character frequencies. + + for (int endWindow = 0; endWindow < s.length(); endWindow++) { + char right = s.charAt(endWindow); // Get the character at the end of the window. + mp.put(right, mp.getOrDefault(right, 0) + 1); // Update the character count in the HashMap. + + // While there are more than k distinct characters in the window. while (mp.size() > k) { - char left = s.charAt(startWindow); - mp.put(left, mp.get(left) - 1); - startWindow++; - if(mp.get(left) == 0) { - mp.remove(left); + char left = s.charAt(startWindow); // Get the character at the start of the window. + mp.put(left, mp.get(left) - 1); // Decrease the count of the character. + startWindow++; // Move the start of the window to the right. + + if (mp.get(left) == 0) { + mp.remove(left); // If the count becomes 0, remove the character from the HashMap. } } - maxlen = Math.max(maxlen, endWindow - startWindow + 1); + + maxlen = Math.max(maxlen, endWindow - startWindow + 1); // Update the maximum length. } return maxlen; } + public static void main(String[] args) { LongestSubstringWithKDistinctChars l = new LongestSubstringWithKDistinctChars(); System.out.println(l.longestSubstringWithKDistinctChars("araaci", 2)); From 452a58068e8dde4411eeb98bb96ecfa6d40fd665 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 2 Nov 2023 23:32:37 +0530 Subject: [PATCH 1862/1894] add longestSubstringWithKDistinctChars in go --- ...longest_substring_with_k_distinct_chars.go | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Sliding Window/longest_substring_with_k_distinct_chars.go diff --git a/Sliding Window/longest_substring_with_k_distinct_chars.go b/Sliding Window/longest_substring_with_k_distinct_chars.go new file mode 100644 index 00000000..63491976 --- /dev/null +++ b/Sliding Window/longest_substring_with_k_distinct_chars.go @@ -0,0 +1,51 @@ +/* + * Given a string, find the length of the longest substring in it with no more than K distinct characters. + + */ +package main + +import ( + "fmt" +) + +func longestSubstringWithKDistinctChars(s string, k int) int { + // Check for edge cases where s is empty, or k is 0. + if len(s) == 0 || k == 0 { + return 0 + } + + startWindow := 0 // Initialize the start of the sliding window. + maxLen := 0 // Initialize the maximum length of the substring. + charCount := make(map[byte]int) // Create a map to store character frequencies. + + for endWindow := 0; endWindow < len(s); endWindow++ { + right := s[endWindow] // Get the character at the end of the window. + charCount[right]++ // Update the character count in the map. + + // While there are more than k distinct characters in the window. + for len(charCount) > k { + left := s[startWindow] // Get the character at the start of the window. + charCount[left]-- // Decrease the count of the character. + if charCount[left] == 0 { + delete(charCount, left) // If the count becomes 0, remove the character from the map. + } + startWindow++ // Move the start of the window to the right. + } + + maxLen = max(maxLen, endWindow-startWindow+1) // Update the maximum length. + } + return maxLen +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func main() { + fmt.Println(longestSubstringWithKDistinctChars("araaci", 2)) + fmt.Println(longestSubstringWithKDistinctChars("araaci", 1)) + fmt.Println(longestSubstringWithKDistinctChars("cbbebi", 3)) +} From 6dea3fedbfbf0c96b051e630324f9432ea8496c5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Nov 2023 22:51:38 +0530 Subject: [PATCH 1863/1894] add longest_substring_with_k_distinct_chars --- ...longest_substring_with_k_distinct_chars.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sliding Window/longest_substring_with_k_distinct_chars.py diff --git a/Sliding Window/longest_substring_with_k_distinct_chars.py b/Sliding Window/longest_substring_with_k_distinct_chars.py new file mode 100644 index 00000000..adb1fc7c --- /dev/null +++ b/Sliding Window/longest_substring_with_k_distinct_chars.py @@ -0,0 +1,38 @@ +''' +Given a string, find the length of the longest substring in it with no more than K distinct characters. + +''' +def longestSubstringWithKDistinctChars(s, k): + # Check for edge cases where s is empty, or k is 0. + if not s or k == 0: + return 0 + + start_window = 0 # Initialize the start of the sliding window. + max_len = 0 # Initialize the maximum length of the substring. + char_count = {} # Create a dictionary to store character frequencies. + + for end_window in range(len(s)): + right = s[end_window] # Get the character at the end of the window. + char_count[right] = char_count.get(right, 0) + 1 # Update the character count in the dictionary. + + # While there are more than k distinct characters in the window. + while len(char_count) > k: + left = s[start_window] # Get the character at the start of the window. + char_count[left] -= 1 # Decrease the count of the character. + if char_count[left] == 0: + del char_count[left] # If the count becomes 0, remove the character from the dictionary. + start_window += 1 # Move the start of the window to the right. + + max_len = max(max_len, end_window - start_window + 1) # Update the maximum length. + + return max_len + +def max(a, b): + if a > b: + return a + return b + +if __name__ == "__main__": + print(longestSubstringWithKDistinctChars("araaci", 2)) + print(longestSubstringWithKDistinctChars("araaci", 1)) + print(longestSubstringWithKDistinctChars("cbbebi", 3)) From 7c342ecb0816cf9a493b3590f9563c1e9da52b40 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 3 Nov 2023 22:52:54 +0530 Subject: [PATCH 1864/1894] add longest_substring_with_k_distinct_chars --- ...longest_substring_with_k_distinct_chars.js | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Sliding Window/longest_substring_with_k_distinct_chars.js diff --git a/Sliding Window/longest_substring_with_k_distinct_chars.js b/Sliding Window/longest_substring_with_k_distinct_chars.js new file mode 100644 index 00000000..5a418427 --- /dev/null +++ b/Sliding Window/longest_substring_with_k_distinct_chars.js @@ -0,0 +1,41 @@ +/* + * Given a string, find the length of the longest substring in it with no more than K distinct characters. + + */ +function longestSubstringWithKDistinctChars(s, k) { + // Check for edge cases where s is empty, or k is 0. + if (!s || k === 0) { + return 0; + } + + let startWindow = 0; // Initialize the start of the sliding window. + let maxLen = 0; // Initialize the maximum length of the substring. + const charCount = {}; // Create an object to store character frequencies. + + for (let endWindow = 0; endWindow < s.length; endWindow++) { + const right = s[endWindow]; // Get the character at the end of the window. + charCount[right] = (charCount[right] || 0) + 1; // Update the character count in the object. + + // While there are more than k distinct characters in the window. + while (Object.keys(charCount).length > k) { + const left = s[startWindow]; // Get the character at the start of the window. + charCount[left]--; // Decrease the count of the character. + if (charCount[left] === 0) { + delete charCount[left]; // If the count becomes 0, remove the character from the object. + } + startWindow++; // Move the start of the window to the right. + } + + maxLen = Math.max(maxLen, endWindow - startWindow + 1); // Update the maximum length. + } + + return maxLen; +} + +function max(a, b) { + return a > b ? a : b; +} + +console.log(longestSubstringWithKDistinctChars("araaci", 2)); +console.log(longestSubstringWithKDistinctChars("araaci", 1)); +console.log(longestSubstringWithKDistinctChars("cbbebi", 3)); From 8269f5a80ae08a1329e163423bc801171fe4d075 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Nov 2023 22:58:29 +0530 Subject: [PATCH 1865/1894] add subarray sum in go --- Sliding Window/subaray_sum_equals_k.go | 88 ++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Sliding Window/subaray_sum_equals_k.go diff --git a/Sliding Window/subaray_sum_equals_k.go b/Sliding Window/subaray_sum_equals_k.go new file mode 100644 index 00000000..808cc626 --- /dev/null +++ b/Sliding Window/subaray_sum_equals_k.go @@ -0,0 +1,88 @@ +/* + Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. + + A subarray is a contiguous non-empty sequence of elements within an array. + + + + Example 1: + + Input: nums = [1,1,1], k = 2 + Output: 2 + Example 2: + + Input: nums = [1,2,3], k = 3 + Output: 2 + + + ### Explanation: + + The code is designed to count the number of subarrays within the 'nums' array whose elements sum to a given target integer 'k'. + It uses a hashmap to efficiently keep track of cumulative sums and their counts. + + Here's the code's key logic: + + 1. It initializes a hashmap `sumIndex` to store cumulative sums as keys and their counts as values. + + 2. It initializes variables `result` and `currentSum`. + + 3. It adds a key-value pair of `(0, 1)` to the `sumIndex` hashmap to represent the sum of an empty subarray (0) and its count (1). + + 4. It iterates through the elements of the 'nums' array. + + 5. For each element, it adds the element's value to `currentSum`. + + 6. It calculates the value to find in the hashmap by subtracting 'k' from the current cumulative sum, which is stored in the `toFind` variable. + + 7. It checks if the hashmap contains the value 'toFind' and, if found, adds the count of subarrays that sum to 'toFind' to the 'result'. + + 8. It updates the hashmap with the current cumulative sum. If the sum is already in the hashmap, it increments its count by 1. If it's not in the hashmap, + it adds it with a count of 1. + + 9. Finally, it returns the 'result,' which represents the total number of subarrays with a sum of 'k'. + + ### Time Complexity: + + The time complexity of this code is O(n), where 'n' is the length of the 'nums' array. This is because the code iterates through the 'nums' + array once, and each iteration consists of constant-time operations (e.g., hashmap lookups and additions). + + ### Space Complexity: + + The space complexity of this code is O(n), where 'n' is the length of the 'nums' array. The space is primarily used for the hashmap `sumIndex`, + which can have up to 'n' distinct cumulative sums. In the worst case, all elements are unique, resulting in 'n' distinct cumulative sums, + each with a count of 1. + + In summary, this code efficiently counts subarrays with a sum of 'k' in O(n) time and uses O(n) space to store cumulative sums and their counts. + */ + func subarraySum(nums []int, k int) int { + // Create a map to store cumulative sums as keys and their counts as values. + sumIndex := make(map[int]int) + // Initialize the result to 0. + result := 0 + // Initialize a variable to track the current cumulative sum. + currentSum := 0 + // Initialize the map with a key-value pair representing the sum of an empty subarray (0) and its count (1). + sumIndex[0] = 1 + + // Iterate through the elements of the 'nums' slice. + for _, num := range nums { + // Add the current element to the cumulative sum. + currentSum += num + // Calculate the value to find in the map by subtracting 'k' from the current cumulative sum. + toFind := currentSum - k + + // Check if the map contains the value 'toFind'. + if count, ok := sumIndex[toFind]; ok { + // If found, add the count of subarrays that sum to 'toFind' to the 'result'. + result += count + } + + // Update the map with the current cumulative sum. + // If it's already in the map, increment its count by 1. + // If it's not in the map, add it with a count of 1. + sumIndex[currentSum]++ + } + + // Return the final result, which represents the total number of subarrays with a sum of 'k'. + return result +} From 31cf999b5f96378c86b0749a9195c41b885f8265 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 4 Nov 2023 22:58:38 +0530 Subject: [PATCH 1866/1894] add subarray sum k in python --- Sliding Window/subaray_sum_equals_k.py | 85 ++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 Sliding Window/subaray_sum_equals_k.py diff --git a/Sliding Window/subaray_sum_equals_k.py b/Sliding Window/subaray_sum_equals_k.py new file mode 100644 index 00000000..0eaa7da3 --- /dev/null +++ b/Sliding Window/subaray_sum_equals_k.py @@ -0,0 +1,85 @@ +''' +Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. + + A subarray is a contiguous non-empty sequence of elements within an array. + + + + Example 1: + + Input: nums = [1,1,1], k = 2 + Output: 2 + Example 2: + + Input: nums = [1,2,3], k = 3 + Output: 2 + + + ### Explanation: + + The code is designed to count the number of subarrays within the 'nums' array whose elements sum to a given target integer 'k'. + It uses a hashmap to efficiently keep track of cumulative sums and their counts. + + Here's the code's key logic: + + 1. It initializes a hashmap `sumIndex` to store cumulative sums as keys and their counts as values. + + 2. It initializes variables `result` and `currentSum`. + + 3. It adds a key-value pair of `(0, 1)` to the `sumIndex` hashmap to represent the sum of an empty subarray (0) and its count (1). + + 4. It iterates through the elements of the 'nums' array. + + 5. For each element, it adds the element's value to `currentSum`. + + 6. It calculates the value to find in the hashmap by subtracting 'k' from the current cumulative sum, which is stored in the `toFind` variable. + + 7. It checks if the hashmap contains the value 'toFind' and, if found, adds the count of subarrays that sum to 'toFind' to the 'result'. + + 8. It updates the hashmap with the current cumulative sum. If the sum is already in the hashmap, it increments its count by 1. If it's not in the hashmap, + it adds it with a count of 1. + + 9. Finally, it returns the 'result,' which represents the total number of subarrays with a sum of 'k'. + + ### Time Complexity: + + The time complexity of this code is O(n), where 'n' is the length of the 'nums' array. This is because the code iterates through the 'nums' + array once, and each iteration consists of constant-time operations (e.g., hashmap lookups and additions). + + ### Space Complexity: + + The space complexity of this code is O(n), where 'n' is the length of the 'nums' array. The space is primarily used for the hashmap `sumIndex`, + which can have up to 'n' distinct cumulative sums. In the worst case, all elements are unique, resulting in 'n' distinct cumulative sums, + each with a count of 1. + + In summary, this code efficiently counts subarrays with a sum of 'k' in O(n) time and uses O(n) space to store cumulative sums and their counts. + +''' +def subarraySum(nums, k): + # Create a dictionary to store cumulative sums as keys and their counts as values. + sum_index = {0: 1} + # Initialize the result to 0. + result = 0 + # Initialize a variable to track the current cumulative sum. + current_sum = 0 + + # Iterate through the elements of the 'nums' list. + for num in nums: + # Add the current element to the cumulative sum. + current_sum += num + # Calculate the value to find in the dictionary by subtracting 'k' from the current cumulative sum. + to_find = current_sum - k + + # Check if the dictionary contains the value 'to_find'. + if to_find in sum_index: + # If found, add the count of subarrays that sum to 'to_find' to the 'result'. + result += sum_index[to_find] + + # Update the dictionary with the current cumulative sum. + # If it's already in the dictionary, increment its count by 1. + # If it's not in the dictionary, add it with a count of 1. + sum_index[current_sum] = sum_index.get(current_sum, 0) + 1 + + # Return the final result, which represents the total number of subarrays with a sum of 'k'. + return result + From b3522f427efaf6401535670f77cde0130295b328 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Nov 2023 19:24:53 +0530 Subject: [PATCH 1867/1894] add subarray sum equals k in cpp --- Sliding Window/subaray_sum_equals_k.cpp | 101 ++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 Sliding Window/subaray_sum_equals_k.cpp diff --git a/Sliding Window/subaray_sum_equals_k.cpp b/Sliding Window/subaray_sum_equals_k.cpp new file mode 100644 index 00000000..13f1b5b6 --- /dev/null +++ b/Sliding Window/subaray_sum_equals_k.cpp @@ -0,0 +1,101 @@ +/* + Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. + + A subarray is a contiguous non-empty sequence of elements within an array. + + + + Example 1: + + Input: nums = [1,1,1], k = 2 + Output: 2 + Example 2: + + Input: nums = [1,2,3], k = 3 + Output: 2 + + + ### Explanation: + + The code is designed to count the number of subarrays within the 'nums' array whose elements sum to a given target integer 'k'. + It uses a hashmap to efficiently keep track of cumulative sums and their counts. + + Here's the code's key logic: + + 1. It initializes a hashmap `sumIndex` to store cumulative sums as keys and their counts as values. + + 2. It initializes variables `result` and `currentSum`. + + 3. It adds a key-value pair of `(0, 1)` to the `sumIndex` hashmap to represent the sum of an empty subarray (0) and its count (1). + + 4. It iterates through the elements of the 'nums' array. + + 5. For each element, it adds the element's value to `currentSum`. + + 6. It calculates the value to find in the hashmap by subtracting 'k' from the current cumulative sum, which is stored in the `toFind` variable. + + 7. It checks if the hashmap contains the value 'toFind' and, if found, adds the count of subarrays that sum to 'toFind' to the 'result'. + + 8. It updates the hashmap with the current cumulative sum. If the sum is already in the hashmap, it increments its count by 1. If it's not in the hashmap, + it adds it with a count of 1. + + 9. Finally, it returns the 'result,' which represents the total number of subarrays with a sum of 'k'. + + ### Time Complexity: + + The time complexity of this code is O(n), where 'n' is the length of the 'nums' array. This is because the code iterates through the 'nums' + array once, and each iteration consists of constant-time operations (e.g., hashmap lookups and additions). + + ### Space Complexity: + + The space complexity of this code is O(n), where 'n' is the length of the 'nums' array. The space is primarily used for the hashmap `sumIndex`, + which can have up to 'n' distinct cumulative sums. In the worst case, all elements are unique, resulting in 'n' distinct cumulative sums, + each with a count of 1. + + In summary, this code efficiently counts subarrays with a sum of 'k' in O(n) time and uses O(n) space to store cumulative sums and their counts. + */ +#include +#include +#include + +int subarraySum(std::vector& nums, int k) { + // Create an unordered_map to store cumulative sums as keys and their counts as values. + std::unordered_map sumIndex; + // Initialize the result to 0. + int result = 0; + // Initialize a variable to track the current cumulative sum. + int currentSum = 0; + // Initialize the unordered_map with a key-value pair representing the sum of an empty subarray (0) and its count (1). + sumIndex[0] = 1; + + // Iterate through the elements of the 'nums' vector. + for (int i = 0; i < nums.size(); i++) { + // Add the current element to the cumulative sum. + currentSum += nums[i]; + // Calculate the value to find in the unordered_map by subtracting 'k' from the current cumulative sum. + int toFind = currentSum - k; + + // Check if the unordered_map contains the value 'toFind'. + if (sumIndex.find(toFind) != sumIndex.end()) { + // If found, add the count of subarrays that sum to 'toFind' to the 'result'. + result += sumIndex[toFind]; + } + + // Update the unordered_map with the current cumulative sum. + // If it's already in the unordered_map, increment its count by 1. + // If it's not in the unordered_map, add it with a count of 1. + sumIndex[currentSum]++; + + } + + // Return the final result, which represents the total number of subarrays with a sum of 'k'. + return result; +} + +int main() { + std::vector nums = {1, 1, 1}; + int k = 2; + int result = subarraySum(nums, k); + std::cout << "Number of subarrays with sum " << k << " is: " << result << std::endl; + return 0; +} From ddd08904104ba76b9489de8d4425506c8543e103 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 5 Nov 2023 19:24:57 +0530 Subject: [PATCH 1868/1894] add subarray sum equals k in js --- Sliding Window/subaray_sum_equals_k.js | 88 ++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Sliding Window/subaray_sum_equals_k.js diff --git a/Sliding Window/subaray_sum_equals_k.js b/Sliding Window/subaray_sum_equals_k.js new file mode 100644 index 00000000..8f3d19e6 --- /dev/null +++ b/Sliding Window/subaray_sum_equals_k.js @@ -0,0 +1,88 @@ +/* + Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. + + A subarray is a contiguous non-empty sequence of elements within an array. + + + + Example 1: + + Input: nums = [1,1,1], k = 2 + Output: 2 + Example 2: + + Input: nums = [1,2,3], k = 3 + Output: 2 + + + ### Explanation: + + The code is designed to count the number of subarrays within the 'nums' array whose elements sum to a given target integer 'k'. + It uses a hashmap to efficiently keep track of cumulative sums and their counts. + + Here's the code's key logic: + + 1. It initializes a hashmap `sumIndex` to store cumulative sums as keys and their counts as values. + + 2. It initializes variables `result` and `currentSum`. + + 3. It adds a key-value pair of `(0, 1)` to the `sumIndex` hashmap to represent the sum of an empty subarray (0) and its count (1). + + 4. It iterates through the elements of the 'nums' array. + + 5. For each element, it adds the element's value to `currentSum`. + + 6. It calculates the value to find in the hashmap by subtracting 'k' from the current cumulative sum, which is stored in the `toFind` variable. + + 7. It checks if the hashmap contains the value 'toFind' and, if found, adds the count of subarrays that sum to 'toFind' to the 'result'. + + 8. It updates the hashmap with the current cumulative sum. If the sum is already in the hashmap, it increments its count by 1. If it's not in the hashmap, + it adds it with a count of 1. + + 9. Finally, it returns the 'result,' which represents the total number of subarrays with a sum of 'k'. + + ### Time Complexity: + + The time complexity of this code is O(n), where 'n' is the length of the 'nums' array. This is because the code iterates through the 'nums' + array once, and each iteration consists of constant-time operations (e.g., hashmap lookups and additions). + + ### Space Complexity: + + The space complexity of this code is O(n), where 'n' is the length of the 'nums' array. The space is primarily used for the hashmap `sumIndex`, + which can have up to 'n' distinct cumulative sums. In the worst case, all elements are unique, resulting in 'n' distinct cumulative sums, + each with a count of 1. + + In summary, this code efficiently counts subarrays with a sum of 'k' in O(n) time and uses O(n) space to store cumulative sums and their counts. + */ +function subarraySum(nums, k) { + // Create a map to store cumulative sums as keys and their counts as values. + const sumIndex = new Map(); + // Initialize the result to 0. + let result = 0; + // Initialize a variable to track the current cumulative sum. + let currentSum = 0; + // Initialize the map with a key-value pair representing the sum of an empty subarray (0) and its count (1). + sumIndex.set(0, 1); + + // Iterate through the elements of the 'nums' array. + for (let i = 0; i < nums.length; i++) { + // Add the current element to the cumulative sum. + currentSum += nums[i]; + // Calculate the value to find in the map by subtracting 'k' from the current cumulative sum. + const toFind = currentSum - k; + + // Check if the map contains the value 'toFind'. + if (sumIndex.has(toFind)) { + // If found, add the count of subarrays that sum to 'toFind' to the 'result'. + result += sumIndex.get(toFind); + } + + // Update the map with the current cumulative sum. + // If it's already in the map, increment its count by 1. + // If it's not in the map, add it with a count of 1. + sumIndex.set(currentSum, (sumIndex.get(currentSum) || 0) + 1); + } + + // Return the final result, which represents the total number of subarrays with a sum of 'k'. + return result; +} From 479c95a2ccf181e8f8cf34e10ca7fbee10254844 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Nov 2023 23:02:03 +0530 Subject: [PATCH 1869/1894] add subarray product less than k --- .../subarray_product_less_than_k.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Sliding Window/subarray_product_less_than_k.java diff --git a/Sliding Window/subarray_product_less_than_k.java b/Sliding Window/subarray_product_less_than_k.java new file mode 100644 index 00000000..e9cecaee --- /dev/null +++ b/Sliding Window/subarray_product_less_than_k.java @@ -0,0 +1,20 @@ +/** + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + */ +class Solution { + public int numSubarrayProductLessThanK(int[] nums, int k) { + int startWindow = 0, product = 1, count = 0; + + for(int endWindow = 0; endWindow < nums.length; endWindow++) { + product *= nums[endWindow]; + while(startWindow <= endWindow && product >= k) { + product /= nums[startWindow]; + startWindow++; + } + count += endWindow - startWindow + 1; + } + return count; + } +} \ No newline at end of file From d3a9cbee1dfd995a2ec233ddc5e5ec3579a35b62 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Nov 2023 23:02:43 +0530 Subject: [PATCH 1870/1894] add comments --- .../subarray_product_less_than_k.java | 21 +++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/Sliding Window/subarray_product_less_than_k.java b/Sliding Window/subarray_product_less_than_k.java index e9cecaee..6352b204 100644 --- a/Sliding Window/subarray_product_less_than_k.java +++ b/Sliding Window/subarray_product_less_than_k.java @@ -5,16 +5,29 @@ */ class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { - int startWindow = 0, product = 1, count = 0; + // Initialize pointers and a count variable + int startWindow = 0; // The left end of the sliding window + int product = 1; // Initialize product to 1 to accumulate the product + int count = 0; // Count of subarrays with a product less than k - for(int endWindow = 0; endWindow < nums.length; endWindow++) { + // Iterate through the array using a sliding window approach + for (int endWindow = 0; endWindow < nums.length; endWindow++) { + // Multiply the current element to the product product *= nums[endWindow]; - while(startWindow <= endWindow && product >= k) { + + // Shrink the window by moving the start pointer as long as the product is greater than or equal to k + while (startWindow <= endWindow && product >= k) { + // Divide the product by the element at the start of the window product /= nums[startWindow]; + // Move the start of the window to the right startWindow++; } + + // Update the count with the number of valid subarrays within the current window count += endWindow - startWindow + 1; } + + // Return the count, which represents the number of subarrays with a product less than k return count; } -} \ No newline at end of file +} From 70d8b55a524f8a7666601805abf1cf8f7bdbfd88 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 6 Nov 2023 23:03:26 +0530 Subject: [PATCH 1871/1894] add time and space complexity --- .../subarray_product_less_than_k.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/Sliding Window/subarray_product_less_than_k.java b/Sliding Window/subarray_product_less_than_k.java index 6352b204..6edd74fe 100644 --- a/Sliding Window/subarray_product_less_than_k.java +++ b/Sliding Window/subarray_product_less_than_k.java @@ -1,7 +1,20 @@ /** - Given an array of integers nums and an integer k, - return the number of contiguous subarrays where the product of all the elements in the subarray is - strictly less than k. + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window + approach to efficiently compute this count. + + Time Complexity: + + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. + Space Complexity: + + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. */ class Solution { public int numSubarrayProductLessThanK(int[] nums, int k) { From 62b7c11a00f53f18e3b93d631575d1a05f6a10ba Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Nov 2023 23:18:34 +0530 Subject: [PATCH 1872/1894] add longest repeated character replacement in java --- ...longest_repeated_character_replacement.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Sliding Window/longest_repeated_character_replacement.java diff --git a/Sliding Window/longest_repeated_character_replacement.java b/Sliding Window/longest_repeated_character_replacement.java new file mode 100644 index 00000000..efd484da --- /dev/null +++ b/Sliding Window/longest_repeated_character_replacement.java @@ -0,0 +1,18 @@ +class Solution { + public int characterReplacement(String s, int k) { + int[] count = new int[26]; + int startWindow = 0, maxCount = 0, max = 0; + for(int endWindow = 0; endWindow < s.length(); endWindow++) { + int val = s.charAt(endWindow) - 'A'; + count[val]++; + maxCount = Math.max(maxCount, count[val]); + while(endWindow - startWindow + 1 - maxCount > k) { + val = s.charAt(startWindow) - 'A'; + count[val]--; + startWindow++; + } + max = Math.max(max, endWindow - startWindow + 1); + } + return max; + } +} \ No newline at end of file From 725f59d11cf2c5f1bc0a22d3e1d7ed6292751c55 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 7 Nov 2023 23:20:15 +0530 Subject: [PATCH 1873/1894] add comments --- ...ongest_repeated_character_replacement.java | 62 ++++++++++++++++--- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/Sliding Window/longest_repeated_character_replacement.java b/Sliding Window/longest_repeated_character_replacement.java index efd484da..51defebd 100644 --- a/Sliding Window/longest_repeated_character_replacement.java +++ b/Sliding Window/longest_repeated_character_replacement.java @@ -1,18 +1,60 @@ +/* + You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + + Return the length of the longest substring containing the same letter you can get after performing the above operations. + + Example 1: + + Input: s = "ABAB", k = 2 + Output: 4 + Explanation: Replace the two 'A's with two 'B's or vice versa. + + Summary: + The provided code defines a Java class `Solution` with a method `characterReplacement` that aims to find the + longest substring within the input string `s` such that it can be created by replacing at most `k` characters + with any other character. It uses a sliding window approach to efficiently compute the maximum length of such a + substring. + + Time Complexity: + - The code iterates through the input string `s` using a sliding window with two pointers + (startWindow and endWindow). During each iteration, it updates character counts and evaluates the + maximum length of a valid substring. Since each character is processed exactly once, the time complexity + is O(N), where N is the length of the input string `s`. + + Space Complexity: + - The code uses additional space to store integer variables (`count`, `startWindow`, `maxCount`, and `max`). + The `count` array has a fixed size of 26 (for 26 English alphabet letters). Therefore, the space complexity is + O(1), as the space used is constant and does not depend on the input size. + + In summary, the algorithm has a time complexity of O(N) and a space complexity of O(1), making it efficient + for finding the longest substring with at most 'k' replacements in a given string. + */ class Solution { public int characterReplacement(String s, int k) { + // Initialize an array to count the occurrences of characters (26 letters in the English alphabet) int[] count = new int[26]; - int startWindow = 0, maxCount = 0, max = 0; - for(int endWindow = 0; endWindow < s.length(); endWindow++) { - int val = s.charAt(endWindow) - 'A'; - count[val]++; - maxCount = Math.max(maxCount, count[val]); - while(endWindow - startWindow + 1 - maxCount > k) { - val = s.charAt(startWindow) - 'A'; - count[val]--; - startWindow++; + int startWindow = 0; // The left end of the sliding window + int maxCount = 0; // The maximum count of any character within the window + int max = 0; // The maximum length of a substring that can be formed + + // Iterate through the string using a sliding window approach + for (int endWindow = 0; endWindow < s.length(); endWindow++) { + int val = s.charAt(endWindow) - 'A'; // Convert the character to an index (0-25) + count[val]++; // Increment the count for the current character + maxCount = Math.max(maxCount, count[val]); // Update the maximum character count + + // While the length of the current window minus the maximum character count exceeds 'k', shrink the window + while (endWindow - startWindow + 1 - maxCount > k) { + val = s.charAt(startWindow) - 'A'; // Get the character at the start of the window + count[val]--; // Decrement the count for the character at the start of the window + startWindow++; // Move the start of the window to the right } + + // Update the maximum length of a substring that can be formed max = Math.max(max, endWindow - startWindow + 1); } + + // Return the maximum length, which represents the longest substring with at most 'k' replacements return max; } -} \ No newline at end of file +} From 113e70619a9c2e831a8ea417422237d9582f7706 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 8 Nov 2023 23:16:10 +0530 Subject: [PATCH 1874/1894] add subarray sum less than k in go --- .../subarray_product_less_than_k.go | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Sliding Window/subarray_product_less_than_k.go diff --git a/Sliding Window/subarray_product_less_than_k.go b/Sliding Window/subarray_product_less_than_k.go new file mode 100644 index 00000000..a3c9cab7 --- /dev/null +++ b/Sliding Window/subarray_product_less_than_k.go @@ -0,0 +1,44 @@ +/** + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window + approach to efficiently compute this count. + + Time Complexity: + + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. + Space Complexity: + + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. +*/ + + func numSubarrayProductLessThanK(nums []int, k int) int { + startWindow := 0 // The left end of the sliding window + product := 1 // Initialize product to 1 to accumulate the product + count := 0 // Count of subarrays with a product less than k + + // Iterate through the array using a sliding window approach + for endWindow := 0; endWindow < len(nums); endWindow++ { + // Multiply the current element to the product + product *= nums[endWindow] + + // Shrink the window by moving the start pointer as long as the product is greater than or equal to k + for startWindow <= endWindow && product >= k { + // Divide the product by the element at the start of the window + product /= nums[startWindow] + // Move the start of the window to the right + startWindow++ + } + + // Update the count with the number of valid subarrays within the current window + count += endWindow - startWindow + 1 + } + + // Return the count, which represents the number of subarrays with a product less than k + return count +} From 07ecc187470a4f832ad43625eb515780751ec179 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Nov 2023 23:20:53 +0530 Subject: [PATCH 1875/1894] add max eraser value in java --- Sliding Window/max_eraser_value.java | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sliding Window/max_eraser_value.java diff --git a/Sliding Window/max_eraser_value.java b/Sliding Window/max_eraser_value.java new file mode 100644 index 00000000..544bf472 --- /dev/null +++ b/Sliding Window/max_eraser_value.java @@ -0,0 +1,38 @@ +/* +You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. + +Return the maximum score you can get by erasing exactly one subarray. + +An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). + + + +Example 1: + +Input: nums = [4,2,4,5,6] +Output: 17 +Explanation: The optimal subarray here is [2,4,5,6]. +Example 2: + +Input: nums = [5,2,1,2,5,2,1,2,5] +Output: 8 +Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. + +*/ +class Solution { + public int maximumUniqueSubarray(int[] nums) { + int startWindow = 0, windowSum = 0, res = 0; + HashMap mp = new HashMap<>(); + for(int endWindow = 0; endWindow < nums.length; endWindow++) { + while(mp.containsKey(nums[endWindow])) { + mp.remove(nums[startWindow]); + windowSum -= nums[startWindow]; + startWindow++; + } + mp.put(nums[endWindow], 1); + windowSum += nums[endWindow]; + res = Math.max(res, windowSum); + } + return res; + } +} \ No newline at end of file From 4d89e1d5520184f12210138187d3e88f0cd03e7c Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Nov 2023 23:21:32 +0530 Subject: [PATCH 1876/1894] add comments --- Sliding Window/max_eraser_value.java | 29 +++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/Sliding Window/max_eraser_value.java b/Sliding Window/max_eraser_value.java index 544bf472..1be661b1 100644 --- a/Sliding Window/max_eraser_value.java +++ b/Sliding Window/max_eraser_value.java @@ -21,18 +21,33 @@ */ class Solution { public int maximumUniqueSubarray(int[] nums) { - int startWindow = 0, windowSum = 0, res = 0; + // Initialize pointers, windowSum, and result + int startWindow = 0; // The left end of the sliding window + int windowSum = 0; // Sum of elements within the current window + int res = 0; // Result, which represents the maximum unique subarray sum + + // HashMap to store the last index where each element was seen HashMap mp = new HashMap<>(); - for(int endWindow = 0; endWindow < nums.length; endWindow++) { - while(mp.containsKey(nums[endWindow])) { - mp.remove(nums[startWindow]); - windowSum -= nums[startWindow]; - startWindow++; + + // Iterate through the array using a sliding window approach + for (int endWindow = 0; endWindow < nums.length; endWindow++) { + // Check if the current element is already in the window + while (mp.containsKey(nums[endWindow])) { + // Remove the element at the start of the window from the HashMap and update windowSum + mp.remove(nums[startWindow]); + windowSum -= nums[startWindow]; + startWindow++; } + + // Add the current element to the HashMap and update windowSum mp.put(nums[endWindow], 1); windowSum += nums[endWindow]; + + // Update the result with the maximum unique subarray sum res = Math.max(res, windowSum); } + + // Return the result, which represents the maximum unique subarray sum return res; } -} \ No newline at end of file +} From 120476fdf311c9c0bf1b530a343b0065a5c6f8e8 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 9 Nov 2023 23:22:02 +0530 Subject: [PATCH 1877/1894] add explanation --- Sliding Window/max_eraser_value.java | 46 ++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/Sliding Window/max_eraser_value.java b/Sliding Window/max_eraser_value.java index 1be661b1..9f9744a0 100644 --- a/Sliding Window/max_eraser_value.java +++ b/Sliding Window/max_eraser_value.java @@ -1,22 +1,44 @@ /* -You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. + You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. -Return the maximum score you can get by erasing exactly one subarray. + Return the maximum score you can get by erasing exactly one subarray. -An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). + An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). - + -Example 1: + Example 1: -Input: nums = [4,2,4,5,6] -Output: 17 -Explanation: The optimal subarray here is [2,4,5,6]. -Example 2: + Input: nums = [4,2,4,5,6] + Output: 17 + Explanation: The optimal subarray here is [2,4,5,6]. + Example 2: -Input: nums = [5,2,1,2,5,2,1,2,5] -Output: 8 -Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. + Input: nums = [5,2,1,2,5,2,1,2,5] + Output: 8 + Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. + + Explanation: + + startWindow: The left end of the sliding window. + windowSum: Sum of elements within the current window. + res: Result, initialized to 0, representing the maximum unique subarray sum. + mp: HashMap to store the last index where each element was seen. + Sliding Window: + + Use a for loop to iterate through the array with the endWindow as the right end of the window. + Check if the current element is already in the window using a while loop. + If yes, remove the element at the start of the window from the HashMap and update windowSum and startWindow. + Update HashMap and windowSum: + + Add the current element to the HashMap and update windowSum. + Update Result: + + Update the result (res) with the maximum unique subarray sum. + Return Result: + + Return the final result, which represents the maximum unique subarray sum. + This code efficiently finds the maximum sum of a subarray where all elements are unique using a sliding window and a HashMap to keep track of the last index of each element encountered. */ class Solution { From 83484bb8d0eb06fce5d128bdb6fa4be2530c47d0 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Nov 2023 21:57:57 +0530 Subject: [PATCH 1878/1894] add numSubarrayProductLessThanK in cpp --- .../subarray_product_less_than_k.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Sliding Window/subarray_product_less_than_k.cpp diff --git a/Sliding Window/subarray_product_less_than_k.cpp b/Sliding Window/subarray_product_less_than_k.cpp new file mode 100644 index 00000000..6855d9d9 --- /dev/null +++ b/Sliding Window/subarray_product_less_than_k.cpp @@ -0,0 +1,49 @@ +/** + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window + approach to efficiently compute this count. + + Time Complexity: + + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. + Space Complexity: + + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. + */ + +#include + +class Solution { +public: + int numSubarrayProductLessThanK(std::vector& nums, int k) { + int startWindow = 0; // The left end of the sliding window + int product = 1; // Initialize product to 1 to accumulate the product + int count = 0; // Count of subarrays with a product less than k + + // Iterate through the array using a sliding window approach + for (int endWindow = 0; endWindow < nums.size(); endWindow++) { + // Multiply the current element to the product + product *= nums[endWindow]; + + // Shrink the window by moving the start pointer as long as the product is greater than or equal to k + while (startWindow <= endWindow && product >= k) { + // Divide the product by the element at the start of the window + product /= nums[startWindow]; + // Move the start of the window to the right + startWindow++; + } + + // Update the count with the number of valid subarrays within the current window + count += endWindow - startWindow + 1; + } + + // Return the count, which represents the number of subarrays with a product less than k + return count; + } +}; From c80079dd77c236f8175bc7d426ae355435ccfb86 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 10 Nov 2023 21:58:48 +0530 Subject: [PATCH 1879/1894] add numSubarrayProductLessThanK in python --- .../subarray_product_less_than_k.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Sliding Window/subarray_product_less_than_k.py diff --git a/Sliding Window/subarray_product_less_than_k.py b/Sliding Window/subarray_product_less_than_k.py new file mode 100644 index 00000000..e4821ca3 --- /dev/null +++ b/Sliding Window/subarray_product_less_than_k.py @@ -0,0 +1,43 @@ +''' + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window + approach to efficiently compute this count. + + Time Complexity: + + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. + Space Complexity: + + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. +''' +from typing import List + +class Solution: + def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: + startWindow = 0 # The left end of the sliding window + product = 1 # Initialize product to 1 to accumulate the product + count = 0 # Count of subarrays with a product less than k + + # Iterate through the list using a sliding window approach + for endWindow in range(len(nums)): + # Multiply the current element to the product + product *= nums[endWindow] + + # Shrink the window by moving the start pointer as long as the product is greater than or equal to k + while startWindow <= endWindow and product >= k: + # Divide the product by the element at the start of the window + product /= nums[startWindow] + # Move the start of the window to the right + startWindow += 1 + + # Update the count with the number of valid subarrays within the current window + count += endWindow - startWindow + 1 + + # Return the count, which represents the number of subarrays with a product less than k + return count From 8dba7e240b088d01ec9432c2a434db5dff5b7e4a Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 11 Nov 2023 19:04:37 +0530 Subject: [PATCH 1880/1894] add longest_repeated_character_replacement in go --- .../longest_repeated_character_replacement.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Sliding Window/longest_repeated_character_replacement.go diff --git a/Sliding Window/longest_repeated_character_replacement.go b/Sliding Window/longest_repeated_character_replacement.go new file mode 100644 index 00000000..a3a438de --- /dev/null +++ b/Sliding Window/longest_repeated_character_replacement.go @@ -0,0 +1,64 @@ +/* + You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + + Return the length of the longest substring containing the same letter you can get after performing the above operations. + + Example 1: + + Input: s = "ABAB", k = 2 + Output: 4 + Explanation: Replace the two 'A's with two 'B's or vice versa. + + Summary: + The provided code defines a Java class `Solution` with a method `characterReplacement` that aims to find the + longest substring within the input string `s` such that it can be created by replacing at most `k` characters + with any other character. It uses a sliding window approach to efficiently compute the maximum length of such a + substring. + + Time Complexity: + - The code iterates through the input string `s` using a sliding window with two pointers + (startWindow and endWindow). During each iteration, it updates character counts and evaluates the + maximum length of a valid substring. Since each character is processed exactly once, the time complexity + is O(N), where N is the length of the input string `s`. + + Space Complexity: + - The code uses additional space to store integer variables (`count`, `startWindow`, `maxCount`, and `max`). + The `count` array has a fixed size of 26 (for 26 English alphabet letters). Therefore, the space complexity is + O(1), as the space used is constant and does not depend on the input size. + + In summary, the algorithm has a time complexity of O(N) and a space complexity of O(1), making it efficient + for finding the longest substring with at most 'k' replacements in a given string. + */ + func characterReplacement(s string, k int) int { + count := make([]int, 26) // Initialize an array to count the occurrences of characters (26 letters in the English alphabet) + startWindow := 0 // The left end of the sliding window + maxCount := 0 // The maximum count of any character within the window + max := 0 // The maximum length of a substring that can be formed + + // Iterate through the string using a sliding window approach + for endWindow := 0; endWindow < len(s); endWindow++ { + val := int(s[endWindow] - 'A') // Convert the character to an index (0-25) + count[val]++ // Increment the count for the current character + maxCount = maxInt(maxCount, count[val]) // Update the maximum character count + + // While the length of the current window minus the maximum character count exceeds 'k', shrink the window + for endWindow - startWindow + 1 - maxCount > k { + val = int(s[startWindow] - 'A') // Get the character at the start of the window + count[val]-- // Decrement the count for the character at the start of the window + startWindow++ // Move the start of the window to the right + } + + // Update the maximum length of a substring that can be formed + max = maxInt(max, endWindow - startWindow + 1) + } + + // Return the maximum length, which represents the longest substring with at most 'k' replacements + return max +} + +func maxInt(a, b int) int { + if a > b { + return a + } + return b +} From 25a24d3256fd08e3ce00296213f027dbcaee2b70 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 12 Nov 2023 19:39:29 +0530 Subject: [PATCH 1881/1894] add longest repeated character replacement in c++ --- ...longest_repeated_character_replacement.cpp | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Sliding Window/longest_repeated_character_replacement.cpp diff --git a/Sliding Window/longest_repeated_character_replacement.cpp b/Sliding Window/longest_repeated_character_replacement.cpp new file mode 100644 index 00000000..784512a3 --- /dev/null +++ b/Sliding Window/longest_repeated_character_replacement.cpp @@ -0,0 +1,64 @@ +/* + You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + + Return the length of the longest substring containing the same letter you can get after performing the above operations. + + Example 1: + + Input: s = "ABAB", k = 2 + Output: 4 + Explanation: Replace the two 'A's with two 'B's or vice versa. + + Summary: + The provided code defines a Java class `Solution` with a method `characterReplacement` that aims to find the + longest substring within the input string `s` such that it can be created by replacing at most `k` characters + with any other character. It uses a sliding window approach to efficiently compute the maximum length of such a + substring. + + Time Complexity: + - The code iterates through the input string `s` using a sliding window with two pointers + (startWindow and endWindow). During each iteration, it updates character counts and evaluates the + maximum length of a valid substring. Since each character is processed exactly once, the time complexity + is O(N), where N is the length of the input string `s`. + + Space Complexity: + - The code uses additional space to store integer variables (`count`, `startWindow`, `maxCount`, and `max`). + The `count` array has a fixed size of 26 (for 26 English alphabet letters). Therefore, the space complexity is + O(1), as the space used is constant and does not depend on the input size. + + In summary, the algorithm has a time complexity of O(N) and a space complexity of O(1), making it efficient + for finding the longest substring with at most 'k' replacements in a given string. + */ +#include +#include +#include + +class Solution { +public: + int characterReplacement(std::string s, int k) { + std::vector count(26, 0); // Initialize an array to count the occurrences of characters (26 letters in the English alphabet) + int startWindow = 0; // The left end of the sliding window + int maxCount = 0; // The maximum count of any character within the window + int max = 0; // The maximum length of a substring that can be formed + + // Iterate through the string using a sliding window approach + for (int endWindow = 0; endWindow < s.length(); endWindow++) { + int val = s[endWindow] - 'A'; // Convert the character to an index (0-25) + count[val]++; // Increment the count for the current character + maxCount = std::max(maxCount, count[val]); // Update the maximum character count + + // While the length of the current window minus the maximum character count exceeds 'k', shrink the window + while (endWindow - startWindow + 1 - maxCount > k) { + val = s[startWindow] - 'A'; // Get the character at the start of the window + count[val]--; // Decrement the count for the character at the start of the window + startWindow++; // Move the start of the window to the right + } + + // Update the maximum length of a substring that can be formed + max = std::max(max, endWindow - startWindow + 1); + } + + // Return the maximum length, which represents the longest substring with at most 'k' replacements + return max; + } +}; From 11ab5c89db65be55448b56de6400699d45991bcd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 13 Nov 2023 16:46:55 +0530 Subject: [PATCH 1882/1894] add longest_repeated_character_replacement in python --- .../longest_repeated_character_replacement.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Sliding Window/longest_repeated_character_replacement.py diff --git a/Sliding Window/longest_repeated_character_replacement.py b/Sliding Window/longest_repeated_character_replacement.py new file mode 100644 index 00000000..82ae1559 --- /dev/null +++ b/Sliding Window/longest_repeated_character_replacement.py @@ -0,0 +1,55 @@ +''' + You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + + Return the length of the longest substring containing the same letter you can get after performing the above operations. + + Example 1: + + Input: s = "ABAB", k = 2 + Output: 4 + Explanation: Replace the two 'A's with two 'B's or vice versa. + + Summary: + The provided code defines a Java class `Solution` with a method `characterReplacement` that aims to find the + longest substring within the input string `s` such that it can be created by replacing at most `k` characters + with any other character. It uses a sliding window approach to efficiently compute the maximum length of such a + substring. + + Time Complexity: + - The code iterates through the input string `s` using a sliding window with two pointers + (startWindow and endWindow). During each iteration, it updates character counts and evaluates the + maximum length of a valid substring. Since each character is processed exactly once, the time complexity + is O(N), where N is the length of the input string `s`. + + Space Complexity: + - The code uses additional space to store integer variables (`count`, `startWindow`, `maxCount`, and `max`). + The `count` array has a fixed size of 26 (for 26 English alphabet letters). Therefore, the space complexity is + O(1), as the space used is constant and does not depend on the input size. + + In summary, the algorithm has a time complexity of O(N) and a space complexity of O(1), making it efficient + for finding the longest substring with at most 'k' replacements in a given string. +''' +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + count = [0] * 26 # Initialize a list to count the occurrences of characters (26 letters in the English alphabet) + startWindow = 0 # The left end of the sliding window + maxCount = 0 # The maximum count of any character within the window + max_length = 0 # The maximum length of a substring that can be formed + + # Iterate through the string using a sliding window approach + for endWindow in range(len(s)): + val = ord(s[endWindow]) - ord('A') # Convert the character to an index (0-25) + count[val] += 1 # Increment the count for the current character + maxCount = max(maxCount, count[val]) # Update the maximum character count + + # While the length of the current window minus the maximum character count exceeds 'k', shrink the window + while endWindow - startWindow + 1 - maxCount > k: + val = ord(s[startWindow]) - ord('A') # Get the character at the start of the window + count[val] -= 1 # Decrement the count for the character at the start of the window + startWindow += 1 # Move the start of the window to the right + + # Update the maximum length of a substring that can be formed + max_length = max(max_length, endWindow - startWindow + 1) + + # Return the maximum length, which represents the longest substring with at most 'k' replacements + return max_length From 37484b7bc7dfe6e05d777fba9b2f4fa798adc955 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 14 Nov 2023 15:19:01 +0530 Subject: [PATCH 1883/1894] add longest_repeated_character_replacement --- .../longest_repeated_character_replacement.js | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Sliding Window/longest_repeated_character_replacement.js diff --git a/Sliding Window/longest_repeated_character_replacement.js b/Sliding Window/longest_repeated_character_replacement.js new file mode 100644 index 00000000..5b239116 --- /dev/null +++ b/Sliding Window/longest_repeated_character_replacement.js @@ -0,0 +1,64 @@ +/* + You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. + + Return the length of the longest substring containing the same letter you can get after performing the above operations. + + Example 1: + + Input: s = "ABAB", k = 2 + Output: 4 + Explanation: Replace the two 'A's with two 'B's or vice versa. + + Summary: + The provided code defines a Java class `Solution` with a method `characterReplacement` that aims to find the + longest substring within the input string `s` such that it can be created by replacing at most `k` characters + with any other character. It uses a sliding window approach to efficiently compute the maximum length of such a + substring. + + Time Complexity: + - The code iterates through the input string `s` using a sliding window with two pointers + (startWindow and endWindow). During each iteration, it updates character counts and evaluates the + maximum length of a valid substring. Since each character is processed exactly once, the time complexity + is O(N), where N is the length of the input string `s`. + + Space Complexity: + - The code uses additional space to store integer variables (`count`, `startWindow`, `maxCount`, and `max`). + The `count` array has a fixed size of 26 (for 26 English alphabet letters). Therefore, the space complexity is + O(1), as the space used is constant and does not depend on the input size. + + In summary, the algorithm has a time complexity of O(N) and a space complexity of O(1), making it efficient + for finding the longest substring with at most 'k' replacements in a given string. +*/ +class Solution { + characterReplacement(s, k) { + const count = Array(26).fill(0); // Initialize an array to count the occurrences of characters (26 letters in the English alphabet) + let startWindow = 0; // The left end of the sliding window + let maxCount = 0; // The maximum count of any character within the window + let max_length = 0; // The maximum length of a substring that can be formed + + // Iterate through the string using a sliding window approach + for (let endWindow = 0; endWindow < s.length; endWindow++) { + const val = s.charCodeAt(endWindow) - "A".charCodeAt(0); // Convert the character to an index (0-25) + count[val]++; // Increment the count for the current character + maxCount = Math.max(maxCount, count[val]); // Update the maximum character count + + // While the length of the current window minus the maximum character count exceeds 'k', shrink the window + while (endWindow - startWindow + 1 - maxCount > k) { + const val = s.charCodeAt(startWindow) - "A".charCodeAt(0); // Get the character at the start of the window + count[val]--; // Decrement the count for the character at the start of the window + startWindow++; // Move the start of the window to the right + } + + // Update the maximum length of a substring that can be formed + max_length = Math.max(max_length, endWindow - startWindow + 1); + } + + // Return the maximum length, which represents the longest substring with at most 'k' replacements + return max_length; + } +} + +// Example usage +const solution = new Solution(); +const result = solution.characterReplacement("ABAB", 2); +console.log(result); // Output: 4 From 72cc6fee9356e2cc356f15505e33b4a8467c4fa1 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 15 Nov 2023 23:05:51 +0530 Subject: [PATCH 1884/1894] add subarray_product_less_than_k --- .../subarray_product_less_than_k,js | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Sliding Window/subarray_product_less_than_k,js diff --git a/Sliding Window/subarray_product_less_than_k,js b/Sliding Window/subarray_product_less_than_k,js new file mode 100644 index 00000000..de4b2474 --- /dev/null +++ b/Sliding Window/subarray_product_less_than_k,js @@ -0,0 +1,50 @@ +/** + Given an array of integers nums and an integer k, + return the number of contiguous subarrays where the product of all the elements in the subarray is + strictly less than k. + + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window + approach to efficiently compute this count. + + Time Complexity: + + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. + Space Complexity: + + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. + */ +class Solution { + numSubarrayProductLessThanK(nums, k) { + let startWindow = 0; // The left end of the sliding window + let product = 1; // Initialize product to 1 to accumulate the product + let count = 0; // Count of subarrays with a product less than k + + // Iterate through the array using a sliding window approach + for (let endWindow = 0; endWindow < nums.length; endWindow++) { + // Multiply the current element to the product + product *= nums[endWindow]; + + // Shrink the window by moving the start pointer as long as the product is greater than or equal to k + while (startWindow <= endWindow && product >= k) { + // Divide the product by the element at the start of the window + product /= nums[startWindow]; + // Move the start of the window to the right + startWindow++; + } + + // Update the count with the number of valid subarrays within the current window + count += endWindow - startWindow + 1; + } + + // Return the count, which represents the number of subarrays with a product less than k + return count; + } +} + +// Example usage +const solution = new Solution(); +const result = solution.numSubarrayProductLessThanK([10, 5, 2, 6], 100); +console.log(result); // Output: 8 From 61a8cbeb8648a3ae8934e9796d8aeb20f19ae899 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Thu, 16 Nov 2023 22:49:27 +0530 Subject: [PATCH 1885/1894] add max_eraser_value in go --- Sliding Window/max_eraser_value.go | 82 ++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Sliding Window/max_eraser_value.go diff --git a/Sliding Window/max_eraser_value.go b/Sliding Window/max_eraser_value.go new file mode 100644 index 00000000..fb964df2 --- /dev/null +++ b/Sliding Window/max_eraser_value.go @@ -0,0 +1,82 @@ +/* + You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. + + Return the maximum score you can get by erasing exactly one subarray. + + An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). + + + + Example 1: + + Input: nums = [4,2,4,5,6] + Output: 17 + Explanation: The optimal subarray here is [2,4,5,6]. + Example 2: + + Input: nums = [5,2,1,2,5,2,1,2,5] + Output: 8 + Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. + + Explanation: + + startWindow: The left end of the sliding window. + windowSum: Sum of elements within the current window. + res: Result, initialized to 0, representing the maximum unique subarray sum. + mp: HashMap to store the last index where each element was seen. + Sliding Window: + + Use a for loop to iterate through the array with the endWindow as the right end of the window. + Check if the current element is already in the window using a while loop. + If yes, remove the element at the start of the window from the HashMap and update windowSum and startWindow. + Update HashMap and windowSum: + + Add the current element to the HashMap and update windowSum. + Update Result: + + Update the result (res) with the maximum unique subarray sum. + Return Result: + + Return the final result, which represents the maximum unique subarray sum. + This code efficiently finds the maximum sum of a subarray where all elements are unique using a sliding window and a HashMap to keep track of the last index of each element encountered. + +*/ +package main + +import "fmt" + +func maximumUniqueSubarray(nums []int) int { + startWindow := 0 // The left end of the sliding window + windowSum := 0 // Sum of elements within the current window + res := 0 // Result, which represents the maximum unique subarray sum + mp := make(map[int]int) // Map to store the last index where each element was seen + + // Iterate through the array using a sliding window approach + for endWindow := 0; endWindow < len(nums); endWindow++ { + // Check if the current element is already in the window + for mp[nums[endWindow]] > 0 { + // Remove the element at the start of the window from the map and update windowSum + mp[nums[startWindow]]-- + windowSum -= nums[startWindow] + startWindow++ + } + + // Add the current element to the map and update windowSum + mp[nums[endWindow]]++ + windowSum += nums[endWindow] + + // Update the result with the maximum unique subarray sum + if windowSum > res { + res = windowSum + } + } + + // Return the result, which represents the maximum unique subarray sum + return res +} + +func main() { + nums := []int{4, 2, 4, 5, 6} + result := maximumUniqueSubarray(nums) + fmt.Println(result) // Output: 17 +} From 9f08f180ac30220c76d3c64469af2eb75ec790bd Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Nov 2023 18:01:03 +0530 Subject: [PATCH 1886/1894] add inorder traversal using stack --- Trees/Binary Trees/inorder_traversal.java | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Trees/Binary Trees/inorder_traversal.java diff --git a/Trees/Binary Trees/inorder_traversal.java b/Trees/Binary Trees/inorder_traversal.java new file mode 100644 index 00000000..ff89680c --- /dev/null +++ b/Trees/Binary Trees/inorder_traversal.java @@ -0,0 +1,37 @@ + +/** + * Given the root of a binary tree, return the inorder traversal of its nodes' values. + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +/** + + */ +class Solution { + public List inorderTraversal(TreeNode root) { + List li = new ArrayList<>(); + Stack s = new Stack<>(); + TreeNode curr = root; + while(curr != null || !s.isEmpty()) { + while(curr != null) { + s.push(curr); + curr = curr.left; + } + curr = s.pop(); + li.add(curr.val); + curr = curr.right; + } + return li; + } +} \ No newline at end of file From 347f2e7ae47676d42dac6683c7af0f6ad4ab8e58 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 17 Nov 2023 18:01:12 +0530 Subject: [PATCH 1887/1894] add comments --- Trees/Binary Trees/inorder_traversal.java | 40 ++++++++++++++++------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/Trees/Binary Trees/inorder_traversal.java b/Trees/Binary Trees/inorder_traversal.java index ff89680c..7269a032 100644 --- a/Trees/Binary Trees/inorder_traversal.java +++ b/Trees/Binary Trees/inorder_traversal.java @@ -20,18 +20,34 @@ */ class Solution { public List inorderTraversal(TreeNode root) { - List li = new ArrayList<>(); - Stack s = new Stack<>(); - TreeNode curr = root; - while(curr != null || !s.isEmpty()) { - while(curr != null) { - s.push(curr); - curr = curr.left; + // List to store the in-order traversal result + List result = new ArrayList<>(); + + // Stack to simulate the recursive call stack + Stack stack = new Stack<>(); + + // Current node starts from the root + TreeNode current = root; + + // Continue traversal until current node is null and stack is empty + while (current != null || !stack.isEmpty()) { + // Traverse all the way to the leftmost node, pushing each node onto the stack + while (current != null) { + stack.push(current); + current = current.left; } - curr = s.pop(); - li.add(curr.val); - curr = curr.right; + + // Pop the top node from the stack (current leftmost node) + current = stack.pop(); + + // Add the value of the current node to the result list + result.add(current.val); + + // Move to the right subtree of the current node + current = current.right; } - return li; + + // Return the final in-order traversal result + return result; } -} \ No newline at end of file +} From 458be01677a5edaf48d2a23143628e0f8845e28b Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 19 Nov 2023 23:32:59 +0530 Subject: [PATCH 1888/1894] update inorder traversal --- Trees/Binary Trees/inorder_traversal.cpp | 97 +++++++++++++++--------- 1 file changed, 63 insertions(+), 34 deletions(-) diff --git a/Trees/Binary Trees/inorder_traversal.cpp b/Trees/Binary Trees/inorder_traversal.cpp index 4d195fb3..1f303f0e 100644 --- a/Trees/Binary Trees/inorder_traversal.cpp +++ b/Trees/Binary Trees/inorder_traversal.cpp @@ -13,42 +13,71 @@ Input : 40 10 5 1 -1 -1 -1 -1 30 -1 28 15 -1 -1 20 -1 -1 Output : 1->5->10->40->30->15->28->20 */ -#include -using namespace std; -class Node{ - public: - int data; - Node* left; - Node* right; - - Node(int x){ - data = x; - left = NULL; - right = NULL; - } +#include +#include +#include + +// Definition for a binary tree node. +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; -Node* build_binary_tree(){ - int data; - cin >> data; - if(data == -1){ - return NULL; + +class Solution { +public: + std::vector inorderTraversal(TreeNode* root) { + // Vector to store the in-order traversal result + std::vector result; + + // Stack to simulate the recursive call stack + std::stack stack; + + // Current node starts from the root + TreeNode* current = root; + + // Continue traversal until the current node is null and the stack is empty + while (current != nullptr || !stack.empty()) { + // Traverse all the way to the leftmost node, pushing each node onto the stack + while (current != nullptr) { + stack.push(current); + current = current->left; + } + + // Pop the top node from the stack (current leftmost node) + current = stack.top(); + stack.pop(); + + // Add the value of the current node to the result vector + result.push_back(current->val); + + // Move to the right subtree of the current node + current = current->right; + } + + // Return the final in-order traversal result + return result; } - Node* root = new Node(data); - root->left = build_binary_tree(); - root->right = build_binary_tree(); - return root; -} -void print_binary_tree(Node* root){ - if(root == NULL){ - return; +}; + +// Example usage +int main() { + // Create a sample binary tree + TreeNode* root = new TreeNode(1); + root->right = new TreeNode(2); + root->right->left = new TreeNode(3); + + // Perform in-order traversal + Solution solution; + std::vector result = solution.inorderTraversal(root); + + // Print the result + for (int val : result) { + std::cout << val << " "; } - print_binary_tree(root->left); - cout << root->data << "->"; - print_binary_tree(root->right); -} -int main(){ - Node* root = build_binary_tree(); - print_binary_tree(root); - return 0; + + // Output: 1 3 2 + return 0; } From bd5793ac7e38817be9ff4d62243733daf778d7b5 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Mon, 20 Nov 2023 23:10:55 +0530 Subject: [PATCH 1889/1894] add inorder traversal in go js and python undefined --- Trees/Binary Trees/inorder_traversal.go | 46 +++++++++++++++++++++++++ Trees/Binary Trees/inorder_traversal.js | 43 +++++++++++++++++++++++ Trees/Binary Trees/inorder_traversal.py | 37 ++++++++++++++++++++ 3 files changed, 126 insertions(+) create mode 100644 Trees/Binary Trees/inorder_traversal.go create mode 100644 Trees/Binary Trees/inorder_traversal.js create mode 100644 Trees/Binary Trees/inorder_traversal.py diff --git a/Trees/Binary Trees/inorder_traversal.go b/Trees/Binary Trees/inorder_traversal.go new file mode 100644 index 00000000..564404c9 --- /dev/null +++ b/Trees/Binary Trees/inorder_traversal.go @@ -0,0 +1,46 @@ +package main + +import "fmt" + +// TreeNode definition +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func inorderTraversal(root *TreeNode) []int { + var result []int + var stack []*TreeNode + current := root + + for current != nil || len(stack) > 0 { + // Traverse all the way to the leftmost node, pushing each node onto the stack + for current != nil { + stack = append(stack, current) + current = current.Left + } + + // Pop the top node from the stack (current leftmost node) + current, stack = stack[len(stack)-1], stack[:len(stack)-1] + + // Add the value of the current node to the result slice + result = append(result, current.Val) + + // Move to the right subtree of the current node + current = current.Right + } + + return result +} + +func main() { + // Create a sample binary tree + root := &TreeNode{Val: 1, Right: &TreeNode{Val: 2, Left: &TreeNode{Val: 3}}} + + // Perform in-order traversal + result := inorderTraversal(root) + + // Print the result + fmt.Println(result) // Output: [1 3 2] +} diff --git a/Trees/Binary Trees/inorder_traversal.js b/Trees/Binary Trees/inorder_traversal.js new file mode 100644 index 00000000..2ebc4f1e --- /dev/null +++ b/Trees/Binary Trees/inorder_traversal.js @@ -0,0 +1,43 @@ +class TreeNode { + constructor(val) { + this.val = val; + this.left = this.right = null; + } +} + +class Solution { + inorderTraversal(root) { + const result = []; + const stack = []; + let current = root; + + while (current || stack.length > 0) { + // Traverse all the way to the leftmost node, pushing each node onto the stack + while (current) { + stack.push(current); + current = current.left; + } + + // Pop the top node from the stack (current leftmost node) + current = stack.pop(); + + // Add the value of the current node to the result array + result.push(current.val); + + // Move to the right subtree of the current node + current = current.right; + } + + return result; + } +} + +// Example usage +const root = new TreeNode(1); +root.right = new TreeNode(2); +root.right.left = new TreeNode(3); + +const solution = new Solution(); +const result = solution.inorderTraversal(root); + +console.log(result); // Output: [1, 3, 2] diff --git a/Trees/Binary Trees/inorder_traversal.py b/Trees/Binary Trees/inorder_traversal.py new file mode 100644 index 00000000..acd1982c --- /dev/null +++ b/Trees/Binary Trees/inorder_traversal.py @@ -0,0 +1,37 @@ +class TreeNode: + def __init__(self, val): + self.val = val + self.left = self.right = None + +class Solution: + def inorderTraversal(self, root): + result = [] + stack = [] + current = root + + while current or stack: + # Traverse all the way to the leftmost node, pushing each node onto the stack + while current: + stack.append(current) + current = current.left + + # Pop the top node from the stack (current leftmost node) + current = stack.pop() + + # Add the value of the current node to the result list + result.append(current.val) + + # Move to the right subtree of the current node + current = current.right + + return result + +# Example usage +root = TreeNode(1) +root.right = TreeNode(2) +root.right.left = TreeNode(3) + +solution = Solution() +result = solution.inorderTraversal(root) + +print(result) # Output: [1, 3, 2] From 160f613868bb833f8fc4b713bdbe533f6a6ef773 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Tue, 21 Nov 2023 23:48:54 +0530 Subject: [PATCH 1890/1894] add issymmetric in java undefined --- Trees/Binary Trees/is_symmetric.java | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Trees/Binary Trees/is_symmetric.java diff --git a/Trees/Binary Trees/is_symmetric.java b/Trees/Binary Trees/is_symmetric.java new file mode 100644 index 00000000..1aac1f27 --- /dev/null +++ b/Trees/Binary Trees/is_symmetric.java @@ -0,0 +1,44 @@ +/* + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical + if the left and right subtrees are mirror images of each other. +*/ +import java.util.Stack; + +public class BinaryTree { + // Assume that BinaryTree has properties: left, right, and value. + + public boolean isSymmetricalTreeIterative(BinaryTree tree) { + Stack stackLeft = new Stack<>(); + Stack stackRight = new Stack<>(); + + // Initialize stackLeft with the left child of the root node + // Initialize stackRight with the right child of the root node + stackLeft.push(tree.getLeft()); + stackRight.push(tree.getRight()); + + // Perform mirror traversal of the left and right subtrees + while (!stackLeft.isEmpty()) { + BinaryTree left = stackLeft.pop(); + BinaryTree right = stackRight.pop(); + + if (left == null && right == null) { + continue; // Both left and right subtrees are symmetric, continue to the next iteration + } + + if (left == null || right == null || left.getValue() != right.getValue()) { + return false; // Asymmetry detected, tree is not symmetric + } + + // Push the children of left and right onto the respective stacks in reverse order + stackLeft.push(left.getLeft()); + stackLeft.push(left.getRight()); + + stackRight.push(right.getRight()); + stackRight.push(right.getLeft()); + } + + return true; // Tree is symmetric + } + + // Other methods and properties for BinaryTree class +} From a93b3f274424dd02b072baab61d9c896355c6296 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Wed, 22 Nov 2023 23:43:51 +0530 Subject: [PATCH 1891/1894] add issymmetric in js and py --- Trees/Binary Trees/is_symmetric.js | 50 ++++++++++++++++++++++++++++++ Trees/Binary Trees/is_symmetric.py | 36 +++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 Trees/Binary Trees/is_symmetric.js create mode 100644 Trees/Binary Trees/is_symmetric.py diff --git a/Trees/Binary Trees/is_symmetric.js b/Trees/Binary Trees/is_symmetric.js new file mode 100644 index 00000000..f275a07b --- /dev/null +++ b/Trees/Binary Trees/is_symmetric.js @@ -0,0 +1,50 @@ +/* + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical + if the left and right subtrees are mirror images of each other. +*/ +class BinaryTree { + constructor(value, left = null, right = null) { + this.value = value; + this.left = left; + this.right = right; + } +} + +function isSymmetricalTreeIterative(tree) { + const stackLeft = (tree && [tree.left]) || []; // Initialize stackLeft with the left child of the root node + const stackRight = (tree && [tree.right]) || []; // Initialize stackRight with the right child of the root node + + // Perform mirror traversal of the left and right subtrees + while (stackLeft.length > 0) { + const left = stackLeft.pop() || null; // Pop the top node from stackLeft + const right = stackRight.pop() || null; // Pop the top node from stackRight + + if (!left && !right) { + continue; // Both left and right subtrees are symmetric, continue to the next iteration + } + + if (!left || !right || left.value !== right.value) { + return false; // Asymmetry detected, tree is not symmetric + } + + // Push the children of left and right onto the respective stacks in reverse order + if (left) { + stackLeft.push(left.left, left.right); + } + if (right) { + stackRight.push(right.right, right.left); + } + } + + return true; // Tree is symmetric +} + +// Example usage: +// Construct a symmetric tree +const symmetricTree = new BinaryTree( + 1, + new BinaryTree(2, new BinaryTree(3), new BinaryTree(4)), + new BinaryTree(2, new BinaryTree(4), new BinaryTree(3)) +); + +console.log(isSymmetricalTreeIterative(symmetricTree)); // Output: true diff --git a/Trees/Binary Trees/is_symmetric.py b/Trees/Binary Trees/is_symmetric.py new file mode 100644 index 00000000..8870f998 --- /dev/null +++ b/Trees/Binary Trees/is_symmetric.py @@ -0,0 +1,36 @@ +''' + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical + if the left and right subtrees are mirror images of each other. +''' +class BinaryTree: + def __init__(self, value, left=None, right=None): + self.value = value + self.left = left + self.right = right + +def is_symmetrical_tree_iterative(tree): + stack_left = [tree.left] if tree else [] # Initialize stackLeft with the left child of the root node + stack_right = [tree.right] if tree else [] # Initialize stackRight with the right child of the root node + + # Perform mirror traversal of the left and right subtrees + while stack_left: + left = stack_left.pop() if stack_left else None + right = stack_right.pop() if stack_right else None + + if not left and not right: + continue # Both left and right subtrees are symmetric, continue to the next iteration + + if not left or not right or left.value != right.value: + return False # Asymmetry detected, tree is not symmetric + + # Push the children of left and right onto the respective stacks in reverse order + stack_left.extend([left.left, left.right] if left else []) + stack_right.extend([right.right, right.left] if right else []) + + return True # Tree is symmetric + +# Example usage: +# Construct a symmetric tree +symmetric_tree = BinaryTree(1, BinaryTree(2, BinaryTree(3), BinaryTree(4)), BinaryTree(2, BinaryTree(4), BinaryTree(3))) + +print(is_symmetrical_tree_iterative(symmetric_tree)) # Output: True From 525ed333c959cba3f9e2b6487570f817315dac09 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Fri, 24 Nov 2023 23:47:54 +0530 Subject: [PATCH 1892/1894] add invert tree in cpp and py --- Trees/Binary Trees/invert.cpp | 52 +++++++++++++++++++++++++++++++++++ Trees/Binary Trees/invert.py | 33 ++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 Trees/Binary Trees/invert.cpp create mode 100644 Trees/Binary Trees/invert.py diff --git a/Trees/Binary Trees/invert.cpp b/Trees/Binary Trees/invert.cpp new file mode 100644 index 00000000..abc22ee3 --- /dev/null +++ b/Trees/Binary Trees/invert.cpp @@ -0,0 +1,52 @@ +// Invert Binary tree +#include + +class BinaryTreeNode { +public: + int data; + BinaryTreeNode* left; + BinaryTreeNode* right; + + BinaryTreeNode(int val) : data(val), left(nullptr), right(nullptr) {} +}; + +BinaryTreeNode* invertTree(BinaryTreeNode* root) { + if (root != nullptr) { + root->left = invertTree(root->right); + root->right = invertTree(root->left); + } + return root; +} + +BinaryTreeNode* invertTree2(BinaryTreeNode* root) { + if (root != nullptr) { + // swap the pointers in this node + BinaryTreeNode* temp = root->left; + root->left = root->right; + root->right = temp; + + invertTree2(root->left); + invertTree2(root->right); + } + return root; +} + +int main() { + // Example usage: + // Construct a binary tree + BinaryTreeNode* root = new BinaryTreeNode(1); + root->left = new BinaryTreeNode(2); + root->right = new BinaryTreeNode(3); + root->left->left = new BinaryTreeNode(4); + root->left->right = new BinaryTreeNode(5); + + // Invert the binary tree using the first approach + BinaryTreeNode* invertedRoot = invertTree(root); + + // Invert the binary tree using the second approach + BinaryTreeNode* invertedRoot2 = invertTree2(root); + + // Additional code for printing or further usage... + + return 0; +} diff --git a/Trees/Binary Trees/invert.py b/Trees/Binary Trees/invert.py new file mode 100644 index 00000000..1d2201d2 --- /dev/null +++ b/Trees/Binary Trees/invert.py @@ -0,0 +1,33 @@ +# Invert Binary tree +class BinaryTreeNode: + def __init__(self, data): + self.left = None + self.data = data + self.right = None + +def invert_tree(root): + if root: + root.left, root.right = invert_tree(root.right), invert_tree(root.left) + return root + +def invert_tree2(root): + if root is not None: + # swap the pointers in this node + root.left, root.right = root.right, root.left + invert_tree2(root.left) + invert_tree2(root.right) + return root + +# Example usage: +# Assuming you have a binary tree +root = BinaryTreeNode(1) +root.left = BinaryTreeNode(2) +root.right = BinaryTreeNode(3) +root.left.left = BinaryTreeNode(4) +root.left.right = BinaryTreeNode(5) + +# Invert the binary tree using the first approach +inverted_root = invert_tree(root) + +# Invert the binary tree using the second approach +inverted_root2 = invert_tree2(root) From 7bb127285ebad263d91b7be504621ecfecfccbf6 Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sat, 25 Nov 2023 23:01:43 +0530 Subject: [PATCH 1893/1894] add bt invert in java and js --- Trees/Binary Trees/invert.java | 61 ++++++++++++++++++++++++++++++++++ Trees/Binary Trees/invert.js | 61 ++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 Trees/Binary Trees/invert.java create mode 100644 Trees/Binary Trees/invert.js diff --git a/Trees/Binary Trees/invert.java b/Trees/Binary Trees/invert.java new file mode 100644 index 00000000..6a01db3b --- /dev/null +++ b/Trees/Binary Trees/invert.java @@ -0,0 +1,61 @@ +class BinaryTreeNode { + int data; + BinaryTreeNode left, right; + + public BinaryTreeNode(int data) { + this.data = data; + this.left = this.right = null; + } +} + +public class BinaryTreeInverter { + // Time Complexity: O(n). Space Complexity: O(n). + // Approach: The inverse of an empty tree is an empty tree + // The inverse of a tree with root r, and subtrees right and left is a tree with + // root, whose right subtree is the inverse of left and whose left subtree + // is the inverse of right + public BinaryTreeNode invertTree(BinaryTreeNode root) { + if (root != null) { + root.left = invertTree(root.right); + root.right = invertTree(root.left); + } + return root; + } + + // Time Complexity: O(n). Space Complexity: O(1). + // Method2: swap pointers + public BinaryTreeNode invertTree2(BinaryTreeNode root) { + if (root != null) { + // swap the pointers in this node + BinaryTreeNode temp = root.left; + root.left = root.right; + root.right = temp; + + invertTree2(root.left); + invertTree2(root.right); + } + return root; + } + + // Additional methods or code as needed... + + public static void main(String[] args) { + // Example usage: + // Construct a binary tree + BinaryTreeNode root = new BinaryTreeNode(1); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(3); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(5); + + BinaryTreeInverter inverter = new BinaryTreeInverter(); + + // Invert the binary tree using the first approach + BinaryTreeNode invertedRoot = inverter.invertTree(root); + + // Invert the binary tree using the second approach + BinaryTreeNode invertedRoot2 = inverter.invertTree2(root); + + // Additional code for printing or further usage... + } +} diff --git a/Trees/Binary Trees/invert.js b/Trees/Binary Trees/invert.js new file mode 100644 index 00000000..a4bf6822 --- /dev/null +++ b/Trees/Binary Trees/invert.js @@ -0,0 +1,61 @@ +class BinaryTreeNode { + constructor(data) { + this.data = data; + this.left = this.right = null; + } +} + +class BinaryTreeInverter { + // Time Complexity: O(n). Space Complexity: O(n). + // Approach: The inverse of an empty tree is an empty tree + // The inverse of a tree with root r, and subtrees right and left is a tree with + // root, whose right subtree is the inverse of left and whoose left subtree + // is the inverse of right + invertTree(root) { + if (root !== null) { + root.left = this.invertTree(root.right); + root.right = this.invertTree(root.left); + } + return root; + } + + // Time Complexity: O(n). Space Complexity: O(1). + // Method2: swap pointers + invertTree2(root) { + if (root !== null) { + // swap the pointers in this node + let temp = root.left; + root.left = root.right; + root.right = temp; + + this.invertTree2(root.left); + this.invertTree2(root.right); + } + return root; + } + + // Additional methods or code as needed... + + // Example usage: + static main() { + // Construct a binary tree + let root = new BinaryTreeNode(1); + root.left = new BinaryTreeNode(2); + root.right = new BinaryTreeNode(3); + root.left.left = new BinaryTreeNode(4); + root.left.right = new BinaryTreeNode(5); + + let inverter = new BinaryTreeInverter(); + + // Invert the binary tree using the first approach + let invertedRoot = inverter.invertTree(root); + + // Invert the binary tree using the second approach + let invertedRoot2 = inverter.invertTree2(root); + + // Additional code for printing or further usage... + } +} + +// Example usage: +BinaryTreeInverter.main(); From 8d4daa487d5eaa1824e63bb18c5da6913eeb49eb Mon Sep 17 00:00:00 2001 From: Abhisek Kumar Gupta Date: Sun, 14 Jan 2024 23:03:41 +0530 Subject: [PATCH 1894/1894] add graphbfs in java --- Graphs/GraphBFS.java | 63 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Graphs/GraphBFS.java diff --git a/Graphs/GraphBFS.java b/Graphs/GraphBFS.java new file mode 100644 index 00000000..e9f921b7 --- /dev/null +++ b/Graphs/GraphBFS.java @@ -0,0 +1,63 @@ +/** + * The GraphBFS class represents a simple undirected graph using an adjacency list + * and provides a breadth-first search (BFS) algorithm to traverse the graph. + */ +import java.util.*; +import java.io.*; + +class GraphBFS { + private int V; // Number of vertices in the graph + private List adjacency[]; // Adjacency list to represent the graph + + // Constructor to initialize the graph with the given number of vertices + GraphBFS(int v) { + V = v; + adjacency = new ArrayList[V]; + for(int i = 0; i < V; i++) { + adjacency[i] = new ArrayList(); + } + } + + // Method to add an edge between vertices 'u' and 'v' in the graph + void addEdge(int u, int v) { + adjacency[u].add(v); + adjacency[v].add(u); + } + + /** + * Performs breadth-first search (BFS) starting from the given source vertex 's'. + * Prints the vertices in BFS order. + * @param s The source vertex from which BFS starts. + */ + void bfs(int s) { + boolean[] visited = new boolean[V]; // Array to track visited vertices + visited[s] = true; // Mark the source vertex as visited + LinkedList Q = new LinkedList(); // Queue for BFS traversal + Q.add(s); // Enqueue the source vertex + + // BFS traversal + while(Q.size() != 0) { + int current = Q.poll(); // Dequeue the current vertex + System.out.print(current + " -> "); // Print the current vertex + + // Visit all neighbors of the current vertex + for(int neighbour: adjacency[current]) { + if(!visited[neighbour]) { + visited[neighbour] = true; // Mark the neighbour as visited + Q.add(neighbour); // Enqueue the neighbour for further exploration + } + } + } + } + + // Main method for testing the GraphBFS class + public static void main(String[] args) { + GraphBFS g = new GraphBFS(5); // Create a graph with 5 vertices + g.addEdge(2, 3); // Add edges to the graph + g.addEdge(2, 4); + g.addEdge(3, 1); + g.addEdge(4, 1); + + g.bfs(2); // Perform BFS starting from vertex 2 + } +}