diff --git a/courses/recommend.md b/courses/recommend.md index 89507aee8..d164b2e0a 100644 --- a/courses/recommend.md +++ b/courses/recommend.md @@ -12,4 +12,4 @@ hide_table_of_contents: true import courses from '@site/src/database/courses'; - \ No newline at end of file + diff --git a/dsa-solutions/gfg-solutions/Easy problems/Lucky-Numbers.md b/dsa-solutions/gfg-solutions/Easy problems/Lucky-Numbers.md index 308e60aad..764158264 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/Lucky-Numbers.md +++ b/dsa-solutions/gfg-solutions/Easy problems/Lucky-Numbers.md @@ -1,195 +1,191 @@ ---- -id: lucky-number -title: Nth Fibonacci Number -sidebar_label: Nth Fibonacci Number -tags: - - Easy - - Dynamic Programming - - Math -description: "This tutorial covers the solution to the Nth Fibonacci Number problem from the GeeksforGeeks." ---- -## Problem Description - -Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers, -Take the set of integers -`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`,…… -First, delete every second number, we get following reduced set. -`1`, `3`, `5`, `7`, `9`, `11`, `13`, `15`, `17`, `19`,………… -Now, delete every third number, we get -`1`, `3`, `7`, `9`, `13`, `15`, `19`,….…. -Continue this process indefinitely…… -Any number that does NOT get deleted due to above process is called “lucky”. - -You are given a number N, you need to tell whether the number is lucky or not. If the number is lucky return 1 otherwise 0. - -## Examples - -**Example 1:** - -``` -Input: -N = 5 -Output: 0 -Explanation: 5 is not a lucky number -as it gets deleted in the second -iteration. -``` - -**Example 2:** - -``` -Input: -N = 19 -Output: 1 -Explanation: 19 is a lucky number because -it does not get deleted throughout the process. -``` - -## Your Task - -You don't need to read input or print anything. You only need to complete the function isLucky() that takes N as parameter and returns either False if the N is not lucky else True. - -Expected Time Complexity: $O(sqrt(n))$ - -Expected Auxiliary Space: $O(1)$ for iterative approach. - -## Constraints - -* `1 ≤ n ≤ 10^5` - -## Problem Explanation - -Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers, -Take the set of integers -`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`,…… -First, delete every second number, we get following reduced set. -`1`, `3`, `5`, `7`, `9`, `11`, `13`, `15`, `17`, `19`,………… -Now, delete every third number, we get -`1`, `3`, `7`, `9`, `13`, `15`, `19`,….…. -Continue this process indefinitely…… -Any number that does NOT get deleted due to above process is called “lucky”. - -You are given a number N, you need to tell whether the number is lucky or not. If the number is lucky return 1 otherwise 0. - -## Code Implementation - - - - - - ```py - def is_lucky(N): - lucky_numbers = list(range(1, N + 1)) - delete_step = 2 - while delete_step <= len(lucky_numbers): - lucky_numbers = [num for i, num in enumerate(lucky_numbers) if (i + 1) % delete_step != 0] - delete_step += 1 - return 1 if N in lucky_numbers else 0 - - ``` - - - - - - ```cpp - int isLucky(int N) { - vector luckyNumbers; - for (int i = 1; i <= N; i++) { - luckyNumbers.push_back(i); - } - int deleteStep = 2; - while (deleteStep <= luckyNumbers.size()) { - for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { - luckyNumbers.erase(luckyNumbers.begin() + i); - } - deleteStep++; - } - for (int num : luckyNumbers) { - if (num == N) { - return 1; - } - } - return 0; -} - - ``` - - - - - - - ```javascript -function isLucky(N) { - let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); - let deleteStep = 2; - while (deleteStep <= luckyNumbers.length) { - luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); - deleteStep++; - } - return luckyNumbers.includes(N) ? 1 : 0; -} - - - ``` - - - - - - - ```typescript -function isLucky(N) { - let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); - let deleteStep = 2; - while (deleteStep <= luckyNumbers.length) { - luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); - deleteStep++; - } - return luckyNumbers.includes(N) ? 1 : 0; -} - - - ``` - - - - - - - ```java -public int isLucky(int N) { - List luckyNumbers = new ArrayList<>(); - for (int i = 1; i <= N; i++) { - luckyNumbers.add(i); - } - int deleteStep = 2; - while (deleteStep <= luckyNumbers.size()) { - for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { - luckyNumbers.remove(i); - } - deleteStep++; - } - for (int num : luckyNumbers) { - if (num == N) { - return 1; - } - } - return 0; -} - - - ``` - - - - - -## Time Complexity - -* The iterative approach has a time complexity of $O(n^2)$. - -## Space Complexity - -* The space complexity is $O(n)$ since we are using only a fixed amount of extra space. \ No newline at end of file +--- +id: lucky-number +title: Nth Fibonacci Number +sidebar_label: Nth Fibonacci Number +tags: + - Easy + - Dynamic Programming + - Math +description: "This tutorial covers the solution to the Nth Fibonacci Number problem from the GeeksforGeeks." +--- + +## Problem Description + +Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers, +Take the set of integers +`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`,…… +First, delete every second number, we get following reduced set. +`1`, `3`, `5`, `7`, `9`, `11`, `13`, `15`, `17`, `19`,………… +Now, delete every third number, we get +`1`, `3`, `7`, `9`, `13`, `15`, `19`,….…. +Continue this process indefinitely…… +Any number that does NOT get deleted due to above process is called “lucky”. + +You are given a number N, you need to tell whether the number is lucky or not. If the number is lucky return 1 otherwise 0. + +## Examples + +**Example 1:** + +``` +Input: +N = 5 +Output: 0 +Explanation: 5 is not a lucky number +as it gets deleted in the second +iteration. +``` + +**Example 2:** + +``` +Input: +N = 19 +Output: 1 +Explanation: 19 is a lucky number because +it does not get deleted throughout the process. +``` + +## Your Task + +You don't need to read input or print anything. You only need to complete the function isLucky() that takes N as parameter and returns either False if the N is not lucky else True. + +Expected Time Complexity: $O(sqrt(n))$ + +Expected Auxiliary Space: $O(1)$ for iterative approach. + +## Constraints + +- `1 ≤ n ≤ 10^5` + +## Problem Explanation + +Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers, +Take the set of integers +`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`, `13`, `14`, `15`, `16`, `17`, `18`, `19`,…… +First, delete every second number, we get following reduced set. +`1`, `3`, `5`, `7`, `9`, `11`, `13`, `15`, `17`, `19`,………… +Now, delete every third number, we get +`1`, `3`, `7`, `9`, `13`, `15`, `19`,….…. +Continue this process indefinitely…… +Any number that does NOT get deleted due to above process is called “lucky”. + +You are given a number N, you need to tell whether the number is lucky or not. If the number is lucky return 1 otherwise 0. + +## Code Implementation + + + + + +```py +def is_lucky(N): + lucky_numbers = list(range(1, N + 1)) + delete_step = 2 + while delete_step <= len(lucky_numbers): + lucky_numbers = [num for i, num in enumerate(lucky_numbers) if (i + 1) % delete_step != 0] + delete_step += 1 + return 1 if N in lucky_numbers else 0 + +``` + + + + + +```cpp +int isLucky(int N) { + vector luckyNumbers; + for (int i = 1; i <= N; i++) { + luckyNumbers.push_back(i); + } + int deleteStep = 2; + while (deleteStep <= luckyNumbers.size()) { + for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { + luckyNumbers.erase(luckyNumbers.begin() + i); + } + deleteStep++; + } + for (int num : luckyNumbers) { + if (num == N) { + return 1; + } + } + return 0; +} + +``` + + + + + + +```javascript +function isLucky(N) { + let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); + let deleteStep = 2; + while (deleteStep <= luckyNumbers.length) { + luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); + deleteStep++; + } + return luckyNumbers.includes(N) ? 1 : 0; +} +``` + + + + + + +```typescript +function isLucky(N) { + let luckyNumbers = Array.from({ length: N }, (_, i) => i + 1); + let deleteStep = 2; + while (deleteStep <= luckyNumbers.length) { + luckyNumbers = luckyNumbers.filter((_, i) => (i + 1) % deleteStep !== 0); + deleteStep++; + } + return luckyNumbers.includes(N) ? 1 : 0; +} +``` + + + + + + +```java +public int isLucky(int N) { + List luckyNumbers = new ArrayList<>(); + for (int i = 1; i <= N; i++) { + luckyNumbers.add(i); + } + int deleteStep = 2; + while (deleteStep <= luckyNumbers.size()) { + for (int i = deleteStep - 1; i < luckyNumbers.size(); i += deleteStep) { + luckyNumbers.remove(i); + } + deleteStep++; + } + for (int num : luckyNumbers) { + if (num == N) { + return 1; + } + } + return 0; +} + + +``` + + + + +## Time Complexity + +- The iterative approach has a time complexity of $O(n^2)$. + +## Space Complexity + +- The space complexity is $O(n)$ since we are using only a fixed amount of extra space. diff --git a/dsa-solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md b/dsa-solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md index 07b45c15d..c425ea8f7 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md +++ b/dsa-solutions/gfg-solutions/Easy problems/determine-if-two-trees-are-identical.md @@ -1,7 +1,7 @@ --- -id: determine-if-two-trees-are-identical -title: Determine if Two Trees are Identical (gfg) -sidebar_label: 0012 - Determine if Two Trees are Identical +id: determine-if-two-trees-are-identical +title: Determine if Two Trees are Identical (gfg) +sidebar_label: 0012 - Determine if Two Trees are Identical tags: - Easy - Tree @@ -9,9 +9,10 @@ tags: - GeeksforGeeks - CPP - Python - - DSA + - DSA description: "This tutorial covers the solution to the Determine if Two Trees are Identical problem from the GeeksforGeeks website, featuring implementations in Python and C++." --- + ## Problem Description Given two binary trees, the task is to find if both of them are identical or not. Note: You need to return true or false, the printing is done by the driver code. @@ -60,8 +61,8 @@ Expected Auxiliary Space: $O(H)$, where H is the height of the trees. ## Constraints -* `1 ≤ Number of nodes ≤ 10^5` -* `1 ≤ Data of a node ≤ 10^5` +- `1 ≤ Number of nodes ≤ 10^5` +- `1 ≤ Data of a node ≤ 10^5` ## Problem Explanation @@ -73,125 +74,125 @@ Two trees are considered identical if they have the same structure and their cor - ```py - # Definition for a binary tree node. - class TreeNode: - def __init__(self, val=0, left=None, right=None): - self.val = val - self.left = left - self.right = right - - class Solution: - def isIdentical(self, r1: TreeNode, r2: TreeNode) -> bool: - if not r1 and not r2: - return True - if not r1 or not r2: - return False - return (r1.val == r2.val) and self.isIdentical(r1.left, r2.left) and self.isIdentical(r1.right, r2.right) - - # Example usage - if __name__ == "__main__": - root1 = TreeNode(1) - root1.left = TreeNode(2) - root1.right = TreeNode(3) - - root2 = TreeNode(1) - root2.left = TreeNode(2) - root2.right = TreeNode(3) - - solution = Solution() - print(solution.isIdentical(root1, root2)) # Expected output: True - ``` +```py +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def isIdentical(self, r1: TreeNode, r2: TreeNode) -> bool: + if not r1 and not r2: + return True + if not r1 or not r2: + return False + return (r1.val == r2.val) and self.isIdentical(r1.left, r2.left) and self.isIdentical(r1.right, r2.right) + +# Example usage +if __name__ == "__main__": + root1 = TreeNode(1) + root1.left = TreeNode(2) + root1.right = TreeNode(3) + + root2 = TreeNode(1) + root2.left = TreeNode(2) + root2.right = TreeNode(3) + + solution = Solution() + print(solution.isIdentical(root1, root2)) # Expected output: True +``` - ```cpp - //{ Driver Code Starts - #include - using namespace std; - - struct Node { - int data; - Node* left; - Node* right; - - Node(int val) { - data = val; - left = right = NULL; - } - }; - - // } Driver Code Ends - class Solution { - public: - // Function to check if two trees are identical. - bool isIdentical(Node* r1, Node* r2) { - if (!r1 && !r2) return true; - if (!r1 || !r2) return false; - return (r1->data == r2->data) && isIdentical(r1->left, r2->left) && isIdentical(r1->right, r2->right); - } - }; - - //{ Driver Code Starts. - // Function to Build Tree - Node* buildTree(string str) { - if (str.length() == 0 || str[0] == 'N') return NULL; - - vector ip; - istringstream iss(str); - for (string str; iss >> str;) ip.push_back(str); - - Node* root = new Node(stoi(ip[0])); - queue queue; - queue.push(root); - - int i = 1; - while (!queue.empty() && i < ip.size()) { - Node* currNode = queue.front(); - queue.pop(); - - string currVal = ip[i]; - if (currVal != "N") { - currNode->left = new Node(stoi(currVal)); - queue.push(currNode->left); - } - - i++; - if (i >= ip.size()) break; - currVal = ip[i]; - - if (currVal != "N") { - currNode->right = new Node(stoi(currVal)); - queue.push(currNode->right); - } - i++; - } - - return root; - } - - int main() { - int tc; - scanf("%d ", &tc); - while (tc--) { - string str, str1; - getline(cin, str); - Node* rootA = buildTree(str); - getline(cin, str1); - Node* rootB = buildTree(str1); - Solution ob; - if (ob.isIdentical(rootA, rootB)) { - cout << "Yes\n"; - } else { - cout << "No\n"; - } - } - return 0; - } - // } Driver Code Ends - ``` +```cpp +//{ Driver Code Starts +#include +using namespace std; + +struct Node { + int data; + Node* left; + Node* right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +// } Driver Code Ends +class Solution { +public: + // Function to check if two trees are identical. + bool isIdentical(Node* r1, Node* r2) { + if (!r1 && !r2) return true; + if (!r1 || !r2) return false; + return (r1->data == r2->data) && isIdentical(r1->left, r2->left) && isIdentical(r1->right, r2->right); + } +}; + +//{ Driver Code Starts. +// Function to Build Tree +Node* buildTree(string str) { + if (str.length() == 0 || str[0] == 'N') return NULL; + + vector ip; + istringstream iss(str); + for (string str; iss >> str;) ip.push_back(str); + + Node* root = new Node(stoi(ip[0])); + queue queue; + queue.push(root); + + int i = 1; + while (!queue.empty() && i < ip.size()) { + Node* currNode = queue.front(); + queue.pop(); + + string currVal = ip[i]; + if (currVal != "N") { + currNode->left = new Node(stoi(currVal)); + queue.push(currNode->left); + } + + i++; + if (i >= ip.size()) break; + currVal = ip[i]; + + if (currVal != "N") { + currNode->right = new Node(stoi(currVal)); + queue.push(currNode->right); + } + i++; + } + + return root; +} + +int main() { + int tc; + scanf("%d ", &tc); + while (tc--) { + string str, str1; + getline(cin, str); + Node* rootA = buildTree(str); + getline(cin, str1); + Node* rootB = buildTree(str1); + Solution ob; + if (ob.isIdentical(rootA, rootB)) { + cout << "Yes\n"; + } else { + cout << "No\n"; + } + } + return 0; +} +// } Driver Code Ends +``` @@ -245,11 +246,11 @@ For the trees: ## Time Complexity -* The function visits each node once, so the time complexity is $O(N)$. +- The function visits each node once, so the time complexity is $O(N)$. ## Space Complexity -* The auxiliary space complexity is $O(H)$ due to the recursion stack, where H is the height of the tree. +- The auxiliary space complexity is $O(H)$ due to the recursion stack, where H is the height of the tree. ## References diff --git a/dsa-solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md b/dsa-solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md index a7fdab99d..989f52177 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md +++ b/dsa-solutions/gfg-solutions/Easy problems/find-duplicates-in-an-array.md @@ -17,8 +17,9 @@ description: "This tutorial covers the solution to the Find Duplicates in an Arr Given an array `arr` of size `n` which contains elements in the range from 0 to `n-1`, you need to find all the elements occurring more than once in the given array. Return the answer in ascending order. If no such element is found, return a list containing [-1]. :::note - Try and perform all operations within the provided array. The extra (non-constant) space needs to be used only for the array to be returned. +Try and perform all operations within the provided array. The extra (non-constant) space needs to be used only for the array to be returned. ::: + ## Examples **Example 1:** @@ -47,8 +48,8 @@ Expected Auxiliary Space: $O(1)$ (excluding the space for the output list) ## Constraints -* `1 ≤ n ≤ 10^5` -* `0 ≤ arr[i] ≤ n-1` +- `1 ≤ n ≤ 10^5` +- `0 ≤ arr[i] ≤ n-1` ## Problem Explanation @@ -60,89 +61,89 @@ The problem is to find the duplicate elements in an array of size `n`, where the - ```py - class Solution: - def duplicates(self, arr): - n = len(arr) - # Use the array elements as index - for i in range(n): - arr[arr[i] % n] += n +```py +class Solution: + def duplicates(self, arr): + n = len(arr) + # Use the array elements as index + for i in range(n): + arr[arr[i] % n] += n - # Collect elements that occur more than once - result = [i for i in range(n) if arr[i] // n > 1] + # Collect elements that occur more than once + result = [i for i in range(n) if arr[i] // n > 1] - return result if result else [-1] + return result if result else [-1] - # Example usage - if __name__ == "__main__": - solution = Solution() - print(solution.duplicates([2, 3, 1, 2, 3])) # Expected output: [2, 3] - print(solution.duplicates([0, 1, 2, 3])) # Expected output: [-1] - ``` +# Example usage +if __name__ == "__main__": + solution = Solution() + print(solution.duplicates([2, 3, 1, 2, 3])) # Expected output: [2, 3] + print(solution.duplicates([0, 1, 2, 3])) # Expected output: [-1] +``` - ```cpp - #include - #include - #include - using namespace std; - - class Solution { - public: - vector duplicates(vector& arr) { - int n = arr.size(); - vector result; - - // Use the array elements as index - for (int i = 0; i < n; i++) { - arr[arr[i] % n] += n; - } - - // Collect elements that occur more than once - for (int i = 0; i < n; i++) { - if (arr[i] / n > 1) { - result.push_back(i); - } - } - - if (result.empty()) { - return {-1}; - } - - return result; - } - }; - - // Example usage - void solve() { - int n; - cin >> n; - vector arr(n); - for (int i = 0; i < n; i++) { - cin >> arr[i]; - } - - Solution obj; - vector ans = obj.duplicates(arr); - for (int i : ans) { - cout << i << ' '; - } - cout << endl; - } - - int main() { - int t; - cin >> t; - - while (t--) { - solve(); - } - return 0; - } - ``` +```cpp +#include +#include +#include +using namespace std; + +class Solution { +public: + vector duplicates(vector& arr) { + int n = arr.size(); + vector result; + + // Use the array elements as index + for (int i = 0; i < n; i++) { + arr[arr[i] % n] += n; + } + + // Collect elements that occur more than once + for (int i = 0; i < n; i++) { + if (arr[i] / n > 1) { + result.push_back(i); + } + } + + if (result.empty()) { + return {-1}; + } + + return result; + } +}; + +// Example usage +void solve() { + int n; + cin >> n; + vector arr(n); + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + Solution obj; + vector ans = obj.duplicates(arr); + for (int i : ans) { + cout << i << ' '; + } + cout << endl; +} + +int main() { + int t; + cin >> t; + + while (t--) { + solve(); + } + return 0; +} +``` @@ -170,11 +171,11 @@ For the array `arr = [0, 1, 2, 3]`: ## Time Complexity -* The time complexity is $O(n)$, where n is the size of the input array. +- The time complexity is $O(n)$, where n is the size of the input array. ## Space Complexity -* The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input array. +- The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input array. ## References diff --git a/dsa-solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md b/dsa-solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md index 28adf4025..301fa1c3a 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md +++ b/dsa-solutions/gfg-solutions/Easy problems/floor-in-a-sorted-array.md @@ -1,7 +1,7 @@ --- -id: floor-in-sorted-array -title: Floor in a Sorted Array Problem (gfg) -sidebar_label: 0013 - Floor in a Sorted Array +id: floor-in-sorted-array +title: Floor in a Sorted Array Problem (gfg) +sidebar_label: 0013 - Floor in a Sorted Array tags: - Easy - Array @@ -9,9 +9,10 @@ tags: - GeeksforGeeks - CPP - Python - - DSA + - DSA description: "This tutorial covers the solution to the Floor in a Sorted Array problem from the GeeksforGeeks website, featuring implementations in Python and C++." --- + ## Problem Description Given a sorted array `arr[]` of size `n` without duplicates, and given a value `x`. Floor of `x` is defined as the largest element `k` in `arr[]` such that `k` is smaller than or equal to `x`. Find the index of `k` (0-based indexing). @@ -21,7 +22,7 @@ Given a sorted array `arr[]` of size `n` without duplicates, and given a value ` **Example 1:** ``` -Input: +Input: arr = [1, 2, 8, 10, 11, 12, 19] x = 5 Output: 1 @@ -58,9 +59,9 @@ Expected Auxiliary Space: $O(1)$ ## Constraints -* `1 ≤ n ≤ 10^7` -* `1 ≤ arr[i] ≤ 10^18` -* `0 ≤ x ≤ 10^18` +- `1 ≤ n ≤ 10^7` +- `1 ≤ arr[i] ≤ 10^18` +- `0 ≤ x ≤ 10^18` ## Problem Explanation @@ -72,91 +73,91 @@ The floor of a number `x` in a sorted array is the largest element in the array - ```py - from typing import List - - class Solution: - def findFloor(self, arr: List[int], n: int, x: int) -> int: - low, high = 0, n - 1 - floor_index = -1 - - while low <= high: - mid = (low + high) // 2 - - if arr[mid] == x: - return mid - elif arr[mid] < x: - floor_index = mid - low = mid + 1 - else: - high = mid - 1 - - return floor_index - - # Example usage - if __name__ == "__main__": - solution = Solution() - arr = [1, 2, 8, 10, 11, 12, 19] - x = 5 - print(solution.findFloor(arr, len(arr), x)) # Expected output: 1 - ``` +```py +from typing import List + +class Solution: + def findFloor(self, arr: List[int], n: int, x: int) -> int: + low, high = 0, n - 1 + floor_index = -1 + + while low <= high: + mid = (low + high) // 2 + + if arr[mid] == x: + return mid + elif arr[mid] < x: + floor_index = mid + low = mid + 1 + else: + high = mid - 1 + + return floor_index + +# Example usage +if __name__ == "__main__": + solution = Solution() + arr = [1, 2, 8, 10, 11, 12, 19] + x = 5 + print(solution.findFloor(arr, len(arr), x)) # Expected output: 1 +``` - ```cpp - //{ Driver Code Starts - #include - using namespace std; - - class Solution{ - public: - int findFloor(vector v, long long n, long long x){ - int low = 0, high = n - 1; - int floor_index = -1; - - while (low <= high) { - int mid = low + (high - low) / 2; - - if (v[mid] == x) { - return mid; - } else if (v[mid] < x) { - floor_index = mid; - low = mid + 1; - } else { - high = mid - 1; - } - } - - return floor_index; - } - }; - - int main() { - long long t; - cin >> t; - - while(t--){ - long long n; - cin >> n; - long long x; - cin >> x; - - vector v(n); - - for(long long i = 0; i < n; i++){ - cin >> v[i]; - } - - Solution obj; - cout << obj.findFloor(v, n, x) << endl; - } - - return 0; - } - // } Driver Code Ends - ``` +```cpp +//{ Driver Code Starts +#include +using namespace std; + +class Solution{ +public: + int findFloor(vector v, long long n, long long x){ + int low = 0, high = n - 1; + int floor_index = -1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (v[mid] == x) { + return mid; + } else if (v[mid] < x) { + floor_index = mid; + low = mid + 1; + } else { + high = mid - 1; + } + } + + return floor_index; + } +}; + +int main() { + long long t; + cin >> t; + + while(t--){ + long long n; + cin >> n; + long long x; + cin >> x; + + vector v(n); + + for(long long i = 0; i < n; i++){ + cin >> v[i]; + } + + Solution obj; + cout << obj.findFloor(v, n, x) << endl; + } + + return 0; +} +// } Driver Code Ends +``` @@ -189,11 +190,11 @@ For `x = 0`: ## Time Complexity -* The time complexity of the binary search is $O(\log N)$. +- The time complexity of the binary search is $O(\log N)$. ## Space Complexity -* The auxiliary space complexity is $O(1)$. +- The auxiliary space complexity is $O(1)$. ## References diff --git a/dsa-solutions/gfg-solutions/Easy problems/square-root.md b/dsa-solutions/gfg-solutions/Easy problems/square-root.md index 640a3c101..c249e2811 100644 --- a/dsa-solutions/gfg-solutions/Easy problems/square-root.md +++ b/dsa-solutions/gfg-solutions/Easy problems/square-root.md @@ -3,8 +3,8 @@ id: square-root title: Square Root sidebar_label: Square-Root tags: -- Math -- Binary Search + - Math + - Binary Search description: "This document provides solutions to the problem of finding the Square Root of an integer." --- @@ -38,6 +38,7 @@ You don't need to read input or print anything. The task is to complete the func **Expected Auxiliary Space:** $O(1)$ **Constraints** + - `1 ≤ x ≤ 10^7` ## Solution @@ -128,25 +129,27 @@ public: ```javascript class Solution { - floorSqrt(x) { - if (x === 0 || x === 1) { - return x; - } - let start = 1, end = x, ans = 0; - while (start <= end) { - let mid = Math.floor((start + end) / 2); - if (mid * mid === x) { - return mid; - } - if (mid * mid < x) { - start = mid + 1; - ans = mid; - } else { - end = mid - 1; - } - } - return ans; + floorSqrt(x) { + if (x === 0 || x === 1) { + return x; + } + let start = 1, + end = x, + ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } } + return ans; + } } ``` @@ -155,25 +158,27 @@ class Solution { ```typescript class Solution { - floorSqrt(x: number): number { - if (x === 0 || x === 1) { - return x; - } - let start = 1, end = x, ans = 0; - while (start <= end) { - let mid = Math.floor((start + end) / 2); - if (mid * mid === x) { - return mid; - } - if (mid * mid < x) { - start = mid + 1; - ans = mid; - } else { - end = mid - 1; - } - } - return ans; + floorSqrt(x: number): number { + if (x === 0 || x === 1) { + return x; + } + let start = 1, + end = x, + ans = 0; + while (start <= end) { + let mid = Math.floor((start + end) / 2); + if (mid * mid === x) { + return mid; + } + if (mid * mid < x) { + start = mid + 1; + ans = mid; + } else { + end = mid - 1; + } } + return ans; + } } ``` @@ -185,4 +190,4 @@ class Solution { The provided solutions efficiently find the floor value of the square root of a given integer `x` using binary search. This approach ensures a time complexity of $ O(log N) and an auxiliary space complexity of $O(1)$. The algorithms are designed to handle large values of `x` up to 10^7 efficiently without relying on built-in square root functions. **Time Complexity:** $O(log N)$ -**Auxiliary Space:** $O(1)$ \ No newline at end of file +**Auxiliary Space:** $O(1)$ diff --git a/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-ii.md b/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-ii.md index e3b9a1324..bdd389ce2 100644 --- a/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-ii.md +++ b/dsa-solutions/lc-solutions/0200-0299/0240-search-a-2d-matrix-ii.md @@ -69,6 +69,7 @@ Output: false ### Intuition and Approach To search for a value in this matrix efficiently, we can utilize the properties of the matrix. Since the matrix is sorted both row-wise and column-wise, we can start our search from the top-right corner of the matrix. From here, we have two options: + 1. If the target is greater than the current value, move downwards. 2. If the target is less than the current value, move leftwards. @@ -76,7 +77,7 @@ This approach ensures that we eliminate one row or one column in each step, lead - + ### Approach: Greedy Search By leveraging the sorted properties of the matrix, we can search for the target value efficiently using a greedy approach. This involves starting from the top-right corner and adjusting our search direction based on the current value. @@ -108,7 +109,7 @@ const matrix = [ [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] + [18, 21, 23, 26, 30], ]; const target = 5; const result = searchMatrix(matrix, target); @@ -116,13 +117,8 @@ const result = searchMatrix(matrix, target); return (

- Input: matrix = [ - [1, 4, 7, 11, 15], - [2, 5, 8, 12, 19], - [3, 6, 9, 16, 22], - [10, 13, 14, 17, 24], - [18, 21, 23, 26, 30] - ], target = 5 + Input: matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, + 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ], target = 5

Output: {result ? "true" : "false"} @@ -182,7 +178,7 @@ return ( ``` - + ```python def searchMatrix(matrix: List[List[int]], target: int) -> bool: @@ -259,7 +255,7 @@ return ( }; ``` - + #### Complexity Analysis @@ -269,7 +265,8 @@ return ( - The time complexity is linear in terms of the dimensions of the matrix. Each step eliminates either a row or a - column, leading to a linear time complexity of $O(m + n)$. +column, leading to a linear time complexity of $O(m + n)$. + - The space complexity is constant because we only use a few extra variables regardless of the matrix size. @@ -287,8 +284,8 @@ This solution leverages the matrix's properties to reduce the search space effic - --- - +--- + @@ -306,7 +303,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> @@ -315,7 +312,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> @@ -328,7 +325,7 @@ This solution leverages the matrix's properties to reduce the search space effic params="autoplay=1&autohide=1&showinfo=0&rel=0" title="Search a 2D Matrix II Problem Explanation | Search a 2D Matrix II Solution" poster="maxresdefault" - webp + webp /> diff --git a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md index 4eacd7aa6..4278ec3fb 100644 --- a/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md +++ b/dsa-solutions/lc-solutions/0900-0999/0905-sort-array-by-parity.md @@ -2,15 +2,15 @@ id: Sort-Array-By-Parity title: Sort Array By Parity sidebar_label: Sort Array By Parity -tags: - - Arrays - - Sorting +tags: + - Arrays + - Sorting --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| Problem Statement | Solution Link | LeetCode Profile | +| :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/description/) | [Sort Array By Parity Solution on LeetCode](https://leetcode.com/problems/sort-array-by-parity/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | ## Problem Description @@ -21,13 +21,13 @@ Return any array that satisfies this condition. ### Example 1: -**Input:** `nums = [3, 1, 2, 4]` -**Output:** `[2, 4, 3, 1]` +**Input:** `nums = [3, 1, 2, 4]` +**Output:** `[2, 4, 3, 1]` **Explanation:** The outputs `[4, 2, 3, 1]`, `[2, 4, 1, 3]`, and `[4, 2, 1, 3]` would also be accepted. ### Example 2: -**Input:** `nums = [0]` +**Input:** `nums = [0]` **Output:** `[0]` ## Constraints @@ -64,7 +64,7 @@ public class EvenOddArray { public static int[] sortArrayByParity(int[] nums) { List even = new ArrayList<>(); List odd = new ArrayList<>(); - + for (int num : nums) { if (num % 2 == 0) { even.add(num); @@ -72,11 +72,11 @@ public class EvenOddArray { odd.add(num); } } - + even.addAll(odd); return even.stream().mapToInt(i -> i).toArray(); } - + public static void main(String[] args) { int[] nums = {3, 1, 2, 4}; System.out.println(Arrays.toString(sortArrayByParity(nums))); // Output: [2, 4, 3, 1] @@ -122,7 +122,7 @@ int main() { void sortArrayByParity(int* nums, int numsSize, int* returnSize) { int* result = (int*)malloc(numsSize * sizeof(int)); int evenIndex = 0, oddIndex = numsSize - 1; - + for (int i = 0; i < numsSize; ++i) { if (nums[i] % 2 == 0) { result[evenIndex++] = nums[i]; @@ -142,7 +142,7 @@ int main() { int numsSize = sizeof(nums) / sizeof(nums[0]); int returnSize; sortArrayByParity(nums, numsSize, &returnSize); - + for (int i = 0; i < numsSize; ++i) { printf("%d ", nums[i]); } @@ -155,23 +155,23 @@ int main() { ```javascript function sortArrayByParity(nums) { - let even = []; - let odd = []; - - for (let num of nums) { - if (num % 2 === 0) { - even.push(num); - } else { - odd.push(num); - } + let even = []; + let odd = []; + + for (let num of nums) { + if (num % 2 === 0) { + even.push(num); + } else { + odd.push(num); } - - return [...even, ...odd]; + } + + return [...even, ...odd]; } // Example usage let nums = [3, 1, 2, 4]; -console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] +console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] ``` ## Step-by-Step Algorithm @@ -185,4 +185,4 @@ console.log(sortArrayByParity(nums)); // Output: [2, 4, 3, 1] ## Conclusion -This problem can be solved efficiently by iterating through the array once and separating the integers into even and odd lists/arrays. The time complexity is O(n), where n is the length of the array, making this approach optimal for the given constraints. \ No newline at end of file +This problem can be solved efficiently by iterating through the array once and separating the integers into even and odd lists/arrays. The time complexity is O(n), where n is the length of the array, making this approach optimal for the given constraints. diff --git a/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md b/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md index b4c6801dc..bdc410957 100644 --- a/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md +++ b/dsa-solutions/lc-solutions/0900-0999/0906-super-palindromes.md @@ -2,15 +2,15 @@ id: super-palindromes title: Super Palindromes sidebar_label: Super Palindromes -tags: - - Palindrome - - Math +tags: + - Palindrome + - Math --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| Problem Statement | Solution Link | LeetCode Profile | +| :-------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- | :--------------------------------------------------- | | [Super Palindromes](https://leetcode.com/problems/super-palindromes/description/) | [Super Palindromes Solution on LeetCode](https://leetcode.com/problems/super-palindromes/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | ## Problem Description @@ -62,7 +62,7 @@ def super_palindromes(left, right): left, right = int(left), int(right) count = 0 limit = int(math.sqrt(right)) + 1 - + for i in range(1, limit): s = str(i) pal = s + s[::-1] @@ -71,14 +71,14 @@ def super_palindromes(left, right): break if num >= left and is_palindrome(str(num)): count += 1 - + pal = s + s[-2::-1] num = int(pal) ** 2 if num > right: break if num >= left and is_palindrome(str(num)): count += 1 - + return count ``` @@ -178,7 +178,7 @@ int superPalindromes(char* left, char* right) { for (long long i = 1; i < limit; i++) { sprintf(s, "%lld", i); int len = strlen(s); - + // Palindrome of even length snprintf(pal, 40, "%s%s", s, strrev(strdup(s))); long long num1 = atoll(pal) * atoll(pal); @@ -200,28 +200,29 @@ int superPalindromes(char* left, char* right) { ```javascript function isPalindrome(s) { - return s === s.split('').reverse().join(''); + return s === s.split("").reverse().join(""); } function superPalindromes(left, right) { - let l = BigInt(left), r = BigInt(right); - let count = 0; - let limit = BigInt(Math.sqrt(Number(r))) + BigInt(1); - - for (let i = BigInt(1); i < limit; i++) { - let s = i.toString(); - let pal1 = s + s.split('').reverse().join(''); - let num1 = BigInt(pal1) ** BigInt(2); - if (num1 > r) break; - if (num1 >= l && isPalindrome(num1.toString())) count++; - - let pal2 = s + s.slice(0, -1).split('').reverse().join(''); - let num2 = BigInt(pal2) ** BigInt(2); - if (num2 > r) break; - if (num2 >= l && isPalindrome(num2.toString())) count++; - } - - return count; + let l = BigInt(left), + r = BigInt(right); + let count = 0; + let limit = BigInt(Math.sqrt(Number(r))) + BigInt(1); + + for (let i = BigInt(1); i < limit; i++) { + let s = i.toString(); + let pal1 = s + s.split("").reverse().join(""); + let num1 = BigInt(pal1) ** BigInt(2); + if (num1 > r) break; + if (num1 >= l && isPalindrome(num1.toString())) count++; + + let pal2 = s + s.slice(0, -1).split("").reverse().join(""); + let num2 = BigInt(pal2) ** BigInt(2); + if (num2 > r) break; + if (num2 >= l && isPalindrome(num2.toString())) count++; + } + + return count; } ``` @@ -230,12 +231,13 @@ function superPalindromes(left, right) { 1. **Generate Palindromes:** - Iterate through possible values of `i` from 1 to the square root of the right boundary. - Construct palindromes by concatenating `s` with its reverse and with its reverse minus the last character. - 2. **Square Palindromes:** + - Compute the square of each palindrome. - Check if the squared value is within the range `[left, right]`. 3. **Check for Super-Palindromes:** + - Verify if the squared palindrome is also a palindrome. 4. **Count and Return:** diff --git a/src/data/courses/index.tsx b/src/data/courses/index.tsx index f25b7a8d5..a77af4f20 100644 --- a/src/data/courses/index.tsx +++ b/src/data/courses/index.tsx @@ -31,10 +31,10 @@ const courses = [ imageUrl: "/img/svg/static_assets.svg", author: "Ajay Dhangar", link: "/docs/category/javascript" - }, - + }, + // React for beginners - + { id: 5, title: "React for Beginners", @@ -46,7 +46,7 @@ const courses = [ }, // angular for beginners - + // { // id: 6, // title: "Angular for Beginners", @@ -351,6 +351,5 @@ const courses = [ "link": "https://www.figma.com/resources/learn-design/" }, ]; - + export default courses; - diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 02f16057c..66bd42804 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -137,7 +137,7 @@ export default function Home() {

- +