diff --git a/dsa-solutions/gfg-solutions/Basic/0001.md b/dsa-solutions/gfg-solutions/Basic/0001.md new file mode 100644 index 000000000..b8fc5bb5a --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0001.md @@ -0,0 +1,192 @@ +--- +id: binary-search +title: Binary Search +sidebar_label: 0001 Binary Search +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of performing Binary Search in a sorted array." +--- + +## Problem + +Given a sorted array of size N and an integer K, find the position(0-based indexing) at which K is present in the array using binary search. + +### Examples +**Example 1:** +``` +Input: +N = 5 +arr[] = {1 2 3 4 5} +K = 4 +Output: 3 +Explanation: 4 appears at index 3. +``` + +**Example 2:** +``` +Input: +N = 5 +arr[] = {11 22 33 44 55} +K = 445 +Output: -1 +Explanation: 445 is not present. +``` + +### Your Task: +You dont need to read input or print anything. Complete the function **binarysearch()** which takes **arr[]**, **N** and **K** as input parameters and returns the index of **K** in the array. If **K** is not present in the array, return -1. + +- **Expected Time Complexity:** $O(LogN)$ +- **Expected Auxiliary Space:** $O(LogN)$ if solving recursively and $O(1)$ otherwise. + +### Constraints: + +- $1 <= N <= 10^5$ +- $1 <= arr[i] <= 10^6$ +- $1 <= K <= 10^6$ + +## Solution: +### Iterative Approach: + +**Python** +```python +def binarysearch(self, arr, n, k): + low = 0 + high = n-1 + while low<=high: + mid = low + (high-low)//2 + if arr[mid]==k: + return mid + elif arr[mid]= arr[1]) : + return 0 + if (arr[n - 1] >= arr[n - 2]) : + return n - 1 + for i in range(1, n - 1) : + if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) : + return i +``` + +**Java** +```java +public int peakElement(int[] arr,int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } + return 0; +} +``` + +**C++** +```cpp +public: +int peakElement(int arr[], int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} +``` + +**C** +```c +int peakElement(int arr[], int n) { + if (n == 1) + return 0; + if (arr[0] >= arr[1]) + return 0; + if (arr[n - 1] >= arr[n - 2]) + return n - 1; + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) + return i; + } +} +``` + +- **Time complexity:** $O(n)$ +- **Space complexity:**: $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0003.md b/dsa-solutions/gfg-solutions/Basic/0003.md new file mode 100644 index 000000000..3642bc1ab --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0003.md @@ -0,0 +1,101 @@ +--- +id: power-of-2 +title: Power Of 2 +sidebar_label: 0003 Power Of 2 +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of checking whether a non-negative number is a power of 2." +--- + +## Problem + +Given a non-negative integer n. The task is to check if it is a power of 2. + +### Examples: +**Example 1:** +``` +Input: n = 8 +Output: true +Explanation: 8 is equal to 2 raised to 3 (2^3 = 8). +``` + +**Example 2:** +``` +Input: n = 98 +Output: false +Explanation: 98 cannot be obtained by any power of 2. +``` + +**Example 3:** +``` +Input: n = 1 +Output: true +Explanation: (2^0 = 1). +``` + +- **Expected Time Complexity:** $O(log n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: +$0 ≤ n < 10^{20}$ + +## Solution +**Python** +```python +def isPowerofTwo(self,n : int ) -> bool: + if (n == 0): + return False + while (n != 1): + if (n % 2 != 0): + return False + n = n // 2 + return True +``` + +**Java** +```java +public static boolean isPowerofTwo(long n) { + if (n == 0) + return false; + while (n != 1) { + if (n % 2 != 0) + return false; + n = n / 2; + } + return true; +} +``` + +**C** +```c +bool isPowerofTwo(long long n) { + if (n == 0) + return 0; + while (n != 1) { + if (n % 2 != 0) + return 0; + n = n / 2; + } + return 1; +} +``` + +**C++** +```cpp +bool isPowerofTwo(long long n) { + if (n == 0) + return 0; + while (n != 1) { + if (n % 2 != 0) + return 0; + n = n / 2; + } + return 1; +} +``` + +- **Time Complexity:** $O(log n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0004.md b/dsa-solutions/gfg-solutions/Basic/0004.md new file mode 100644 index 000000000..f9873f261 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0004.md @@ -0,0 +1,133 @@ +--- +id: union-of-two-arrays +title: Union Of Two Arrays +sidebar_label: 0004 Union Of Two Arrays +tags: +- Array +- Set +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of finding the number of elements in the union between two arrays." +--- + +## Problem + +Given two arrays **a[]** and **b[]** of size **n** and **m** respectively. The task is to find the number of elements in the union between these two arrays. + +Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union. + +**Note:** Elements are not necessarily distinct. + +### Examples: +**Example 1:** +``` +Input: +5 3 +1 2 3 4 5 +1 2 3 +Output: +5 +Explanation: +1, 2, 3, 4 and 5 are the +elements which comes in the union set +of both arrays. So count is 5. +``` + +**Example 2:** +``` +Input: +6 2 +85 25 1 32 54 6 +85 2 +Output: +7 +Explanation: +85, 25, 1, 32, 54, 6, and +2 are the elements which comes in the +union set of both arrays. So count is 7. +``` + +### Your Task: + +Complete **doUnion** function that takes **a, n, b, m as parameters and returns** the count of union elements of the two arrays. The **printing** is done by the **driver** code. + +- **Expected Time Complexity:** $O(n+m)$ +- **Expected Auxilliary Space:** $O(n+m)$ + + +### Constraints: + +- $1 ≤ n, m ≤ 10^5$ +- $0 ≤ a[i], b[i] < 10^5$ + +## Solution + +### Python +```python +def doUnion(self,a,n,b,m): + set1 = set(a) + set2 = set(b) + result = list(set1.union(set2)) + return len(result) +``` + +### Java +```java +public static int doUnion(int a[], int n, int b[], int m) { + TreeSet set = new TreeSet<>(); + for (int i : a) + set.add(i); + for (int i : b) + set.add(i); + ArrayList list = new ArrayList<>(); + for (int i : set) + list.add(i); + return list.size(); +} +``` + +### C++ +```cpp +int doUnion(int a[], int n, int b[], int m) { + set s; + for (int i = 0; i < n; i++) { + s.insert(a[i]); + } + for (int i = 0; i < m; i++) { + s.insert(b[i]); + } + vector vec(s.begin(), s.end()); + return vec.size(); +} +``` + +### C +```c +int doUnion(int a[], int n, int b[], int m) { + int *unionSet = (int *)malloc((n + m) * sizeof(int)); + int i, j; + int unionSize = 0; + for (i = 0; i < n; i++) { + unionSet[unionSize++] = a[i]; + } + for (i = 0; i < m; i++) { + int found = 0; + for (j = 0; j < unionSize; j++) { + if (b[i] == unionSet[j]) { + found = 1; + break; + } + } + if (!found) { + unionSet[unionSize++] = b[i]; + } + } + free(unionSet); + return unionSize; +} +``` + +- **Time Complexity:** $O(m*log(m) + n*log(n))$ +- **Auxiliary Space:** $O(m + n)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0005.md b/dsa-solutions/gfg-solutions/Basic/0005.md new file mode 100644 index 000000000..3657ccad1 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0005.md @@ -0,0 +1,97 @@ +--- +id: reverse-a-string +title: Reverse a String +sidebar_label: 0005 Reverse a String +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to the problem of reversing a string." +--- + +## Problem + +You are given a string s. You need to reverse the string. + +### Examples: +**Example 1:** +``` +Input: +s = Geeks +Output: skeeG +``` + +**Example 2:** +``` +Input: +s = for +Output: rof +``` + +### Your Task: + +You only need to complete the function **reverseWord()** that takes s as parameter and returns the reversed string. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +$1 <= |s| <= 10000$ + +## Solution +### Python +```python +def reverseWord(self, str: str) -> str: + str = str[::-1] + return str +``` + +### Java +```java +public static String reverseWord(String str) { + char ch; + String nstr = ""; + for (int i=0; i map = new HashMap<>(); + for (int i = 0; i < N; i++) { + long key = A[i]; + map.put(key, map.getOrDefault(key, 0) + 1); + } + for (int i = 0; i < N; i++) { + long key = B[i]; + if (!map.containsKey(key)) + return false; + if (map.get(key) == 0) + return false; + int count = map.get(key); + map.put(key, count - 1); + } + return true; +} +``` + +### C++ +```cpp +bool check(vector A, vector B, int N) { + if (A.size() != static_cast(N) || B.size() != static_cast(N)) + return false; + unordered_map map; + for (int i = 0; i < N; ++i) { + ll key = A[i]; + map[key]++; + } + for (int i = 0; i < N; ++i) { + ll key = B[i]; + if (map.find(key) == map.end()) + return false; + if (map[key] == 0) + return false; + map[key]--; + } + return true; +} +``` + +### C +```c +bool check(long long A[], long long B[], int N) { + long long *map = (long long *)calloc(1000001, sizeof(long long)); + for (int i = 0; i < N; ++i) { + long long key = A[i]; + map[key]++; + } + for (int i = 0; i < N; ++i) { + long long key = B[i]; + if (map[key] == 0) + return false; + map[key]--; + } + free(map); + return true; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxilliary Space:** $O(N)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0008.md b/dsa-solutions/gfg-solutions/Basic/0008.md new file mode 100644 index 000000000..80093fe97 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0008.md @@ -0,0 +1,151 @@ +--- +id: array-subset-of-another-array +title: Array Subset of another array +sidebar_label: 0008 Array Subset of another array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to whether an array is the subset of another." +--- + +## Problem + +Given two arrays: **a1[0..n-1]** of size **n** and **a2[0..m-1]** of size **m**, where both arrays may contain duplicate elements. The task is to determine whether array a2 is a subset of array a1. It's important to note that both arrays can be sorted or unsorted. Additionally, each occurrence of a duplicate element within an array is considered as a separate element of the set. + + +### Examples +**Example 1:** +``` +Input: +a1[] = {11, 7, 1, 13, 21, 3, 7, 3} +a2[] = {11, 3, 7, 1, 7} +Output: +Yes +Explanation: +a2[] is a subset of a1[] +``` + +**Example 2:** +``` +Input: +a1[] = {1, 2, 3, 4, 4, 5, 6} +a2[] = {1, 2, 4} +Output: +Yes +Explanation: +a2[] is a subset of a1[] +``` + +**Example 3:** +``` +Input: +a1[] = {10, 5, 2, 23, 19} +a2[] = {19, 5, 3} +Output: +No +Explanation: +a2[] is not a subset of a1[] +``` + +### Your Task: + +You don't need to read input or print anything. Your task is to complete the function **isSubset()** which takes the array **a1[]**, **a2[]**, its size **n** and **m** as inputs and return "Yes" if arr2 is subset of arr1 else return "No" if arr2 is not subset of arr1. + + + +- **Expected Time Complexity:** $O(max(n,m))$ +- **Expected Auxiliary Space:** $O(n)$ + +### Constraints: + +- $1 <= n,m <= 10^5$ +- $1 <= a1[i], a2[j] <= 10^6$ + +## Solution + +### Python +```python +def isSubset(a1, a2, n, m): + count_a1 = {} + count_a2 = {} + for num in a1: + count_a1[num] = count_a1.get(num, 0) + 1 + for num in a2: + count_a2[num] = count_a2.get(num, 0) + 1 + for num in count_a2: + if num not in count_a1 or count_a1[num] < count_a2[num]: + return "No" + return "Yes" +``` + +### Java +```java +public String isSubset( long a1[], long a2[], long n, long m) { + Map count_a1 = new HashMap<>(); + Map count_a2 = new HashMap<>(); + for (long num : a1) { + count_a1.put(num, count_a1.getOrDefault(num, 0) + 1); + } + for (long num : a2) { + count_a2.put(num, count_a2.getOrDefault(num, 0) + 1); + } + for (long num : count_a2.keySet()) { + if (!count_a1.containsKey(num) || count_a1.get(num) < count_a2.get(num)) { + return "No"; + } + } + return "Yes"; +} +``` + +### C++ +```cpp +string isSubset(int a1[], int a2[], int n, int m) { + unordered_map count_a1; + unordered_map count_a2; + for (int i = 0; i < n; ++i) { + count_a1[a1[i]]++; + } + for (int i = 0; i < m; ++i) { + count_a2[a2[i]]++; + } + for (const auto& pair : count_a2) { + int num = pair.first; + int count_in_a2 = pair.second; + if (count_a1.find(num) == count_a1.end() || count_a1[num] < count_in_a2) { + return "No"; + } + } + return "Yes"; +} +``` + +### C +```c +char* isSubset(int a1[], int a2[], int n, int m) { + int *count_a1 = (int *)calloc(1001, sizeof(int)); + int *count_a2 = (int *)calloc(1001, sizeof(int)); + for (int i = 0; i < n; ++i) { + count_a1[a1[i]]++; + } + for (int i = 0; i < m; ++i) { + count_a2[a2[i]]++; + } + for (int i = 0; i < 1001; ++i) { + if (count_a2[i] > 0 && count_a1[i] < count_a2[i]) { + free(count_a1); + free(count_a2); + return "No"; + } + } + free(count_a1); + free(count_a2); + return "Yes"; +} +``` + +- **Time Complexity:** $O(n+m)$ +- **Auxiliary Space:** $O(n+m)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0009.md b/dsa-solutions/gfg-solutions/Basic/0009.md new file mode 100644 index 000000000..8e48c1872 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0009.md @@ -0,0 +1,117 @@ +--- +id: reverse-array-in-groups +title: Reverse array in groups +sidebar_label: 0009 Reverse array in groups +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to reverse an array in groups." +--- + +## Problem + +Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K. + +**Note:** If at any instance, there are no more subarrays of size greater than or equal to K, then reverse the last subarray (irrespective of its size). You shouldn't return any array, modify the given array in-place. + +### Examples: +**Example 1:** +``` +Input: +N = 5, K = 3 +arr[] = {1,2,3,4,5} +Output: 3 2 1 5 4 +Explanation: First group consists of elements 1, 2, 3. Second group consists of 4,5. +``` + +**Example 2:** +``` +Input: +N = 4, K = 3 +arr[] = {5,6,8,9} +Output: 8 6 5 9 +``` + +### Your Task: + +You don't need to read input or print anything. The task is to complete the function **reverseInGroups()** which takes the array, N and K as input parameters and modifies the array in-place. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + + ### Constraints: + +- $1 ≤ N, K ≤ 10^7$ +- $1 ≤ A[i] ≤ 10^{18}$ + +## Solution + +### Python +```python +def reverseInGroups(self, arr, N, K): + i = 0 + while(i arr, int n, int k) { + for (int i = 0; i < n; i += k) { + int left = i; + int right = Math.min(i + k - 1, n - 1); + while (left < right) { + int temp = arr.get(left); + arr.set(left, arr.get(right)); + arr.set(right, temp); + left++; + right--; + } + } +} +``` + +### C++ +```cpp +void reverseInGroups(vector& arr, int n, int k){ + for (int i = 0; i < n; i += k) { + int left = i; + int right = min(i + k - 1, n - 1); + while (left < right) + swap(arr[left++], arr[right--]); + } +} +``` + +### C +```c +void reverse(int arr[], int n, int k) { + for (int i = 0; i < n; i += k) { + int left = i; + int right; + if(i+k-1 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +### C++ +```cpp +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) { + arr[i] = arr[i - 1]; + } + arr[0] = last_el; +} +``` + +### C +```c +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0011.md b/dsa-solutions/gfg-solutions/Basic/0011.md new file mode 100644 index 000000000..7d56f7143 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0011.md @@ -0,0 +1,140 @@ +--- +id: find-minimum-and-maximum-element-in-an-array +title: Find minimum and maximum element in an array +sidebar_label: 0011 Find minimum and maximum element in an array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the minimum and maximum element in an array." +--- + +## Problem + +Given an array **A** of size **N** of integers. Your task is to find the **minimum and maximum** elements in the array. + +Note: Return an array that contains 2 elements the first one will be a minimum element and the second will be a maximum of an array. + +### Examples: +**Example 1:** +``` +Input: +N = 6 +A[] = {3, 2, 1, 56, 10000, 167} +Output: 1 10000 +Explanation: minimum and maximum elements of array are 1 and 10000. +``` + +**Example 2:** +``` +Input: +N = 5 +A[] = {1, 345, 234, 21, 56789} +Output: 1 56789 +Explanation: minimum and maximum element of array are 1 and 56789. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getMinMax()** which takes the array **A[]** and its size **N** as inputs and returns the **minimum and maximum** element of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= N <= 10^5$ +- $1 <= A_i <=10^{12}$ + +## Solution +### Python +```python +def getMinMax( a, n): + if n == 0: + return None + min_value = float('inf') + max_value = float('-inf') + for num in a: + if num < min_value: + min_value = num + if num > max_value: + max_value = num + minmax = [min_value, max_value] + return minmax +``` + +### Java +```java +static Pair getMinMax(long a[], long n) { + if (n == 0) { + return null; + } + long min_value = Long.MAX_VALUE; + long max_value = Long.MIN_VALUE; + for (long num : a) { + if (num < min_value) { + min_value = num; + } + if (num > max_value) { + max_value = num; + } + } + return new Pair(min_value, max_value); +} +``` + +### C++ +```cpp +public: + pair getMinMax(long long a[], int n) { + if (n == 0) { + return {0, 0}; + } + long long min_value = LLONG_MAX; + long long max_value = LLONG_MIN; + for (int i = 0; i < n; ++i) { + if (a[i] < min_value) { + min_value = a[i]; + } + if (a[i] > max_value) { + max_value = a[i]; + } + } + return {min_value, max_value}; + } +}; +``` + +### C +```c +struct pair getMinMax(long long int arr[], long long int n) { + struct pair minmax; + int i; + if (n == 1) { + minmax.max = arr[0]; + minmax.min = arr[0]; + return minmax; + } + if (arr[0] > arr[1]) { + minmax.max = arr[0]; + minmax.min = arr[1]; + } + else { + minmax.max = arr[1]; + minmax.min = arr[0]; + } + + for (i = 2; i minmax.max) + minmax.max = arr[i]; + else if (arr[i] < minmax.min) + minmax.min = arr[i]; + } + return minmax; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0012.md b/dsa-solutions/gfg-solutions/Basic/0012.md new file mode 100644 index 000000000..21d44678b --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0012.md @@ -0,0 +1,106 @@ +--- +id: prime-number +title: Prime Number +sidebar_label: 0012 Prime Number +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to checking whether a number is prime or not." +--- + +## Problem + +For a given number **N** check if it is prime or not. A prime number is a number which is only **divisible by 1 and itself**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: +1 +Explanation: +5 has 2 factors 1 and 5 only. +``` + +**Example 2:** +``` +Input: +N = 25 +Output: +0 +Explanation: +25 has 3 factors 1, 5, 25 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **isPrime()** which takes an integer **N** as input parameters and returns an integer, 1 if N is a prime number or 0 otherwise. + +- **Expected Time Complexity:** $O(sqrt(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^9$ + +## Solution +### Python +```python +def isPrime (self, N): + if (N <= 1): + return 0 + for i in range(2, int(math.sqrt(N))+1): + if (N % i == 0): + return 0 + return 1 +``` + +### Java +```java +static int isPrime(int N){ + if (N <= 1) + return 0; + else if (N == 2) + return 1; + else if (N % 2 == 0) + return 0; + for (int i = 3; i <= Math.sqrt(N); i += 2) { + if (N % i == 0) + return 0; + } + return 1; +} +``` + +### C++ +```cpp +public: + int isPrime(int N){ + if (N <= 1) + return 0; + for (int i = 2; i <= sqrt(N); i++) + if (N % i == 0) + return 0; + return 1; + } +}; +``` + +### C +```c +int isPrime(int N) { + if (N <= 1) + return 0; + for (int i = 2; i <= sqrt(N); i++) { + if (N % i == 0) + return 0; + } + return 1; +} +``` + +- **Time Complexity:** $O(sqrt(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0013.md b/dsa-solutions/gfg-solutions/Basic/0013.md new file mode 100644 index 000000000..f62bc3810 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0013.md @@ -0,0 +1,110 @@ +--- +id: largest-element-in-array +title: Largest Element in Array +sidebar_label: 0013 Largest Element in Array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to find the largest element in an array." +--- + +## Problem + +Given an array **A[]** of size **n**. The task is to find the largest element in it. + +### Examples: +**Example 1:** +``` +Input: +n = 5 +A[] = {1, 8, 7, 56, 90} +Output: +90 +Explanation: +The largest element of given array is 90. +``` + +**Example 2:** +``` +Input: +n = 7 +A[] = {1, 2, 0, 3, 2, 4, 5} +Output: +5 +Explanation: +The largest element of given array is 5. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **largest()** which takes the array **A[]** and its size **n** as inputs and returns the maximum element in the array + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^3$ +- $0<=A[i]<=10^3$ + +Array may contain duplicate elements. + + + +## Solution +### Python +```python +def largest( arr, n): + mx = arr[0] + for i in range(1, n): + if arr[i] > mx: + mx = arr[i] + return mx +``` + +### Java +```java +public int largest(int arr[], int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; +} +``` + +### C++ +```cpp +public: + int largest(vector &arr, int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; + } +}; +``` + +### C +```c +int largest(int arr[], int n) { + int mx = arr[0]; + for (int i = 1; i < n; i++) { + if (arr[i] > mx) { + mx = arr[i]; + } + } + return mx; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0014.md b/dsa-solutions/gfg-solutions/Basic/0014.md new file mode 100644 index 000000000..2b07a9695 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0014.md @@ -0,0 +1,126 @@ +--- +id: print-first-n-fibonacci-numbers +title: Print first n Fibonacci Numbers +sidebar_label: 0014 Print first n Fibonacci Numbers +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to printing first N Fibonacci number." +--- + +## Problem + +Given a number **N**, find the first N Fibonacci numbers. The first two number of the series are 1 and 1. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: 1 1 2 3 5 +``` + +**Example 2:** +``` +Input: +N = 7 +Output: 1 1 2 3 5 8 13 +``` + +### Your task: + +Your task is to complete **printFibb()** which takes single argument N and returns a list of first N Fibonacci numbers. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +Note: This space is used to store and return the answer for printing purpose. + +### Constraints: + +- $1<=N<=84$ + +## Solution +### Python +```python +def printFibb(self,n): + fib_list = [] + f1, f2 = 1, 1 + if n < 1: + return fib_list + fib_list.append(f1) + for _ in range(1, n): + fib_list.append(f2) + next_fib = f1 + f2 + f1 = f2 + f2 = next_fib + return fib_list +``` + +### Java +```java +public static long[] printFibb(int n) { + long[] fibArray = new long[n]; + if (n < 1) { + return fibArray; + } + fibArray[0] = 1; + if (n > 1) { + fibArray[1] = 1; + } + for (int i = 2; i < n; i++) { + fibArray[i] = fibArray[i - 1] + fibArray[i - 2]; + } + return fibArray; +} +``` + +### C++ +```cpp +public: +vector printFibb(int n) { + vector fibVector(n); + if (n < 1) { + return fibVector; + } + fibVector[0] = 1; + if (n > 1) { + fibVector[1] = 1; + } + for (int i = 2; i < n; i++) { + fibVector[i] = fibVector[i - 1] + fibVector[i - 2]; + } + return fibVector; +} +``` + +### C +```c +int* printFibb(int n) { + if (n < 1) { + return NULL; + } + int* fibArray = (int*) malloc(n * sizeof(int)); + if (fibArray == NULL) { + fprintf(stderr, "Memory allocation failed\n"); + exit(1); + } + int f1 = 0, f2 = 1; + fibArray[0] = f1; + if (n > 1) { + fibArray[1] = f2; + } + for (int i = 2; i < n; i++) { + int next_fib = f1 + f2; + fibArray[i] = next_fib; + f1 = f2; + f2 = next_fib; + } + return fibArray; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0015.md b/dsa-solutions/gfg-solutions/Basic/0015.md new file mode 100644 index 000000000..ac48f1b20 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0015.md @@ -0,0 +1,131 @@ +--- +id: searching-an-element-in-a-sorted-array +title: Searching an element in a sorted array +sidebar_label: 0015 Searching an element in a sorted array +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions for searching an element in a sorted array." +--- + +## Problem + +Given an array **arr[]** sorted in ascending order of size **N** and an integer **K**. Check if K is present in the array or not. + +### Examples: +**Example 1:** +``` +Input: +N = 5, K = 6 +arr[] = {1,2,3,4,6} +Output: 1 +Exlpanation: Since, 6 is present in the array at index 4(0-based indexing), output is 1. +``` + +**Example 2:** +``` +Input: +N = 5, K = 2 +arr[] = {1,3,4,5,6} +Output: -1 +Exlpanation: Since, 2 is not present in the array, output is -1. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **searchInSorted()** which takes the sorted array arr[], its size N and the element K as input parameters and returns 1 if K is present in the array, else it returns -1. + +- **Expected Time Complexity:** $O(log N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $1<=K<=10^6$ +- $1<=arr[i]<=10^6$ + +## Solution +### Python +```python +def searchInSorted(self,arr, N, K): + low = 0 + high = N-1 + while low <= high: + mid = low + (high - low) // 2 + if arr[mid] == K: + return 1 + elif arr[mid] < K: + low = mid + 1 + else: + high = mid - 1 + return -1 +``` + +### Java +```java +static int searchInSorted(int arr[], int N, int K) { + int low = 0; + int high = N - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return -1; +} +``` + +### C++ +```cpp +int searchInSorted(int arr[], int N, int K) { + int low = 0; + int high = N - 1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + return -1; + } +``` + +### C +```c +int searchInSorted(int arr[], int N, int K) { +int low = 0; +int high = N - 1; +while (low <= high) { + int mid = low + (high - low) / 2; + if (arr[mid] == K) { + return 1; + } + else if (arr[mid] < K) { + low = mid + 1; + } + else { + high = mid - 1; + } +} +return -1; +} +``` + +- **Time Complexity:** $O(log N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0016.md b/dsa-solutions/gfg-solutions/Basic/0016.md new file mode 100644 index 000000000..f557904b9 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0016.md @@ -0,0 +1,172 @@ +--- +id: linked-list-insertion +title: Linked List Insertion +sidebar_label: 0016 Linked List Insertion +tags: +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to inserting an element in the linked list." +--- + +## Problem + +Create a link list of size N according to the given input literals. Each integer input is accompanied by an indicator which can either be 0 or 1. If it is 0, insert the integer in the beginning of the link list. If it is 1, insert the integer at the end of the link list. + +**Hint:** When inserting at the end, make sure that you handle NULL explicitly. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 9->0->5->1->6->1->2->0->5->0 +Output: 5 2 9 5 6 +Explanation: +Length of Link List = N = 5 +9 0 indicated that 9 should be +inserted in the beginning. Modified +Link List = 9. +5 1 indicated that 5 should be +inserted in the end. Modified Link +List = 9,5. +6 1 indicated that 6 should be +inserted in the end. Modified Link +List = 9,5,6. +2 0 indicated that 2 should be +inserted in the beginning. Modified +Link List = 2,9,5,6. +5 0 indicated that 5 should be +inserted in the beginning. Modified +Link List = 5,2,9,5,6. +Final linked list = 5, 2, 9, 5, 6. +``` + +**Example 2:** +``` +Input: +LinkedList: 5->1->6->1->9->1 +Output: 5 6 9 +``` + +### Your task: + +You only need to complete the functions **insertAtBeginning()** and **insertAtEnd()** that takes the head of link list and integer value of the data to be inserted as inputs and returns the head of the modified link list. + +- **Expected Time Complexity:** $O(1)$ for **insertAtBeginning()** and $O(N)$ for **insertAtEnd()** +- **Expected Auxiliary Space:** $O(1)$ for both + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def insertAtBegining(self,head,x): + new_node = Node(x) + new_node.next = head + head = new_node + return head + +def insertAtEnd(self,head,x): + new_node = Node(x) + if head is None: + head = new_node + else: + temp = head + while temp.next is not None: + temp = temp.next + temp.next = new_node + return head +``` + +### Java +```java +Node insertAtBeginning(Node head, int x) { + Node new_node = new Node(x); + new_node.next = head; + head = new_node; + return head; +} + +Node insertAtEnd(Node head, int x) { + Node new_node = new Node(x); + if (head == null) { + head = new_node; + } + else { + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = new_node; + } + return head; +} +``` + +### C++ +```cpp +Node *insertAtBegining(Node *head, int x) { + Node *new_node = new Node(x); + new_node->next = head; + head = new_node; + return head; +} + +Node *insertAtEnd(Node *head, int x) { + Node *new_node = new Node(x); + if (head == nullptr) { + head = new_node; + } + else { + Node *temp = head; + while (temp->next != nullptr) { + temp = temp->next; + } + temp->next = new_node; + } + return head; +} +``` + +### C +```c +struct Node *insertAtBegining(struct Node *head, int x) { + struct Node *new_node = (struct Node*) malloc(sizeof(struct Node)); + if (new_node == NULL) { + printf("Memory allocation failed.\n"); + return head; + } + new_node->data = x; + new_node->next = head; + head = new_node; + return head; +} + +struct Node *insertAtEnd(struct Node *head, int x) { + struct Node *new_node = (struct Node*) malloc(sizeof(struct Node)); + if (new_node == NULL) { + printf("Memory allocation failed.\n"); + return head; + } + new_node->data = x; + new_node->next = NULL; + if (head == NULL) { + head = new_node; + } + else { + struct Node *temp = head; + while (temp->next != NULL) { + temp = temp->next; + } + temp->next = new_node; + } + return head; +} +``` + +- **Time Complexity:** $O(1)$ for **insertAtBeginning()** and $O(N)$ for **insertAtEnd()** +- **Auxiliary Space:** $O(1)$ for both \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0017.md b/dsa-solutions/gfg-solutions/Basic/0017.md new file mode 100644 index 000000000..a924c3f24 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0017.md @@ -0,0 +1,99 @@ +--- +id: minimum-element-in-bst +title: Minimum element in BST +sidebar_label: 0017 Minimum element in BST +tags: +- Binary Search Tree +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the minimum element in a binary search tree." +--- + +## Problem + +Given the root of a **Binary Search Tree**. The task is to find the minimum valued element in this given BST. + +### Examples: +**Example 1:** +``` +Input: + 5 + / \ + 4 6 + / \ + 3 7 + / + 1 +Output: 1 +``` + +**Example 2:** +``` +Input: + 9 + \ + 10 + \ + 11 +Output: 9 +``` + +### Your task: + +The task is to complete the function **minValue()** which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return **-1** in that case. + +- **Expected Time Complexity:** $O$(Height of the BST) +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0<=n<=10^4$ + +## Solution +### Python +```python +def minValue(self, root): + current = root + while(current.left is not None): + current = current.left + return current.data +``` + +### Java +```java +int minValue(Node root) { + Node current = root; + while (current.left != null) { + current = current.left; + } + return current.data; +} +``` + +### C++ +```cpp +int minValue(Node* root) { + Node* current = root; + while (current->left != nullptr) { + current = current->left; + } + return current->data; +} +``` + +### C +```c +int minValue(struct Node *root) { + struct Node* current = root; + while (current->left != NULL) { + current = current->left; + } + return current->data; +} +``` + +- **Time Complexity:** $O$(Height of the BST) +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0018.md b/dsa-solutions/gfg-solutions/Basic/0018.md new file mode 100644 index 000000000..2576102ac --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0018.md @@ -0,0 +1,106 @@ +--- +id: immediate-smaller-element +title: Immediate Smaller Element +sidebar_label: 0018 Immediate Smaller Element +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the intermediate smaller element in an array." +--- + +## Problem + +Given an integer array **Arr** of size **N**. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If next element is smaller, update the current index to that element. If not, then **-1**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Arr[] = {4, 2, 1, 5, 3} +Output: +2 1 -1 3 -1 +Explanation: Array elements are 4, 2, 1, 5, 3. Next to 4 is 2 which is smaller, so we print 2. Next of 2 is 1 which is smaller, so we print 1. Next of 1 is 5 which is greater, so we print -1. Next of 5 is 3 which is smaller, so we print 3. Note that for last element, output is always going to be -1 because there is no element on right. +``` + +**Example 2:** +``` +Input: +N = 6 +Arr[] = {5, 6, 2, 3, 1, 7} +Output: +-1 2 -1 1 -1 -1 +Explanation: Next to 5 is 6 which is greater, so we print -1. Next of 6 is 2 which is smaller, so we print 2. Next of 2 is 3 which is greater, so we print -1. Next of 3 is 1 which is smaller, so we print 1. Next of 1 is 7 which is greater, so we print -1. Note that for last element, output is always going to be -1 because there is no element on right. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **immediateSmaller()** which takes the array of integers **arr** and **n** as parameters. You need to change the array itself. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^7$ +- $1<=Arr[i]<=10^5$ + +## Solution +### Python +```python +def immediateSmaller(self,arr,n): + for i in range(n - 1) : + if (arr[i] > arr[i + 1]) : + arr[i] = arr[i + 1] + else : + arr[i] = -1 + arr[n - 1] = -1 +``` + +### Java +```java +void immediateSmaller(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } + else + arr[i] = -1; + } + arr[n - 1] = -1; +} +``` + +### C++ +```cpp +void immediateSmaller(vector&arr, int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } + else + arr[i] = -1; + } + arr[n - 1] = -1; +} +``` + +### C +```c +void immediateSmaller(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + if (arr[i] > arr[i + 1]) { + arr[i] = arr[i + 1]; + } else { + arr[i] = -1; + } + } + arr[n - 1] = -1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0019.md b/dsa-solutions/gfg-solutions/Basic/0019.md new file mode 100644 index 000000000..4182c3da2 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0019.md @@ -0,0 +1,122 @@ +--- +id: implement-strstr +title: Implement strstr +sidebar_label: 0019 Implement strstr +tags: +- String +- C +- Python +- Java +- C++ +description: "This document provides solutions to check if a string is a substring of another." +--- + +## Problem + +Your task is to implement the function **strstr**. The function takes two strings as arguments **(s,x)** and locates the occurrence of the string **x** in the string **s**. The function returns an integer denoting the **first occurrence** of the string **x** in s (0 based indexing). + +**Note:** You are not allowed to use inbuilt function. + +### Examples: +**Example 1:** +``` +Input: +s = GeeksForGeeks, x = Fr +Output: -1 +Explanation: Fr is not present in the string GeeksForGeeks as substring. +``` + +**Example 2:** +``` +Input: +s = GeeksForGeeks, x = For +Output: 5 +Explanation: For is present as substring in GeeksForGeeks from index 5 (0 based indexing). +``` + +### Your task: + +You don't have to take any input. Just complete the **strstr()** function which takes two strings **str**, **target** as an input parameter. The function returns -1 if no match if found else it returns an integer denoting the first occurrence of the x in the string s. + +- **Expected Time Complexity:** $O(|s|*|x|)$ +- **Expected Auxiliary Space:** $O(1)$ + +Note : Try to solve the question in constant space complexity. + +### Constraints: + +- $1 <= |s|,|x| <= 100$ + +## Solution +### Python +```python +def strstr(s,x): + n, m = len(s), len(x) + if m == 0: + return 0 + for i in range(n - m + 1): + if s[i:i + m] == x: + return i + return -1 +``` + +### Java +```java +int strstr(String s, String x) { + int n = s.length(); + int m = x.length(); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + if (s.substring(i, i + m).equals(x)) { + return i; + } + } + return -1; +} +``` + +### C++ +```cpp +int strstr(string s, string x) { + int n = s.length(); + int m = x.length(); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + if (s.substr(i, m) == x) { + return i; + } + } + return -1; +} +``` + +### C +```c +int strstr_c(const char *s, const char *x) { + int n = strlen(s); + int m = strlen(x); + if (m == 0) { + return 0; + } + for (int i = 0; i <= n - m; i++) { + int match = 1; + for (int j = 0; j < m; j++) { + if (s[i + j] != x[j]) { + match = 0; + break; + } + } + if (match) { + return i; + } + } + return -1; +} +``` + +- **Time Complexity:** $O(|s|*|x|)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0020.md b/dsa-solutions/gfg-solutions/Basic/0020.md new file mode 100644 index 000000000..aa03874dc --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0020.md @@ -0,0 +1,136 @@ +--- +id: implement-stack-using-array +title: Implement stack using array +sidebar_label: 0020 Implement stack using array +tags: +- Array +- Stack +- C +- Python +- Java +- C++ +description: "This document provides solutions to implement a stack using array." +--- + +## Problem + +Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. + +### Examples: +**Example 1:** +``` +Input: +push(2) +push(3) +pop() +push(4) +pop() +Output: 3, 4 +Explanation: +push(2) the stack will be {2} +push(3) the stack will be {2 3} +pop() poped element will be 3, + the stack will be {2} +push(4) the stack will be {2 4} +pop() poped element will be 4 +``` + +**Example 2:** +``` +Input: +pop() +push(4) +push(5) +pop() +Output: -1, 5 +``` + +### Your task: + +You are required to complete two methods **push()** and **pop()**. The push() method takes one argument, an integer '**x**' to be pushed into the stack and **pop()** which returns an integer present at the top and popped out from the stack. If the stack is empty then return **-1** from the pop() method. + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 <= Q <= 100$ +- $1 <= x <= 100$ + +## Solution +### Python +```python +def push(self,data): + self.arr.append(data) + return self.arr + +def pop(self): + if len(self.arr) == 0: + return -1 + else: + return self.arr.pop() +``` + +### Java +```java +void push(int a) { + if (top < 999) { + top++; + arr[top] = a; + } +} + +int pop() { + if (top >= 0) { + int poppedElement = arr[top]; + top--; + return poppedElement; + } + else { + return -1; + } +} +``` + +### C++ +```cpp +void MyStack :: push(int x) { + if (top < 999) { + top++; + arr[top] = x; + } +} + +int MyStack :: pop() { + if (top >= 0) { + int poppedElement = arr[top]; + top--; + return poppedElement; + } + else { + return -1; + } +} +``` + +### C +```c +void push(struct Stack* stack, int item) { + if (stack->top != stack->capacity - 1) { + stack->top++; + stack->array[stack->top] = item; + } +} + +int pop(struct Stack* stack) { + if (stack->top == -1) { + return -1; + } + int item = stack->array[stack->top]; + stack->top--; + return item; +} +``` + +- **Time Complexity:** $O(1)$, for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$, for both **push()** and **pop()** \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0021.md b/dsa-solutions/gfg-solutions/Basic/0021.md new file mode 100644 index 000000000..08c05e3bb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0021.md @@ -0,0 +1,99 @@ +--- +id: count-linked-list-nodes +title: Count Linked List Nodes +sidebar_label: 0021 Count Linked List Nodes +tags: +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to counting the nodes in a linked list." +--- + +## Problem + +Given a singly linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5 +Output: 5 +Explanation: Count of nodes in the linked list is 5, which is its length. +``` + +**Example 2:** +``` +Input: +LinkedList: 2->4->6->7->5->1->0 +Output: 7 +Explanation: Count of nodes in the linked list is 7. Hence, the output is 7. +``` + +### Your task: + +Your task is to complete the given function **getCount()**, which takes a head reference as an argument and should return the length of the linked list. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=value<=10^3$ + +## Solution +### Python +```python +def getCount(self, head_node): + temp = head_node + count = 0 + while temp is not None: + count+=1 + temp = temp.next + return count +``` + +### Java +```java +public static int getCount(Node head) { + Node temp = head; + int count = 0; + while(temp!=null) { + count++; + temp = temp.next; + } + return count; +} +``` + +### C++ +```cpp +int getCount(struct Node* head){ + struct Node* temp = head; + int count = 0; + while (temp != NULL) { + count++; + temp = temp->next; + } + return count; +} +``` + +### C +```c +int getCount(struct Node* head) { + struct Node* temp = head; + int count = 0; + while (temp != NULL) { + count++; + temp = temp->next; + } + return count; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0022.md b/dsa-solutions/gfg-solutions/Basic/0022.md new file mode 100644 index 000000000..c4d39976a --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0022.md @@ -0,0 +1,105 @@ +--- +id: preorder-traversal +title: Preorder Traversal +sidebar_label: 0022 Preorder Traversal +tags: +- Array +- Vector +- Python +- Java +- C++ +description: "This document provides solutions to preorder traversal of a binary tree." +--- + +## Problem + +Given a binary tree, find its preorder traversal. + +### Examples: +**Example 1:** +``` +Input: + 1 + / + 4 + / \ +4 2 +Output: 1 4 4 2 +``` + +**Example 2:** +``` +Input: + 6 + / \ + 3 2 + \ / + 1 2 +Output: 6 3 1 2 2 +``` + +### Your task: + +You just have to complete the function **preorder()** which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$ Number of nodes $<= 10^4$ +- $0 <=$ Data of a node $<= 10^5$ + +## Solution +### Python +```python +def preorder(root): + arr = [] + def traverse(node): + if node is None: + return + arr.append(node.data) + traverse(node.left) + traverse(node.right) + traverse(root) + return arr +``` + +### Java +```java +static ArrayList preorder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +static void traverse(Node node, ArrayList arr) { + if (node == null) + return; + arr.add(node.data); + traverse(node.left, arr); + traverse(node.right, arr); +} +``` + +### C++ +```cpp +void traverse(Node* node, std::vector& result); + +vector preorder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + result.push_back(node->data); + traverse(node->left, result); + traverse(node->right, result); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0023.md b/dsa-solutions/gfg-solutions/Basic/0023.md new file mode 100644 index 000000000..a80767abf --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0023.md @@ -0,0 +1,120 @@ +--- +id: check-if-circular-linked-list +title: Check If Circular Linked List +sidebar_label: 0010 Check If Circular Linked List +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to whether a linked list is circular or not." +--- + +## Problem + +Given **head**, the head of a singly linked list, find if the linked list is circular or not. A linked list is called circular if it not NULL terminated and all nodes are connected in the form of a cycle. An empty linked list is considered as circular. + +**Note:** The linked list does not contains any inner loop. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5 (the first and last node is connected, i.e. 5 --> 1) +Output: 1 +``` + +**Example 2:** +``` +Input: +LinkedList: 2->4->6->7->5->1 +Output: 0 +``` + +### Your task: + +The task is to complete the function isCircular() which checks if the given linked list is circular or not. It should return true or false accordingly. (the driver code prints 1 if the returned values is true, otherwise 0) + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <=$Number of nodes$<= 100$ + +## Solution +### Python +```python +def isCircular(head): + if head is None: + return False + slow = head + fast = head.next + while fast is not None and fast.next is not None: + if slow == fast: + return True + slow = slow.next + fast = fast.next.next + return False +``` + +### Java +```java +boolean isCircular(Node head) { + if (head == null) { + return false; + } + Node slow = head; + Node fast = head.next; + while (fast != null && fast.next != null) { + if (slow == fast) { + return true; + } + slow = slow.next; + fast = fast.next.next; + } + return false; +} +``` + +### C++ +```cpp +bool isCircular(Node *head) { + if (head == NULL) { + return false; + } + Node* slow = head; + Node* fast = head->next; + while (fast != nullptr && fast->next != nullptr) { + if (slow == fast) { + return true; + } + slow = slow->next; + fast = fast->next->next; + } + return false; +} +``` + +### C +```c +bool isCircular(struct Node *head){ + if (head == NULL) { + return false; + } + struct Node *slow = head; + struct Node *fast = head->next; + while (fast != NULL && fast->next != NULL) { + if (slow == fast) { + return true; + } + slow = slow->next; + fast = fast->next->next; + } + return false; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0024.md b/dsa-solutions/gfg-solutions/Basic/0024.md new file mode 100644 index 000000000..bcb52dd62 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0024.md @@ -0,0 +1,101 @@ +--- +id: inorder-traversal +title: Inorder Traversal +sidebar_label: 0024 Inorder Traversal +tags: +- Array +- Binary tree +- Python +- Java +- C++ +description: "This document provides solutions for inorder traversal of a tree." +--- + +## Problem + +Given a Binary Tree, find the In-Order Traversal of it. + +### Examples: +**Example 1:** +``` +Input: + 1 + / \ + 3 2 +Output: 3 1 2 +``` + +**Example 2:** +``` +Input: + 10 + / \ + 20 30 + / \ / + 40 60 50 +Output: 40 20 60 10 50 30 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **inOrder()** that takes root node of the tree as input and returns a list containing the In-Order Traversal of the given Binary Tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$Number of nodes $<= 10^5$ +- $0 <=$Data of a node $<= 10^5$ + +## Solution +### Python +```python +def InOrder(self,root): + arr = [] + def traverse(node): + if node is None: + return + traverse(node.left) + arr.append(node.data) + traverse(node.right) + traverse(root) + return arr +``` + +### Java +```java +ArrayList inOrder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +void traverse(Node node, ArrayList arr) { + if (node == null) + return; + traverse(node.left, arr); + arr.add(node.data); + traverse(node.right, arr); +} +``` + +### C++ +```cpp +vector inOrder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + traverse(node->left, result); + result.push_back(node->data); + traverse(node->right, result); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0025.md b/dsa-solutions/gfg-solutions/Basic/0025.md new file mode 100644 index 000000000..00c7804e4 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0025.md @@ -0,0 +1,144 @@ +--- +id: implement-queue-using-array +title: Implement Queue using array +sidebar_label: 0010 Implement Queue using array +tags: +- Array +- Queue +- C +- Python +- Java +- C++ +description: "This document provides solutions to implement a queue using an array." +--- + +## Problem + +Implement a Queue using an Array. Queries in the Queue are of the following type: +- 1 x (a query of this type means pushing 'x' into the queue) +- 2 (a query of this type means to pop element from queue and print the poped element) + +### Examples: +**Example 1:** +``` +Input: +Q = 5 +Queries = 1 2 1 3 2 1 4 2 +Output: 2 3 +Explanation: +In the first test case for query +1 2 the queue will be {2} +1 3 the queue will be {2 3} +2 poped element will be 2 the + queue will be {3} +1 4 the queue will be {3 4} +2 poped element will be 3 +``` + +**Example 2:** +``` +Input: +Q = 4 +Queries = 1 3 2 2 1 4 +Output: 3 -1 +Explanation: +In the second testcase for query +1 3 the queue will be {3} +2 poped element will be 3 the + queue will be empty +2 there is no element in the + queue and hence -1 +1 4 the queue will be {4}. +``` + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 ≤ Q ≤ 10^5$ +- $0 ≤ x ≤ 10^5$ + +## Solution +### Python +```python +def __init__(self): + self.q = [] + +def push(self, x): + self.q.append(x) + +def pop(self): + if self.q: + return self.q.pop(0) + else: + return -1 +``` + +### Java +```java +void push(int x) { + if (rear == arr.length) { + return; + } + arr[rear] = x; + rear++; +} + +int pop() { + if (front == rear) { + return -1; + } + int element = arr[front]; + for (int i = 0; i < rear - 1; i++) { + arr[i] = arr[i + 1]; + } + rear--; + return element; +} +``` + +### C++ +```cpp +void MyQueue :: push(int x) { + if ((rear + 1) % 100005 == front) { + return; + } + arr[rear] = x; + rear = (rear + 1) % 100005; +} + +int MyQueue :: pop() { + if (front == rear) { + return -1; + } + int element = arr[front]; + front = (front + 1) % 100005; + + return element; +} +``` + +### C +```c +void push(struct MyQueue *queue, int x) { + if ((queue->rear + 1) % MAX_SIZE == queue->front) { + return; + } + queue->arr[queue->rear] = x; + queue->rear = (queue->rear + 1) % MAX_SIZE; +} + +int pop(struct MyQueue *queue) { + if (queue->front == queue->rear) { + printf("Queue is empty. Cannot pop element.\n"); + return -1; + } + int element = queue->arr[queue->front]; + queue->front = (queue->front + 1) % MAX_SIZE; + return element; +} +``` + +- **Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$ for both **push()** and **pop()** \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0026.md b/dsa-solutions/gfg-solutions/Basic/0026.md new file mode 100644 index 000000000..7f3226361 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0026.md @@ -0,0 +1,78 @@ +--- +id: count-squares +title: Count Squares +sidebar_label: 0026 Count Squares +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions for calculating perfect squares." +--- + +## Problem + +Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number **N**, you have to output the number of integers less than N in the sample space S. + +### Examples: +**Example 1:** +``` +Input : +N = 9 +Output: +2 +Explanation: +1 and 4 are the only Perfect Squares less than 9. So, the Output is 2. +``` + +**Example 2:** +``` +Input : +N = 3 +Output: +1 +Explanation: +1 is the only Perfect Square less than 3. So, the Output is 1. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **countSquares()** which takes an Integer N as input and returns the answer. + +- **Expected Time Complexity:** $O(sqrt(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^8$ + +## Solution +### Python +```python +def countSquares(self, N): + return (math.floor(math.sqrt(N-1)) - math.ceil(math.sqrt(1)) + 1) +``` + +### Java +```java +static int countSquares(int N) { + return (int)(Math.floor(Math.sqrt(N - 1)) - Math.ceil(Math.sqrt(1)) + 1); +} +``` + +### C++ +```cpp +int countSquares(int N) { + return (floor(sqrt(N - 1)) - ceil(sqrt(1)) + 1); +} +``` + +### C +```c +int countSquares(int N) { + return (int)(floor(sqrt(N - 1)) - ceil(sqrt(1)) + 1); +} +``` + +- **Time Complexity:** $O(sqrt(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0027.md b/dsa-solutions/gfg-solutions/Basic/0027.md new file mode 100644 index 000000000..eea9abbb6 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0027.md @@ -0,0 +1,97 @@ +--- +id: print-linked-list-elements +title: Print Linked List elements +sidebar_label: 0027 Print Linked List elements +tags: +- Linked list +- C +- Python +- Java +- C++ +description: "This document provides solutions to cyclically rotate the array by one." +--- + +## Problem + +Given a linked list. Print all the elements of the linked list. + +**Note:** End of Line is handled by driver code itself. You just have to end with a single space. + +### Examples: +**Example 1:** +``` +Input: +LinkedList : 1 -> 2 +Output: +1 2 +Explanation: +The linked list contains two elements 1 and 2.The elements are printed in a single line. +``` + +**Example 2:** +``` +Input: +Linked List : 49 -> 10 -> 30 +Output: +49 10 30 +Explanation: +The linked list contains 3 elements 49, 10 and 30. The elements are printed in a single line. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **display()** which takes the head of the linked list as input and prints the linked list in a single line. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <=10^5$ +- $1 <=$ node values $<= 10^6$ + +## Solution +### Python +```python +def display(self,head): + temp = head + while temp is not None: + print(temp.data, end = " ") + temp = temp.next +``` + +### Java +```java +void display(Node head) { + Node temp = head; + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } +} +``` + +### C++ +```cpp +void display(Node *head) { + Node* temp = head; + while (temp != nullptr) { + cout << temp->data << " "; + temp = temp->next; + } +} +``` + +### C +```c +void display(struct Node *head) { + struct Node* temp = head; + while (temp != NULL) { + printf("%d ", temp->data); + temp = temp->next; + } +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0028.md b/dsa-solutions/gfg-solutions/Basic/0028.md new file mode 100644 index 000000000..47474022d --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0028.md @@ -0,0 +1,139 @@ +--- +id: implement-stack-using-linked-list +title: Implement Stack using Linked List +sidebar_label: 0028 Implement Stack using Linked List +tags: +- Array +- Linked List +- C +- Python +- Java +- C++ +description: "This document provides solutions to implementing a stack using linked list." +--- + +## Problem + +You have a linked list and you have to implement the functionalities push and pop of stack using this given linked list. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. + +### Examples: +**Example 1:** +``` +Input: +push(2) +push(3) +pop() +push(4) +pop() +Output: 3 4 +Explanation: +push(2) the stack will be {2} +push(3) the stack will be {2 3} +pop() poped element will be 3, + the stack will be {2} +push(4) the stack will be {2 4} +pop() poped element will be 4 +``` + +**Example 2:** +``` +Input: +pop() +push(4) +push(5) +pop() +Output: -1 5 +``` + +### Your task: + +You are required to complete two methods **push()** and **pop()**. The **push()** method takes one argument, an integer '**x**' to be pushed into the stack and **pop()** which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the **pop()** method. + +- **Expected Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Expected Auxiliary Space:** $O(1)$ for both **push()** and **pop()** + +### Constraints: + +- $1 <= Q <= 100$ +- $1 <= x <= 100$ + +## Solution +### Python +```python +def __init__(self): + self.head = None + +def push(self, data): + new_node = StackNode(data) + new_node.next = self.head + self.head = new_node + +def pop(self): + if self.head is None: + return -1 + else: + ele = self.head.data + self.head = self.head.next + return ele +``` + +### Java +```java +void push(int a) { + StackNode new_node = new StackNode(a); + new_node.next = top; + top = new_node; +} + +int pop() { + if (top == null) { + return -1; + } else { + int element = top.data; + top = top.next; + return element; + } +} +``` + +### C++ +```cpp +void MyStack ::push(int x) { + StackNode* new_node = new StackNode(x); + new_node->next = top; + top = new_node; +} + +int MyStack ::pop() { + if (top == nullptr) { + return -1; + } + else { + int element = top->data; + StackNode* temp = top; + top = top->next; + delete temp; + return element; + } +} +``` + +### C +```c +void push(struct Stack* stack, int item) { + if (stack->top == stack->capacity - 1) { + return; + } + stack->array[++stack->top] = item; +} + +int pop(struct Stack* stack) { + if (stack->top == -1) { + return -1; + } + return stack->array[stack->top--]; +} +``` + +- **Time Complexity:** $O(1)$ for both **push()** and **pop()** +- **Auxiliary Space:** $O(1)$ for both **push()** and **pop()** \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0029.md b/dsa-solutions/gfg-solutions/Basic/0029.md new file mode 100644 index 000000000..56cf487b2 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0029.md @@ -0,0 +1,90 @@ +--- +id: factorial +title: Factorial +sidebar_label: 0029 Factorial +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the factorial of a number." +--- + +## Problem + +Given a positive integer, **N**. Find the factorial of **N**. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +Output: +120 +Explanation: +5*4*3*2*1 = 120 +``` + +**Example 2:** +``` +Input: +N = 4 +Output: +24 +Explanation: +4*3*2*1 = 24 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **factorial()** which takes an integer **N** as input parameters and returns an integer, the factorial of N. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0 <= N <= 18$ + +## Solution +### Python +```python +def factorial (self, N): + fact = 1 + for i in range(1, N+1): + fact = fact*i + return fact +``` + +### Java +```java +static long factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +### C++ +```cpp +long long int factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +### C +```c +long long int factorial(int N){ + long fact = 1; + for (int i = 1; i<=N; i++) + fact = fact*i; + return fact; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0030.md b/dsa-solutions/gfg-solutions/Basic/0030.md new file mode 100644 index 000000000..42edec0a3 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0030.md @@ -0,0 +1,103 @@ +--- +id: identical-linked-lists +title: Identical Linked Lists +sidebar_label: 0029 Identical Linked Lists +tags: +- C +- Python +- Java +- C++ +description: "This document provides solutions for checking whether two linked lists are identical or not." +--- + +## Problem + +Given the two singly **Linked Lists** respectively. The task is to check whether two linked lists are **identical** or not. + +Two Linked Lists are identical when they have the same data and with the same arrangement too. If both Linked Lists are identical then return true otherwise return false. + +### Examples: +**Example 1:** +``` +Input: +LinkedList1: 1->2->3->4->5->6 +LinkedList2: 99->59->42->20 +Output: Not identical +``` + +**Example 2:** +``` +Input: +LinkedList1: 1->2->3->4->5 +LinkedList2: 1->2->3->4->5 +Output: Identical +``` + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^3$ + +## Solution +### Python +```python +def areIdentical(head1, head2): + temp1 = head1 + temp2 = head2 + while temp1 is not None and temp2 is not None: + if temp1.data!=temp2.data: + return False + temp1 = temp1.next + temp2 = temp2.next + return True +``` + +### Java +```java +public boolean isIdentical (Node head1, Node head2){ + Node temp1 = head1; + Node temp2 = head2; + while (temp1!=null && temp2!=null) { + if (temp1.data!=temp2.data) + return false; + temp1 = temp1.next; + temp2 = temp2.next; + } + return temp1 == null && temp2 == null; +} +``` + +### C++ +```cpp +bool areIdentical(struct Node *head1, struct Node *head2) { + struct Node* temp1 = head1; + struct Node* temp2 = head2; + while (temp1 != nullptr && temp2 != nullptr) { + if (temp1->data != temp2->data) + return false; + temp1 = temp1->next; + temp2 = temp2->next; + } + return temp1 == nullptr && temp2 == nullptr; +} +``` + +### C +```c +bool areIdentical(struct Node *head1, struct Node *head2) { + struct Node* temp1 = head1; + struct Node* temp2 = head2; + while (temp1 != NULL && temp2 != NULL) { + if (temp1->data != temp2->data) + return false; + temp1 = temp1->next; + temp2 = temp2->next; + } + return temp1 == NULL && temp2 == NULL; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0031.md b/dsa-solutions/gfg-solutions/Basic/0031.md new file mode 100644 index 000000000..5293dc8e6 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0031.md @@ -0,0 +1,98 @@ +--- +id: searching-a-number +title: Searching a number +sidebar_label: 0031 Searching a number +tags: +- Array +- C +- Python +- Java +- C++ +description: "This document provides solutions to finding the position of an element in the array." +--- + +## Problem + +Given an array **arr** of **n** elements and a integer **k**. Your task is to return the position of **first occurence** of **k** in the given array and if element k is not present in the array then return **-1** . + +**Note:** Position of first element is considered as 1. + +### Examples: +**Example 1:** +``` +Input: +n = 5 +k = 16 +arr = {9, 7, 2, 16, 4} +Output: 4 +Explanation: k = 16 is found in the given array at position 4. +``` + +**Example 2:** +``` +Input: +n = 7 +k = 98 +arr = {1, 22, 57, 47, 34, 18, 66} +Output: -1 +Explanation: k = 98 isn't found in the given array. +``` + +### Your task: + +Complete the function **search()** which takes two integers **n** , **k** and an array **arr**, as input parameters and returns an integer denoting the answer. Return **-1** if the number is not found in the array. You don't have to print answers or take inputs. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^6$ +- $1 <= k <= 10^6$ +- $1 <= arr[i] <= 10^9$ + +## Solution +### Python +```python +def search(self, n : int, k : int, arr : List[int]) -> int: + for i in range(0, n-1): + if k==arr[i]: + return i+1 + return -1 +``` + +### Java +```java +public static int search(int n, int k, int[] arr) { + for(int i = 0; i &arr) { + for(int i = 0; i sortArr(vectorarr, int n){ + sort(arr.begin(), arr.end()); + return arr; +} +``` + +### C +```c +int compare(const void* a, const void* b) { + return (*(int*)a - *(int*)b); +} + +void sortArr(int arr[], int n) { + qsort(arr, n, sizeof(int), compare); +} +``` + +- **Time Complexity:** $O(n * log n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0033.md b/dsa-solutions/gfg-solutions/Basic/0033.md new file mode 100644 index 000000000..bcc31d143 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0033.md @@ -0,0 +1,114 @@ +--- +id: postorder-traversal +title: Postorder Traversal +sidebar_label: 0033 Postorder Traversal +tags: +- Binary Tree +- Python +- Java +- C++ +description: "This document provides solutions postorder traversal of a binary tree." +--- + +## Problem + +Given a binary tree, find the Postorder Traversal of it. + +For Example, the postorder traversal of the following tree is: +5 10 39 1 +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: + 19 + / \ + 10 8 + / \ + 11 13 +Output: 11 13 10 8 19 +``` + +**Example 2:** +``` +Input: + 11 + / + 15 + / + 7 +Output: 7 15 11 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **postOrder()** that takes **root node** as input and returns an array containing the postorder traversal of the given Binary Tree. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(N)$ + +### Constraints: + +- $1 <=$ Number of nodes $<= 10^5$ +- $0 <=$ Data of a node $<= 10^5$ + +## Solution +### Python +```python +def postOrder(root): + arr = [] + def traverse(node): + if node is None: + return + traverse(node.left) + traverse(node.right) + arr.append(node.data) + traverse(root) + return arr +``` + +### Java +```java +ArrayList postOrder(Node root) { + ArrayList arr = new ArrayList<>(); + traverse(root, arr); + return arr; +} + +void traverse(Node node, ArrayList arr) { + if (node == null) + return; + traverse(node.left, arr); + traverse(node.right, arr); + arr.add(node.data); +} +``` + +### C++ +```cpp +void traverse(Node* node, vector& result); + +vector postOrder(Node* root) { + vector result; + traverse(root, result); + return result; +} + +void traverse(Node* node, vector& result) { + if (node == nullptr) + return; + traverse(node->left, result); + traverse(node->right, result); + result.push_back(node->data); +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(N)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0034.md b/dsa-solutions/gfg-solutions/Basic/0034.md new file mode 100644 index 000000000..baa9eb473 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0034.md @@ -0,0 +1,112 @@ +--- +id: lcm-and-gcd +title: LCM and GCD +sidebar_label: 0034 LCM and GCD +tags: +- Mathematics +- Number Theory +- C +- Python +- Java +- C++ +description: "This document provides solutions for finding the Least Common Multiple (LCM) and Greatest Common Divisor (GCD) of integers." +--- + +## Problem + +Given two integers a and b, write a function lcmAndGcd() to compute their LCM and GCD. The function takes two integers b and b as input and returns a list containing their LCM and GCD. + +### Examples: +**Example 1:** +``` +Input: a = 5 , b = 10 +Output: 10 5 +Explanation: LCM of 5 and 10 is 10, while thier GCD is 5. +``` + +**Example 2:** +``` +Input: a = 14 , b = 8 +Output: 56 2 +Explanation: LCM of 14 and 8 is 56, while thier GCD is 2. +``` + +- **Expected Time Complexity:** $O(log(min(a, b))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= a, b <=10^9$ + +## Solution +### Python +```python +def lcmAndGcd(self, A , B): + def g(a,b): + if (b == 0): + return a + return g(b, a%b) + + gcd = g(A, B) + lcm = A*B//gcd + return lcm, gcd +``` + +### Java +```java +static Long[] lcmAndGcd(Long A , Long B) { + long gcd = calculateGCD(A, B); + long lcm = (A * B) / gcd; + return new Long[] {lcm, gcd}; +} + +static long calculateGCD(long a, long b) { + if (b == 0) { + return a; + } + return calculateGCD(b, a % b); +} +``` + +### C++ +```cpp +public: +vector lcmAndGcd(long long A , long long B) { + long long gcd_val = gcd(A, B); + long long lcm_val = (A / gcd_val) * B; + return {lcm_val, gcd_val}; +} + +private: +long long gcd(long long a, long long b) { + if (b == 0) { + return a; + } + return gcd(b, a % b); +} +``` + +### C +```c +long long gcd(long long a, long long b) { + while (b != 0) { + long long temp = b; + b = a % b; + a = temp; + } + return a; +} + +long long lcm(long long a, long long b) { + return (a / gcd(a, b)) * b; +} + +void lcmAndGcd(long long A, long long B, long long *lcm_result, long long *gcd_result) { + *gcd_result = gcd(A, B); + *lcm_result = lcm(A, B); +} + +``` + +- **Time Complexity:** $O(log(min(a, b))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0035.md b/dsa-solutions/gfg-solutions/Basic/0035.md new file mode 100644 index 000000000..440b6d2d8 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0035.md @@ -0,0 +1,135 @@ +--- +id: rotating-an-array +title: Rotating an Array +sidebar_label: 0035 Rotating an Array +tags: +- Array +- Rotation +- C +- Python +- Java +- C++ +description: "This document provides solutions for rotating an array to the left or right by a specified number of positions." +--- + +## Problem + +Given an array of size n. The task is to rotate array by d elements where d ≤ n. + +### Examples: +**Example 1:** +``` +Input: +n = 7 +arr[] = {-1, -2, -3, 4, 5, 6, 7} +d = 2 +Output: {-3, 4, 5, 6, 7, -1, -2} +Explanation: +Rotate by 1: [-2, -3, 4, 5, 6, 7, -1] +Rotate by 2: [-3, 4, 5, 6, 7, -1, -2] +``` + +**Example 2:** +``` +Input: +n = 4 +arr[] = {1, 3, 4, 2} +d = 3 +Output: {2, 1, 3, 4} +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **leftRotate()** which takes the array of integers **arr[]**, its size **n** and **d** as input parameters and rotates arr[] in-place without using any extra memory. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≤ n ≤ 10^6$ +- $-10^9 ≤ arr[i] ≤ 10^9$ +- $0 ≤ d ≤ n$ + +## Solution +### Python +```python +def reverse(self, arr, start, end): + while start < end: + arr[start], arr[end] = arr[end], arr[start] + start += 1 + end -= 1 + +def leftRotate(self, arr, n, d): + d = d % n + self.reverse(arr, 0, d - 1) + self.reverse(arr, d, n - 1) + self.reverse(arr, 0, n - 1) +``` + +### Java +```java +void leftRotate(int[] arr, int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} + +void reverse(int[] arr, int start, int end) { + while (start < end) { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } +} +``` + +### C++ +```cpp +public: +void reverse(int arr[], int start, int end) { + while (start < end) { + swap(arr[start], arr[end]); + start++; + end--; + } +} + +public: +void leftRotate(int arr[], int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} +``` + +### C +```c +void swap(int *a, int *b) { + int temp = *a; + *a = *b; + *b = temp; +} + +void reverse(int arr[], int start, int end) { + while (start < end) { + swap(&arr[start], &arr[end]); + start++; + end--; + } +} + +void leftRotate(int arr[], int n, int d) { + d = d % n; + reverse(arr, 0, d - 1); + reverse(arr, d, n - 1); + reverse(arr, 0, n - 1); +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0036.md b/dsa-solutions/gfg-solutions/Basic/0036.md new file mode 100644 index 000000000..e3b2aa5ed --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0036.md @@ -0,0 +1,118 @@ +--- +id: binary-array-sorting +title: Binary Array Sorting +sidebar_label: 0036 Binary Array Sorting +tags: +- Array +- Sorting +- Binary Array +- C +- Python +- Java +- C++ +description: "This document provides solutions for sorting a binary array, where elements are either 0 or 1." +--- + +## Problem + +Given a binary array **A[]** of size **N**. The task is to arrange the array in increasing order. + +**Note:** The binary array contains only 0 and 1. + +### Examples: +**Example 1:** +``` +Input: +5 +1 0 1 1 0 + +Output: +0 0 1 1 1 + +Explanation: +After arranging the elements in increasing order, elements will be as 0 0 1 1 1. +``` + +**Example 2:** +``` +Input: +10 +1 0 1 1 1 1 1 0 0 0 + +Output: +0 0 0 0 1 1 1 1 1 1 + +Explanation: +After arranging the elements in increasing order, elements will be 0 0 0 0 1 1 1 1 1 1. +``` + +### Your task: + +This is a function problem. You only need to complete the function **binSort()** that takes the array **A[]** and it's size **N** as parameters and sorts the array. The printing is done automatically by the driver code. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $0<=A[i]<=1$ + +## Solution +### Python +```python +def binSort(self, A, N): + j = -1 + for i in range(N): + if A[i] < 1: + j = j + 1 + A[i], A[j] = A[j], A[i] +``` + +### Java +```java +static void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +### C++ +```cpp +void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +### C +```c +void binSort(int A[], int N) { + int j = -1; + for (int i = 0; i < N; i++) { + if (A[i] < 1) { + j++; + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0037.md b/dsa-solutions/gfg-solutions/Basic/0037.md new file mode 100644 index 000000000..d4013296a --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0037.md @@ -0,0 +1,125 @@ +--- +id: count-leaves-binary-tree +title: Count Leaves in Binary Tree +sidebar_label: 0037 Count Leaves in Binary Tree +tags: +- Binary Tree +- Tree Traversal +- Depth-First Search +- C +- Python +- Java +- C++ +description: "This document provides solutions for counting the number of leaf nodes in a binary tree." +--- + +## Problem + +Given a Binary Tree of size N, You have to count leaves in it. For example, there are two leaves in following tree. + +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: +Given Tree is + 4 + / \ + 8 10 + / / \ + 7 5 1 + / + 3 +Output: +3 +Explanation: +Three leaves are 3 , 5 and 1. +``` + +### Your task: + +You don't have to take input. Complete the function **countLeaves()** that takes root node of the given tree as parameter and returns the count of leaves in tree. The printing is done by the driver code. + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def countLeaves(root): + q = [] + q.append(root) + count = 0 + while(len(q) > 0): + temp = q.pop(0) + if(temp.left is None and temp.right is None): + count += 1 + if(temp.left is not None): + q.append(temp.left) + if(temp.right is not None): + q.append(temp.right) + return count +``` + +### Java +```java +int countLeaves(Node node) { + Queue q = new LinkedList(); + q.add(node); + int count = 0; + while(!q.isEmpty()){ + Node temp = q.poll(); + if(temp.left == null && temp.right == null) count++; + if(temp.left != null) q.add(temp.left); + if(temp.right != null) q.add(temp.right); + } + return count; +} +``` + +### C++ +```cpp +int countLeaves(Node* root) { + queue q; + q.push(root); + int count = 0; + while(!q.empty()){ + Node* temp = q.front(); + q.pop(); + if(temp->left == NULL && temp->right == NULL) + count++; + if(temp->left) q.push(temp->left); + if(temp->right) q.push(temp->right); + } + return count; +} +``` + +### C +```c +int countLeaves(struct Node* root) { + struct Node** queue = (struct Node**) malloc(1000 * sizeof(struct Node*)); + int front = 0, rear = 0; + queue[rear++] = root; + int count = 0; + while (front < rear) { + struct Node* temp = queue[front++]; + if (temp->left == NULL && temp->right == NULL) + count++; + if (temp->left) + queue[rear++] = temp->left; + if (temp->right) + queue[rear++] = temp->right; + } + free(queue); + return count; +} +``` \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0038.md b/dsa-solutions/gfg-solutions/Basic/0038.md new file mode 100644 index 000000000..260cc23d4 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0038.md @@ -0,0 +1,110 @@ +--- +id: third-largest-element +title: Third Largest Element +sidebar_label: 0038 Third Largest Element +tags: +- Array +- Sorting +- C +- Python +- Java +- C++ +description: "This document provides solutions for finding the third largest element in an array." +--- + + +## Problem + +Given an array of distinct elements. Find the third largest element in it. + +Suppose you have A[] = {1, 2, 3, 4, 5, 6, 7}, its output will be 5 because it is the 3 largest element in the array A. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = {2,4,1,3,5} +Output: 3 +``` + +**Example 2:** +``` +Input: +N = 2 +A[] = {10,2} +Output: -1 +``` + +### Your task: + +Complete the function **thirdLargest()** which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=A[i]<=10^5$ + +## Solution +### Python +```python +def thirdLargest(self,a, n): + if (n < 3): + return -1 + else: + a = sorted(a) + return a[-3] +``` + +### Java +```java +int thirdLargest(int a[], int n) { + if (n < 3) { + return -1; + } + else { + Arrays.sort(a); + return a[n - 3]; + } +} +``` + +### C++ +```cpp +int thirdLargest(int a[], int n) { + if (n < 3) { + return -1; + } + else { + std::sort(a, a + n); + return a[n - 3]; + } +} +``` + +### C +```c +int thirdLargest(int* a, int n) { + if (n < 3) { + return -1; + } + else { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (a[j] > a[j + 1]) { + int temp = a[j]; + a[j] = a[j + 1]; + a[j + 1] = temp; + } + } + } + return a[n - 3]; + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0039.md b/dsa-solutions/gfg-solutions/Basic/0039.md new file mode 100644 index 000000000..d4d85f140 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0039.md @@ -0,0 +1,125 @@ +--- +id: insert-middle-linked-list +title: Insert in Middle of Linked List +sidebar_label: 0039 Insert in Middle of Linked List +tags: +- Linked List +- Insertion +- C +- Python +- Java +- C++ +description: "This document provides solutions for inserting a node in the middle of a linked list." +--- + +## Problem + +Given a linked list of size **N** and a **key**. The task is to insert the key in the middle of the linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList = 1->2->4 +key = 3 +Output: 1 2 3 4 +Explanation: The new element is inserted after the current middle element in the linked list. +``` + +**Example 2:** +``` +Input: +LinkedList = 10->20->40->50 +key = 30 +Output: 10 20 30 40 50 +Explanation: The new element is inserted after the current middle element in the linked list and Hence, the output is 10 20 30 40 50. +``` + +### Your task: + +The task is to complete the function **insertInMiddle()** which takes head reference and element to be inserted as the arguments. The printing is done automatically by the driver code. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^4$ + +## Solution +### Python +```python +def insertInMid(head, node): + if head is None: + return node + slow = head + fast = head + while fast.next is not None and fast.next.next is not None: + slow = slow.next + fast = fast.next.next + node.next = slow.next + slow.next = node + return head +``` + +### Java +```java +public Node insertInMid(Node head, int data){ + Node newNode = new Node(data); + if (head == null) { + return newNode; + } + Node slow = head; + Node fast = head; + while (fast.next != null && fast.next.next != null) { + slow = slow.next; + fast = fast.next.next; + } + newNode.next = slow.next; + slow.next = newNode; + return head; +} +``` + +### C++ +```cpp +Node* insertInMiddle(Node* head, int x) { + Node* newNode = new Node(x); + if (head == nullptr) { + return newNode; + } + Node* slow = head; + Node* fast = head; + while (fast->next != nullptr && fast->next->next != nullptr) { + slow = slow->next; + fast = fast->next->next; + } + newNode->next = slow->next; + slow->next = newNode; + return head; +} +``` + +### C +```c +struct Node* insertInMiddle(struct Node* head, int x) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = x; + newNode->next = NULL; + if (head == NULL) { + return newNode; + } + struct Node* slow = head; + struct Node* fast = head; + while (fast->next != NULL && fast->next->next != NULL) { + slow = slow->next; + fast = fast->next->next; + } + newNode->next = slow->next; + slow->next = newNode; + return head; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0040.md b/dsa-solutions/gfg-solutions/Basic/0040.md new file mode 100644 index 000000000..4450dedd1 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0040.md @@ -0,0 +1,122 @@ +--- +id: maximum-occurring-character +title: Maximum Occurring Character +sidebar_label: Maximum Occurring Character +tags: +- Strings +- C +- Python +- Java +- C++ +description: "This document explores algorithms to find the maximum occurring character in a string." +--- + +## Problem + +Given a string **str** of lowercase alphabets. The task is to find the maximum occurring character in the string **str**. If more than one character occurs the maximum number of time then print the lexicographically smaller character. + +### Examples: +**Example 1:** +``` +Input: +str = testsample +Output: e +Explanation: e is the character which is having the highest frequency. +``` + +**Example 2:** +``` +Input: +str = output +Output: t +Explanation: t and u are the characters with the same frequency, but t is lexicographically smaller. +``` + +### Your task: + +The task is to complete the function **getMaxOccuringChar()** which returns the character which is most occurring. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +**Note:** N = |s| + +### Constraints: + +- $1 ≤ |s| ≤ 100$ + +## Solution +### Python +```python +def getMaxOccurringChar(self,s): + mp = {} + n = len(s) + ans = '' + cnt = 0 + + for i in range(n): + if s[i] in mp: + mp[s[i]] += 1 + else: + mp[s[i]] = 1 + if mp[s[i]] > cnt or (mp[s[i]] == cnt and s[i] < ans): + ans = s[i] + cnt = mp[s[i]] + return ans +``` + +### Java +```java +public static char getMaxOccuringChar(String line) { + Map mp = new HashMap<>(); + int n = line.length(); + char ans = '\0'; + int cnt = 0; + for (int i = 0; i < n; i++) { + char ch = line.charAt(i); + mp.put(ch, mp.getOrDefault(ch, 0) + 1); + if (mp.get(ch) > cnt || (mp.get(ch) == cnt && ch < ans)) { + ans = ch; + cnt = mp.get(ch); + } + } + return ans; +} +``` + +### C++ +```cpp +char getMaxOccuringChar(string str) { + unordered_map mp; + char ans = '\0'; + int cnt = 0; + for (char ch : str) { + mp[ch]++; + if (mp[ch] > cnt || (mp[ch] == cnt && ch < ans)) { + ans = ch; + cnt = mp[ch]; + } + } + return ans; +} +``` + +### C +```c +char getMaxOccuringChar(const char* str) { + int freq[256] = {0}; + char ans = '\0'; + int cnt = 0; + for (int i = 0; str[i] != '\0'; i++) { + freq[(int)str[i]]++; + if (freq[(int)str[i]] > cnt || (freq[(int)str[i]] == cnt && str[i] < ans)) { + ans = str[i]; + cnt = freq[(int)str[i]]; + } + } + return ans; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0041.md b/dsa-solutions/gfg-solutions/Basic/0041.md new file mode 100644 index 000000000..8793dfbd2 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0041.md @@ -0,0 +1,103 @@ +--- +id: count-odd-even +title: Count Odd Even +sidebar_label: 0041 Count Odd Even +tags: +- Arrays +- C +- Python +- Java +- C++ +description: "This document covers methods to count the number of odd and even integers in an array." +--- + +## Problem + +Given an array **A[]** of **N** elements. The task is to return the count of the number of **odd** and **even** elements in the array. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = 1 2 3 4 5 +Output: +3 2 +Explanation: +There are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4). +``` + +### Your task: + +Your task is to complete the function **countOddEven()** which should return the count of odd and even elements of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $1<=A_j<=10^6$ + +## Solution +### Python +```python +def countOddEven(self, arr, n): + odd, even = 0,0 + for i in range(0, n): + if arr[i]%2==0: + even+=1 + else: + odd+=1 + return odd, even +``` + +### Java +```java +public int[] countOddEven(int[] arr, int n) { + int odd = 0, even = 0; + for (int i = 0; i < n; i++) { + if (arr[i] % 2 == 0) { + even++; + } else { + odd++; + } + } + int[] result = { odd, even }; + return result; +} +``` + +### C++ +```cpp +vector countOddEven(int arr[], int sizeof_array) { + int odd = 0, even = 0; + for (int i = 0; i < sizeof_array; i++) { + if (arr[i] % 2 == 0) { + even++; + } else { + odd++; + } + } + vector result = { odd, even }; + return result; +} +``` + +### C +```c +void countOddEven(int arr[], int sizeof_array, int *odd, int *even) { + *odd = 0; + *even = 0; + for (int i = 0; i < sizeof_array; i++) { + if (arr[i] % 2 == 0) { + (*even)++; + } else { + (*odd)++; + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0042.md b/dsa-solutions/gfg-solutions/Basic/0042.md new file mode 100644 index 000000000..3e54b74cb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0042.md @@ -0,0 +1,167 @@ +--- +id: implement-queue-linked-list +title: Implement Queue using Linked List +sidebar_label: 0042 Implement Queue with Linked List +tags: +- Queue +- Linked List +- Data Structures +- Implementation +- C +- Python +- Java +- C++ +description: "This document covers the implementation of a Queue data structure using a Linked List in various programming languages." +--- + +## Problem + +Implement a Queue using Linked List. +A Query Q is of 2 Types +- 1 x (a query of this type means pushing 'x' into the queue) +- 2 (a query of this type means to pop an element from the queue and print the poped element) + +### Examples: +**Example 1:** +``` +Input: +Q = 5 +Queries = 1 2 1 3 2 1 4 2 +Output: 2 3 +Explanation: n the first testcase +1 2 the queue will be {2} +1 3 the queue will be {2 3} +2 poped element will be 2 the + queue will be {3} +1 4 the queue will be {3 4} +2 poped element will be 3. +``` + +**Example 2:** +``` +Input: +Q = 4 +Queries = 1 2 2 2 1 3 +Output: 2 -1 +Explanation: In the second testcase +1 2 the queue will be {2} +2 poped element will be {2} then + the queue will be empty. +2 the queue is empty and hence -1 +1 3 the queue will be {3}. +``` + +### Your task: + +Complete the function **push()** which takes an integer as input parameter and **pop()** which will remove and return an element(-1 if queue is empty). + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0<=a[i]<=10^5$ + +## Solution +### Python +```python +def __init__(self): + self.stack1 = [] + self.stack2 = [] + +def push(self, item): + self.stack1.append(item) + +def pop(self): + if not self.stack2: + while self.stack1: + self.stack2.append(self.stack1.pop()) + if self.stack2: + return self.stack2.pop() + else: + return -1 +``` + +### Java +```java +public MyQueue() { + this.front = null; + this.rear = null; +} + +void push(int a) { + QueueNode newNode = new QueueNode(a); + if (this.rear == null) { + this.front = newNode; + this.rear = newNode; + } + else { + this.rear.next = newNode; + this.rear = newNode; + } +} + +int pop() { + if (this.front == null) + return -1; + int poppedValue = this.front.data; + this.front = this.front.next; + if (this.front == null) + this.rear = null; + return poppedValue; +} +``` + +### C++ +```cpp +void MyQueue:: push(int x) { + QueueNode* newNode = new QueueNode(x); + if (rear == nullptr) { + front = newNode; + rear = newNode; + } + else { + rear->next = newNode; + rear = newNode; + } +} + +int MyQueue :: pop() { + if (front == nullptr) + return -1; + int poppedValue = front->data; + QueueNode* temp = front; + front = front->next; + delete temp; + if (front == nullptr) + rear = nullptr; + return poppedValue; +} +``` + +### C +```c +void push(struct Queue* q, int k) { + struct Node* newnode = newNode(k); + if (q->rear == NULL) { + q->front = q->rear = newnode; + return; + } + q->rear->next = newnode; + q->rear = newnode; +} + +void pop(struct Queue* q) { + if (q->front == NULL) + return -1; + struct Node* temp = q->front; + q->front = q->front->next; + if (q->front == NULL) + q->rear = NULL; + free(temp); +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ diff --git a/dsa-solutions/gfg-solutions/Basic/0043.md b/dsa-solutions/gfg-solutions/Basic/0043.md new file mode 100644 index 000000000..2fd65e94c --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0043.md @@ -0,0 +1,87 @@ +--- +id: max-min +title: Max Min +sidebar_label: 0043 Max Min +tags: +- Arrays +- Python +- Java +- C++ +- C +description: "This document covers methods to find the maximum and minimum elements in an array using various programming languages." +--- + +## Problem + +Given an array **A** of size **N** of integers. Your task is to find the sum of minimum and maximum element in the array. + +### Examples: +**Example 1:** +``` +Input: +N = 5 +A[] = {-2, 1, -4, 5, 3} +Output: 1 +Explanation: min = -4, max = 5. Sum = -4 + 5 = 1 +``` + +**Example 2:** +``` +Input: +N = 4 +A[] = {1, 3, 4, 1} +Output: 5 +Explanation: min = 1, max = 4. Sum = 1 + 4 = 5 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **findSum()** which takes the array **A[]** and its size **N** as inputs and returns the summation of minimum and maximum element of the array. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $-10^9 <= A_i <= 10^9$ + +## Solution +### Python +```python +def findSum(self,A,N): + A.sort() + minmax = A[0]+A[-1] + return minmax +``` + +### Java +```java +public static int findSum(int A[],int N) { + Arrays.sort(A); + int minmax = A[0] + A[N - 1]; + return minmax; +} +``` + +### C++ +```cpp +int findSum(int A[], int N) { + sort(A, A + N); + int minmax = A[0] + A[N - 1]; + return minmax; +} +``` + +### C +```c +void rotate(int arr[], int n) { + int last_el = arr[n - 1]; + for (int i = n - 1; i > 0; i--) + arr[i] = arr[i - 1]; + arr[0] = last_el; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0044.md b/dsa-solutions/gfg-solutions/Basic/0044.md new file mode 100644 index 000000000..d7c83a3d7 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0044.md @@ -0,0 +1,102 @@ +--- +id: bit-difference +title: Bit Difference +sidebar_label: 0044 Bit Difference +tags: +- Bit Manipulation +- C +- Python +- Java +- C++ +description: "This document explains how to convert A to B using bit manipulation." +--- + +## Problem + +You are given two numbers **A** and **B**. The task is to count the number of bits needed to be flipped to convert A to B. + +### Examples: +**Example 1:** +``` +Input: A = 10, B = 20 +Output: 4 +Explanation: +A = 01010 +B = 10100 +As we can see, the bits of A that need to be flipped are 01010. If we flip these bits, we get 10100, which is B. +``` + +**Example 2:** +``` +Input: A = 20, B = 25 +Output: 3 +Explanation: +A = 10100 +B = 11001 +As we can see, the bits of A that need to be flipped are 10100. If we flip these bits, we get 11001, which is B. +``` + +### Your task: + +The task is to complete the function **countBitsFlip()** that takes **A** and **B** as parameters and returns the count of the number of bits to be flipped to convert A to B. + +- **Expected Time Complexity:** $O(log N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=A,B<=10^6$ + +## Solution +### Python +```python +def countBitsFlip(self,a,b): + xor_result = a ^ b + count = 0 + while xor_result != 0: + xor_result = xor_result & (xor_result - 1) + count += 1 + return count +``` + +### Java +```java +public static int countBitsFlip(int a, int b){ + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +### C++ +```cpp +int countBitsFlip(int a, int b){ + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +### C +```c +int countBitsFlip(int a, int b) { + int xorResult = a ^ b; + int count = 0; + while (xorResult != 0) { + xorResult = xorResult & (xorResult - 1); + count++; + } + return count; +} +``` + +- **Time Complexity:** $O(log N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0045.md b/dsa-solutions/gfg-solutions/Basic/0045.md new file mode 100644 index 000000000..d61a1bcc1 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0045.md @@ -0,0 +1,158 @@ +--- +id: find-smallest-second-smallest-element-in-array +title: Find the Smallest and Second Smallest Element in an Array +sidebar_label: 0045 Find the Smallest and Second Smallest Element in an Array +tags: +- Arrays +- Python +- Java +- C++ +- C +description: "This document covers methods to find the smallest and second smallest elements in an array using various programming languages." +--- + +## Problem + +Given an array of integers, your task is to find the smallest and second smallest element in the array. If smallest and second smallest do not exist, print **-1**. + +### Examples: +**Example 1:** +``` +Input : +5 +2 4 3 5 6 +Output : +2 3 +Explanation: +2 and 3 are respectively the smallest and second smallest elements in the array. +``` + +**Example 2:** +``` +Input : +6 +1 2 1 3 6 7 +Output : +1 2 +Explanation: +1 and 2 are respectively the smallest and second smallest elements in the array. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **minAnd2ndMin()** which takes the array **A[]** and its size **N** as inputs and returns a vector containing the smallest and second smallest element if possible, else return **{-1,-1}**. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=A[i]<=10^5$ + +## Solution +### Python +```python +def minAnd2ndMin(a, n): + if n < 2: + return [-1, -1] + + first_min = float('inf') + second_min = float('inf') + + for num in a: + if num < first_min: + second_min = first_min + first_min = num + elif num < second_min and num != first_min: + second_min = num + + if second_min == float('inf'): + return [-1, -1] + else: + return [first_min, second_min] +``` + +### Java +```java +public long[] minAnd2ndMin(long a[], long n) { + if (n < 2) { + return new long[]{-1, -1}; + } + long first_min = Long.MAX_VALUE; + long second_min = Long.MAX_VALUE; + for (long num : a) { + if (num < first_min) { + second_min = first_min; + first_min = num; + } + else if (num < second_min && num != first_min) { + second_min = num; + } + } + if (second_min == Long.MAX_VALUE) { + return new long[]{-1, -1}; + } + else { + return new long[]{first_min, second_min}; + } +} +``` + +### C++ +```cpp +vector minAnd2ndMin(int a[], int n) { + if (n < 2) { + return {-1, -1}; + } + int first_min = INT_MAX; + int second_min = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] < first_min) { + second_min = first_min; + first_min = a[i]; + } else if (a[i] < second_min && a[i] != first_min) { + second_min = a[i]; + } + } + if (second_min == INT_MAX) { + return {-1, -1}; + } + else { + return {first_min, second_min}; + } +} +``` + +### C +```c +void minAnd2ndMin(int a[], int n, int result[2]) { + if (n < 2) { + result[0] = -1; + result[1] = -1; + return; + } + int first_min = INT_MAX; + int second_min = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] < first_min) { + second_min = first_min; + first_min = a[i]; + } + else if (a[i] < second_min && a[i] != first_min) { + second_min = a[i]; + } + } + if (second_min == INT_MAX) { + result[0] = -1; + result[1] = -1; + } + else { + result[0] = first_min; + result[1] = second_min; + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0046.md b/dsa-solutions/gfg-solutions/Basic/0046.md new file mode 100644 index 000000000..5b4d98525 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0046.md @@ -0,0 +1,42 @@ +--- +id: cpp-hello-world +title: C++ Hello World +sidebar_label: 0046 C++ Hello World +tags: +- C++ +- Programming +- Basics +- Hello World +description: "This document demonstrates how to write a 'Hello, World!' program in C++." +--- + +## Problem + +Let's begin your journey towards coding with the very first question of the coding world. Your task is to write code that prints **Hello World**. + +### Examples: +**Example 1:** +``` +Input: +No Input +Output: +Hello World +``` + +### Your task: + +In the function **helloWorld()**, output a line "Hello World" (without quotes). + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +## Solution +### C++ +```cpp +void helloWorld() { + cout<<"Hello World"< int: + total_sum = n * (n + 1) // 2 + array_sum = sum(arr) + return total_sum - array_sum +``` + +### Java +```java +public static int missingNumber(int n, int[] arr) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for(int i = 0; i &arr) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for (int i = 0; i < arr.size(); i++) { + array_sum += arr[i]; + } + int result = total_sum - array_sum; + return result; +} +``` + +### C +```c +int missingNumber(int n, int arr[], int size) { + int total_sum = n * (n + 1) / 2; + int array_sum = 0; + for (int i = 0; i < size; i++) { + array_sum += arr[i]; + } + int result = total_sum - array_sum; + return result; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0049.md b/dsa-solutions/gfg-solutions/Basic/0049.md new file mode 100644 index 000000000..ac307aaf3 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0049.md @@ -0,0 +1,115 @@ +--- +id: closest-number +title: Closest Number +sidebar_label: 0049 Closest Number +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the closest number to a given target in an array in various programming languages." +--- + +## Problem + +Given two integers **N** and **M**. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having **maximum absolute value**. + +### Examples: +**Example 1:** +``` +Input: +N = 13 , M = 4 +Output: +12 +Explanation: +12 is the Closest Number to 13 which is divisible by 4. +``` + +**Example 2:** +``` +Input: +N = -15 , M = 6 +Output: +-18 +Explanation: +-12 and -18 are both similarly close to -15 and divisible by 6. but -18 has the maximum absolute value. So, Output is -18 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **closestNumber()** which takes an Integer n as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $-10^5 <= N <= 10^5$ + +## Solution +### Python +```python +def closestNumber(self, N , M): + if M == 0: + return None + quotient = N // M + lower_multiple = M * quotient + upper_multiple = M * (quotient + 1) + if abs(N - lower_multiple) < abs(N - upper_multiple): + return lower_multiple + elif abs(N - upper_multiple) < abs(N - lower_multiple): + return upper_multiple + else: + return max(lower_multiple, upper_multiple, key=abs) +``` + +### Java +```java +static int closestNumber(int N , int M) { + int i=0; + while(true){ + if((N-i)%M==0) + return N-i; + else if((N+i)%M==0) + return N+i; + else + i++; + } +} +``` + +### C++ +```cpp +int closestNumber(int N, int M) { + int r = N % M; + if (r == 0) { + return N; + } + else if (r <= M / 2) { + return N - r; + } + else { + return N + (M - r); + } +} +``` + +### C +```c +int closestNumber(int N, int M) { + int r = N % M; + if (r == 0) { + return N; + } + else if (r <= M / 2) { + return N - r; + } + else { + return N + (M - r); + } +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0050.md b/dsa-solutions/gfg-solutions/Basic/0050.md new file mode 100644 index 000000000..6c2116ef3 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0050.md @@ -0,0 +1,97 @@ +--- +id: node-at-given-index-linked-list +title: Node at Given Index in Linked List +sidebar_label: 0047 Node at Given Index in Linked List +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to find the node at a given index in a linked list in various programming languages." +--- + +## Problem + +Given a singly linked list with N nodes and a number X. The task is to find the node at the given index (X)(1 based index) of linked list. + +### Input: + +First line of input contains number of testcases T. For each testcase, first line of input contains space seperated two integers, length of linked list and X. + +### Output: + +For each testcase, there will be single line of output containing data at Xth node. + +### Examples: + +**Input:** +``` +2 +6 5 +1 2 3 4 657 76 +10 2 +8 7 10 8 6 1 20 91 21 2 +``` + +**Output:** +``` +657 +7 +``` + +**Explanation:** +Testcase 1: Element at 5th index in the linked list is 657 (1-based indexing). + +### Your task: + +The task is to complete the function **GetNth()** which takes head reference and index as arguments and should return the data at Xth position in the linked list. + +### Constraints: + +- $1 <= T <= 30$ +- $1 <= N <= 100$ +- $X <= N$ +- $1 <= value <= 10^3$ + +## Solution +### Python +```python +def getNth(head, k): + temp = head + for _ in range(0,k-1): + temp = temp.next + return temp.data +``` + +### Java +```java +public static int getNth(Node node, int ind) { + Node temp = node; + for(int i=0; inext; + } + return current->data; +} +``` + +### C +```c +int GetNth(struct node* head, int index) { + struct node* current = head; + for (int i = 0; i < index; i++) { + current = current->next; + } + return current->data; +} +``` diff --git a/dsa-solutions/gfg-solutions/Basic/0051.md b/dsa-solutions/gfg-solutions/Basic/0051.md new file mode 100644 index 000000000..8d2e74eae --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0051.md @@ -0,0 +1,171 @@ +--- +id: uncommon-characters +title: Uncommon Characters +sidebar_label: 0051 Uncommon Characters +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to find uncommon characters between two strings in various programming languages." +--- + +## Problem + +Given two strings A and B consisting of lowercase english characters. Find the characters that are not common in the two strings. + +**Note:** Return the string in sorted order. + +### Examples: +**Example 1:** +``` +Input: +A = geeksforgeeks +B = geeksquiz +Output: fioqruz +Explanation: +The characters 'f', 'i', 'o', 'q', 'r', 'u','z' are either present in A or B, but not in both. +``` + +**Example 2:** +``` +Input: +A = characters +B = alphabets +Output: bclpr +Explanation: The characters 'b','c','l','p','r' are either present in A or B, but not in both. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **UncommonChars()** which takes strings A and B as input parameters and returns a string that contains all the uncommon characters in sorted order. If no such character exists return "-1". + +- **Expected Time Complexity:** $O(M+N)$, where M and N are the sizes of A and B respectively. +- **Expected Auxiliary Space:** $O(M+N)$ + +### Constraints: + +- $1<=M,N<=10^4$ + +String may contain duplicate characters. + +## Solution +### Python +```python +def UncommonChars(self, A, B): + count_A = Counter(A) + count_B = Counter(B) + uncommon_chars = [ + for char in count_A: + if char not in count_B: + uncommon_chars.append(char) + for char in count_B: + if char not in count_A: + uncommon_chars.append(char) + uncommon_chars.sort() + if not uncommon_chars: + return "-1" + else: + return ''.join(uncommon_chars) +``` + +### Java +```java +String UncommonChars(String A, String B) { + Set setA = new HashSet<>(); + Set setB = new HashSet<>(); + for (char ch : A.toCharArray()) { + setA.add(ch); + } + for (char ch : B.toCharArray()) { + setB.add(ch); + Set uniqueChars = new HashSet<>(); + for (char ch : setA) { + if (!setB.contains(ch)) { + uniqueChars.add(ch); + } + } + for (char ch : setB) { + if (!setA.contains(ch)) { + uniqueChars.add(ch); + } + } + List sortedList = new ArrayList<>(uniqueChars); + Collections.sort(sortedList); + StringBuilder builder = new StringBuilder(); + for (char ch : sortedList) { + builder.append(ch); + } + String result = builder.toString(); + if (result.isEmpty()) { + return "-1"; + } + return result; +} +``` + +### C++ +```cpp +string UncommonChars(string A, string B) { + unordered_set setA; + unordered_set setB; + for (char ch : A) { + setA.insert(ch); + for (char ch : B) { + setB.insert(ch); + } + unordered_set uniqueChars; + for (char ch : setA) { + if (setB.find(ch) == setB.end()) { + uniqueChars.insert(ch); + } + } + for (char ch : setB) { + if (setA.find(ch) == setA.end()) { + uniqueChars.insert(ch); + } + } + vector sortedList(uniqueChars.begin(), uniqueChars.end()); + sort(sortedList.begin(), sortedList.end()); + string result(sortedList.begin(), sortedList.end()); + if (result.empty()) { + return "-1"; + } + return result; +} +``` + +### C +```c +char* UncommonChars(const char* A, const char* B) { + int map[26] = {0}; + for (int i = 0; A[i] != '\0'; ++i) { + map[A[i] - 'a'] = 1; + } + for (int i = 0; B[i] != '\0'; ++i) { + if (map[B[i] - 'a'] == 1 || map[B[i] - 'a'] == -1) { + map[B[i] - 'a'] = -1; + } else { + map[B[i] - 'a'] = 2; + } + } + char* result = (char*)malloc(27 * sizeof(char)); + int index = 0; + for (int i = 0; i < 26; ++i) { + if (map[i] > 0) { + result[index++] = 'a' + i; + } + } + result[index] = '\0'; + if (index == 0) { + free(result); + result = (char*)malloc(3 * sizeof(char)); + strcpy(result, "-1"); + } + return result; +} +``` + +- **Time Complexity:** $O(M+N)$ +- **Auxiliary Space:** $O(M+N)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0052.md b/dsa-solutions/gfg-solutions/Basic/0052.md new file mode 100644 index 000000000..ca3152a15 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0052.md @@ -0,0 +1,117 @@ +--- +id: search-node-bst +title: Search a Node in BST +sidebar_label: 0052 Search a Node in BST +tags: +- Binary Search Tree +- Python +- Java +- C++ +- C +description: "This document covers methods to search for a node in a Binary Search Tree (BST) in various programming languages." +--- + +## Problem + +Given a **Binary Search Tree** and a node value X, find if the node with value X is present in the BST or not. + +### Examples: +**Example 1:** +``` +Input: + 2 + \ + 81 + / \ + 42 87 + \ \ + 66 90 + / + 45 +X = 87 +Output: 1 +Explanation: As 87 is present in the given nodes , so the output will be 1. +``` + +**Example 2:** +``` +Input: + 6 + \ + 8 + / \ + 7 9 +X = 11 +Output: 0 +Explanation: As 11 is not present in the given nodes , so the output will be 0. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **search()** which returns true if the node with value x is present in the BSTelse returns false. + +- **Expected Time Complexity:** $O$(Height of the BST) +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=$Number of Nodes$<=10^5$ + +## Solution +### Python +```python +def search(self, node, x): + if node is None: + return False + if x == node.data: + return True + elif x < node.data: + return self.search(node.left, x) + else: + return self.search(node.right, x) +``` + +### Java +```java +boolean search(Node root, int x) { + if (root == null) + return false; + if (x == root.data) + return true; + else if (x < root.data) + return search(root.left, x); + else + return search(root.right, x); +} +``` + +### C++ +```cpp +bool search(Node* root, int x) { + if (root == nullptr) + return false; + if (x == root->data) + return true; + else if (x < root->data) + return search(root->left, x); + else + return search(root->right, x); +} +``` + +### C +```c +bool search(struct Node* root, int x) { + if (root == NULL) + return false; + if (x == root->data) + return true; + else if (x < root->data) + return search(root->left, x); + else + return search(root->right, x); +} +``` + +- **Time Complexity:** $O$(Height of the BST) +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0053.md b/dsa-solutions/gfg-solutions/Basic/0053.md new file mode 100644 index 000000000..19cc7c9fb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0053.md @@ -0,0 +1,87 @@ +--- +id: product-of-array-elements +title: Product of Array Elements +sidebar_label: 0053 Product of Array Elements +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the product of all elements in an array in various programming languages." +--- + +## Problem + +This is a functional problem. Your task is to return the product of array elements under a given modulo. + +The **modulo operation** finds the remainder after the division of one number by another. For example, K(mod(m))=K%m= remainder obtained when K is divided by m + +### Examples: +**Example 1:** +``` +Input: +1 +4 +1 2 3 4 + +Output: +24 +``` + +### Input: + +The first line of input contains T denoting the number of test cases. Then each of the T lines contains a single positive integer N denotes the number of elements in the array. The next line contains 'N' integer elements of the array. + +### Output: +Return the product of array elements under a given modulo. +That is, return (Array[0]*Array[1]*Array[2]...*Array[n])%modulo. + +### Constraints: + +- $1<=T<=200$ +- $1<=N<=10^5$ +- $1<=ar[i]<=10^5$ + +## Solution +### Python +```python +def product(arr,n,mod): + product_result = 1 + for n in arr: + product_result = (product_result * n) % mod + return product_result +``` + +### Java +```java +public static Long product(Long arr[], Long mod, int n) { + long productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * arr[i]) % mod; + } + return productResult; +} +``` + +### C++ +```cpp +long long int product(int ar[], int n, long long int mod) { + long long int productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * ar[i]) % mod; + } + return productResult; +} +``` + +### C +```c +long long int product(int ar[], int n, long long int mod) { + long long int productResult = 1; + for (int i = 0; i < n; i++) { + productResult = (productResult * ar[i]) % mod; + } + return productResult; +} +``` diff --git a/dsa-solutions/gfg-solutions/Basic/0054.md b/dsa-solutions/gfg-solutions/Basic/0054.md new file mode 100644 index 000000000..d61b75891 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0054.md @@ -0,0 +1,125 @@ +--- +id: remove-consecutive-characters +title: Remove Consecutive Characters +sidebar_label: 0054 Remove Consecutive Characters +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove consecutive duplicate characters from a string in various programming languages." +--- + +## Problem + +Given a string S. For each index `i(1<=i<=N-1)`, erase it if s[i] is equal to s[i-1] in the string. + +### Examples: +**Example 1:** +``` +Input: +S = aabb +Output: ab +Explanation: 'a' at 2nd position is appearing 2nd time consecutively. Similiar explanation for b at 4th position. +``` + +**Example 2:** +``` +Input: +S = aabaa +Output: aba +Explanation: 'a' at 2nd position is appearing 2nd time consecutively. 'a' at fifth position is appearing 2nd time consecutively. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **removeConsecutiveCharacter()** which accepts a string as input parameter and returns modified string. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(|S|)$ + +### Constraints: + +- $1<=|S|<=10^5$ + +All characters are lowercase alphabets. + +## Solution +### Python +```python +def removeConsecutiveCharacter(self, S): + if len(S) == 0: + return "" + result = [] + result.append(S[0]) + for i in range(1, len(S)): + if S[i] != S[i - 1]: + result.append(S[i]) + return ''.join(result) +``` + +### Java +```java +public String removeConsecutiveCharacter(String S){ + if (S == null || S.length() == 0) { + return ""; + } + StringBuilder result = new StringBuilder(); + result.append(S.charAt(0)); + for (int i = 1; i < S.length(); i++) { + char currentChar = S.charAt(i); + char previousChar = result.charAt(result.length() - 1); + if (currentChar != previousChar) { + result.append(currentChar); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string removeConsecutiveCharacter(string S) { + if (S.empty()) { + return ""; + } + string result; + result.push_back(S[0]); + for (int i = 1; i < S.length(); i++) { + if (S[i] != result.back()) { + result.push_back(S[i]); + } + } + return result; +} +``` + +### C +```c +char* removeConsecutiveCharacter(const char* S) { + if (S == NULL || strlen(S) == 0) { + char* result = (char*) malloc(sizeof(char)); + result[0] = '\0'; + return result; + } + int len = strlen(S); + char* result = (char*) malloc((len + 1) * sizeof(char)); + if (result == NULL) { + return NULL; + } + int resultIndex = 0; + result[resultIndex++] = S[0]; + for (int i = 1; i < len; i++) { + if (S[i] != result[resultIndex - 1]) { + result[resultIndex++] = S[i]; + } + } + result[resultIndex] = '\0'; + return result; +} + +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(|S|)$ diff --git a/dsa-solutions/gfg-solutions/Basic/0055.md b/dsa-solutions/gfg-solutions/Basic/0055.md new file mode 100644 index 000000000..2a17815fb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0055.md @@ -0,0 +1,167 @@ +--- +id: middle-of-three +title: Middle of Three +sidebar_label: 0055 Middle of Three +tags: +- Algorithm +- Python +- Java +- C++ +- C +description: "This document covers methods to find the middle of three given numbers in various programming languages." +--- + +## Problem + +Given three distinct numbers A, B and C. Find the number with value in middle (Try to do it with minimum comparisons). + +### Examples: +**Example 1:** +``` +Input: +A = 978, B = 518, C = 300 +Output: +518 +Explanation: +Since 518>300 and 518<978, so 518 is the middle element. +``` + +**Example 2:** +``` +Input: +A = 162, B = 934, C = 200 +Output: +200 +Exaplanation: +Since 200>162 && 200<934, So, 200 is the middle element. +``` + +### Your task: + +You don't need to read input or print anything.Your task is to complete the function ***middle()*** which takes three integers A,B and C as input parameters and returns the number which has middle value. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=A,B,C<=10^9$ + +A,B,C are distinct. + +## Solution +### Python +```python +def middle(self,A,B,C): + if A > B: + if A > C: + if B > C: + return B + else: + return C + else: + return A + else: + if B > C: + if A > C: + return A + else: + return C + else: + return B +``` + +### Java +```java +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } else { + return A; + } + } + else { + if (B > C) { + if (A > C) {e + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +### C++ +```cpp +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } + else { + return A; + } + } + else { + if (B > C) { + if (A > C) { + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +### C +```c +int middle(int A, int B, int C){ + if (A > B) { + if (A > C) { + if (B > C) { + return B; + } else { + return C; + } + } + else { + return A; + } + } + else { + if (B > C) { + if (A > C) { + return A; + } + else { + return C; + } + } + else { + return B; + } + } +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0056.md b/dsa-solutions/gfg-solutions/Basic/0056.md new file mode 100644 index 000000000..585a868eb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0056.md @@ -0,0 +1,118 @@ +--- +id: replace-zeros-with-fives +title: Replace All 0's with 5 +sidebar_label: 0056 Replace All 0's with 5 +tags: +- Python +- Java +- C++ +- C +description: "This document covers methods to replace all occurrences of 0 with 5 in a given number in various programming languages." +--- + +## Problem + +You are given an integer N. You need to convert all zeroes of N to 5. + +### Examples: +**Example 1:** +``` +Input: +N = 1004 +Output: 1554 +Explanation: There are two zeroes in 1004 on replacing all zeroes with "5", the new number will be "1554". +``` + +**Example 2:** +``` +Input: +N = 121 +Output: 121 +Explanation: Since there are no zeroes in "121", the number remains as "121". +``` + +### Your task: + +Your task is to complete the function **convertFive()** which takes an integer N as an argument and replaces all zeros in the number N with 5. Your function should return the converted number. + +- **Expected Time Complexity:** $O(K)$, where K is the number of digits in N +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10000$ + +## Solution +### Python +```python +def convertFive(n): + n_str = str(n) + modified_digits = [] + for char in n_str: + if char == '0': + modified_digits.append('5') + else: + modified_digits.append(char) + modified_str = ''.join(modified_digits) + modified_n = int(modified_str) + return modified_n +``` + +### Java +```java +int convertfive(int num) { + String numStr = String.valueOf(num); + StringBuilder modifiedDigits = new StringBuilder(); + for (int i = 0; i < numStr.length(); i++) { + char ch = numStr.charAt(i); + if (ch == '0') { + modifiedDigits.append('5'); + } else { + modifiedDigits.append(ch); + } + } + int modifiednum = Integer.parseInt(modifiedDigits.toString()); + return modifiednum; +} +``` + +### C++ +```cpp +int convertFive(int n) { + string nStr = to_string(n); + string modifiedStr = ""; + for (char ch : nStr) { + if (ch == '0') { + modifiedStr += '5'; + } else { + modifiedStr += ch; + } + } + int modifiedN = stoi(modifiedStr); + return modifiedN; +} +``` + +### C +```c +int convertFive(int num) { + if (num == 0) { + return 5; + } + int result = 0; + int decimalPlace = 1; + while (num > 0) { + int digit = num % 10; + if (digit == 0) { + digit = 5; + } + result = digit * decimalPlace + result; + decimalPlace *= 10; + num /= 10; + } + return result; +} +``` + +- **Time Complexity:** $O(K)$, where K is the number of digits in N +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0057.md b/dsa-solutions/gfg-solutions/Basic/0057.md new file mode 100644 index 000000000..08f95ab95 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0057.md @@ -0,0 +1,167 @@ +--- +id: doubly-linked-list-insertion +title: Doubly Linked List Insertion at Given Position +sidebar_label: 0057 Doubly Linked List Insertion at Given Position +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to insert a node at a given position in a doubly linked list in various programming languages." +--- + +## Problem + +Given a doubly-linked list, a position p, and an integer x. The task is to add a new node with value x at the position just after pth node in the doubly linked list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 2<->4<->5 +p = 2, x = 6 +Output: 2 4 5 6 +Explanation: p = 2, and x = 6. So, 6 is inserted after p, i.e, at position 3 (0-based indexing). +``` + +**Example 2:** +``` +Input: +LinkedList: 1<->2<->3<->4 +p = 0, x = 44 +Output: 1 44 2 3 4 +Explanation: p = 0, and x = 44 . So, 44 is inserted after p, i.e, at position 1 (0-based indexing). +``` + +### Your task: + +The task is to complete the function **addNode()** which head reference, position and data to be inserted as the arguments, with no return type. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^4$ +- $0 <= p < N$ + +## Solution +### Python +```python +def addNode(head, p, data): + new_node = Node(data) + if head is None: + head = new_node + else: + temp = head + count = 0 + while temp.next is not None and count < p: + temp = temp.next + count += 1 + if temp.next is None: + temp.next = new_node + new_node.prev = temp + else: + new_node.next = temp.next + new_node.prev = temp + temp.next = new_node + if new_node.next is not None: + new_node.next.prev = new_node +``` + +### Java +```java +void addNode(Node head_ref, int pos, int data) { + Node new_node = new Node(data); + if (head_ref == null) { + head_ref = new_node; + } + else { + Node temp = head_ref; + int count = 0; + while (temp.next != null && count < pos) { + temp = temp.next; + count++; + } + if (temp.next == null) { + temp.next = new_node; + new_node.prev = temp; + } + else { + new_node.next = temp.next; + new_node.prev = temp; + temp.next = new_node; + if (new_node.next != null) { + new_node.next.prev = new_node; + } + } + } +} +``` + +### C++ +```cpp +void addNode(Node *head, int pos, int data) { + Node* new_node = new Node(data); + if (head == nullptr) { + head = new_node; + } + else { + Node* temp = head; + int count = 0; + while (temp->next != nullptr && count < pos) { + temp = temp->next; + count++; + } + if (temp->next == nullptr) { + temp->next = new_node; + new_node->prev = temp; + } + else { + new_node->next = temp->next; + new_node->prev = temp; + temp->next = new_node; + if (new_node->next != nullptr) { + new_node->next->prev = new_node; + } + } + } +} +``` + +### C +```c +void addNode(struct Node *head, int pos, int data) { + struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); + new_node->data = data; + new_node->prev = NULL; + new_node->next = NULL; + if (head == NULL) { + head = new_node; + } + else { + struct Node* temp = head; + int count = 0; + while (temp->next != NULL && count < pos) { + temp = temp->next; + count++; + } + if (temp->next == NULL) { + temp->next = new_node; + new_node->prev = temp; + } + else { + new_node->next = temp->next; + new_node->prev = temp; + temp->next = new_node; + if (new_node->next != NULL) { + new_node->next->prev = new_node; + } + } + } +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0058.md b/dsa-solutions/gfg-solutions/Basic/0058.md new file mode 100644 index 000000000..57829c23f --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0058.md @@ -0,0 +1,119 @@ +--- +id: repeated-character +title: Repeated Character +sidebar_label: 0058 Repeated Character +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to find the first repeated character in a string in various programming languages." +--- + +## Problem + +Given a string consisting of lowercase english alphabets. Find the repeated character present first in the string. + +**NOTE:** If there are no repeating characters return '#'. + +### Examples: +**Example 1:** +``` +Input: +S = "geeksforgeeks" +Output: g +Explanation: g, e, k and s are the repeating characters. Out of these, g occurs first. +``` + +**Example 2:** +``` +Input: +S = "abcde" +Output: -1 +Explanation: No repeating character present. (You need to return '#') +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstRep()** which takes the string S as input and returns the the first repeating character in the string. In case there's no repeating character present, return '#'. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=|S|<=10^5$ + +## Solution +### Python +```python +def firstRep(self, s): + char_count = {} + for index, char in enumerate(s): + if char in char_count: + char_count[char]['count'] += 1 + else: + char_count[char] = {'count': 1, 'index': index} + first_repeated = '#' + min_index = float('inf') + for char in s: + if char_count[char]['count'] > 1 and char_count[char]['index'] < min_index: + first_repeated = char + min_index = char_count[char]['index'] + return first_repeated +``` + +### Java +```java +char firstRep(String S) { + char []str=S.toCharArray(); + for(int i=0;im; + for(char c:s) { + m[c]++; + } + for(char c:s) { + if(m[c]>1) { + return c; + } + } + return '#'; +} +``` + +### C +```c +char firstRep(const char *s) { + Entry hashmap[256] = {0}; + int len = strlen(s); + for (int i = 0; i < len; i++) { + hashmap[s[i]].key = s[i]; + hashmap[s[i]].count++; + } + for (int i = 0; i < len; i++) { + if (hashmap[s[i]].count > 1) { + return s[i]; + } + } + return '#'; / +} +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0059.md b/dsa-solutions/gfg-solutions/Basic/0059.md new file mode 100644 index 000000000..79f4879bd --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0059.md @@ -0,0 +1,90 @@ +--- +id: exceptionally-odd +title: Exceptionally Odd +sidebar_label: 0059 Exceptionally Odd +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the element that occurs an odd number of times in an array in various programming languages." +--- + +## Problem + +Given an array of N positive integers where all numbers occur even number of times except one number which occurs odd number of times. Find the exceptional number. + +### Examples: +**Example 1:** +``` +Input: +N = 7 +Arr[] = {1, 2, 3, 2, 3, 1, 3} +Output: 3 +Explaination: 3 occurs three times. +``` + +**Example 2:** +``` +Input: +N = 7 +Arr[] = {5, 7, 2, 7, 5, 2, 5} +Output: 5 +Explaination: 5 occurs three times. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getOddOccurrence()** which takes **arr[]** and **n** as input parameters and returns the exceptional number. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=arr[i]<=10^6$ + +## Solution +### Python +```python +def getOddOccurrence(self, arr, n): + result = 0 + for num in arr: + result ^= num + return result +``` + +### Java +```java +int getOddOccurrence(int[] arr, int n) { + int result = 0; + for(int i = 0; i4->3 +Output: +Odd +Explanation: +The length of linked list is 3 which is odd. +``` + +**Example 2:** +``` +Input: +n = 6 +linked list = 12->52->10->47->95->0 +Output: +Even +Explanation: +The length of linked list is 6 which is even. +``` + +### Your task: + +Since this is a functional problem you don't have to worry about input, you just have to complete the function **isLengthEvenOrOdd()** which takes the head of the linked list as the input parameter and returns 0 if the length of the linked list is even otherwise returns 1. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 10^4$ +- $1 <=$ elements of the linked list $<= 10^3$ + +## Solution +### Python +```python +def isLengthEvenOrOdd(head): + count = 0 + temp = head + while temp is not None: + count+=1 + temp = temp.next + if count%2==0: + return 0 + else: + return 1 +``` + +### Java +```java +public int isLengthEvenOrOdd(Node head) { + int count = 0; + Node temp = head; + while(temp!=null) { + count+=1; + temp = temp.next; + } + if(count%2==0) + return 0; + else + return 1; +} +``` + +### C++ +```cpp +int isLengthEvenOrOdd(struct Node* head) { + int count = 0; + Node* temp = head; + while(temp!=nullptr) { + count+=1; + temp = temp->next; + } + if(count%2==0) + return 0; + else + return 1; +} +``` + +### C +```c +int isLengthEvenOrOdd(struct Node* head) { + int count = 0; + struct Node* temp = head; + while (temp != NULL) { + count += 1; + temp = temp->next; + } + if (count % 2 == 0) + return 0; + else + return 1; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0063.md b/dsa-solutions/gfg-solutions/Basic/0063.md new file mode 100644 index 000000000..184727f84 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0063.md @@ -0,0 +1,121 @@ +--- +id: find-position-of-set-bit +title: Find Position of Set Bit +sidebar_label: 0063 Find Position of Set Bit +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to find the position of the set bit in a number in various programming languages." +--- + +## Problem + +Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from LSB side in binary representation of the number. + +### Examples: +**Example 1:** +``` +Input: +N = 2 +Output: +2 +Explanation: +2 is represented as "10" in Binary. As we see there's only one set bit and it's in Position 2 and thus the +Output 2. +``` + +**Example 2:** +``` +Input: +N = 5 +Output: +-1 +Explanation: +5 is represented as "101" in Binary. As we see there's two set bits and thus the Output -1. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **findPosition()** which takes an integer N as input and returns the answer. + +- **Expected Time Complexity:** $O(log(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $0 <= N <= 10^8$ + +## Solution +### Python +```python +def findPosition(self, N): + if N == 0 or (N & (N - 1)) != 0: + return -1 + position = 1 + while N: + if N & 1: + return position + N >>= 1 + position += 1 + return -1 +``` + +### Java +```java +static int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +### C++ +```cpp +int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +### C +```c +int findPosition(int N) { + if (N == 0 || (N & (N - 1)) != 0) { + return -1; + } + int position = 1; + while (N != 0) { + if ((N & 1) != 0) { + return position; + } + N >>= 1; + position++; + } + return -1; +} +``` + +- **Time Complexity:** $O(log(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0064.md b/dsa-solutions/gfg-solutions/Basic/0064.md new file mode 100644 index 000000000..0465524d5 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0064.md @@ -0,0 +1,174 @@ +--- +id: remove-common-characters-concatenate +title: Remove Common Characters and Concatenate +sidebar_label: 0064 Remove Common Characters and Concatenate +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove common characters from two strings and concatenate the remaining characters in various programming languages." +--- + +## Problem + +Given two strings s1 and s2. Modify both the strings such that all the common characters of s1 and s2 are to be removed and the uncommon characters of s1 and s2 are to be concatenated. + +**Note:** If all characters are removed print -1. + +### Examples: +**Example 1:** +``` +Input: +s1 = aacdb +s2 = gafd +Output: cbgf +Explanation: The common characters of s1 and s2 are: a, d. The uncommon characters of s1 and s2 are c, b, g and f. Thus the modified string with uncommon characters concatenated is cbgf. +``` + +**Example 2:** +``` +Input: +s1 = abcs +s2 = cxzca +Output: bsxz +Explanation: The common characters of s1 and s2 are: a,c. The uncommon characters of s1 and s2 are b,s,x and z. Thus the modified string with uncommon characters concatenated is bsxz. +``` + +### Your task: + +The task is to complete the function **concatenatedString()** which removes the common characters, concatenates, and returns the string. If all characters are removed then return -1. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +**Note:** N = |Length of Strings| + +### Constraints: + +- $1<=$|Length of Strings|$<=10^4$ + +## Solution +### Python +```python +def concatenatedString(self,s1,s2): + freq_s1 = {} + freq_s2 = {} + for char in s1: + freq_s1[char] = freq_s1.get(char, 0) + 1 + for char in s2: + freq_s2[char] = freq_s2.get(char, 0) + 1 + result = [] + for char in s1: + if char not in freq_s2: + result.append(char) + for char in s2: + if char not in freq_s1: + result.append(char) + if len(result) == 0: + return "-1" + else: + return "".join(result) +``` + +### Java +```java +public static String concatenatedString(String s1,String s2) { + Map freq_s1 = new HashMap<>(); + Map freq_s2 = new HashMap<>(); + for (char ch : s1.toCharArray()) { + freq_s1.put(ch, freq_s1.getOrDefault(ch, 0) + 1); + } + for (char ch : s2.toCharArray()) { + freq_s2.put(ch, freq_s2.getOrDefault(ch, 0) + 1); + } + StringBuilder result = new StringBuilder(); + for (char ch : s1.toCharArray()) { + if (!freq_s2.containsKey(ch)) { + result.append(ch); + } + } + for (char ch : s2.toCharArray()) { + if (!freq_s1.containsKey(ch)) { + result.append(ch); + } + } + if (result.length() == 0) { + return "-1"; + } + else { + return result.toString(); + } +} +``` + +### C++ +```cpp +string concatenatedString(string s1, string s2) { + unordered_map freq_s1; + unordered_map freq_s2; + for (char ch : s1) { + freq_s1[ch]++; + } + for (char ch : s2) { + freq_s2[ch]++; + } + string result; + for (char ch : s1) { + if (freq_s2.find(ch) == freq_s2.end()) { + result += ch; + } + } + for (char ch : s2) { + if (freq_s1.find(ch) == freq_s1.end()) { + result += ch; + } + } + if (result.empty()) { + return "-1"; + } + else { + return result; + } +} +``` + +### C +```c +char* concatenatedString(const char* s1, const char* s2) { + Entry freq_s1[256] = {0}; + Entry freq_s2[256] = {0}; + int len1 = strlen(s1); + int len2 = strlen(s2); + for (int i = 0; i < len1; i++) { + freq_s1[s1[i]].key = s1[i]; + freq_s1[s1[i]].count++; + } + for (int i = 0; i < len2; i++) { + freq_s2[s2[i]].key = s2[i]; + freq_s2[s2[i]].count++; + } + + char* result = (char*)malloc((len1 + len2 + 1) * sizeof(char)); + int idx = 0; + for (int i = 0; i < len1; i++) { + if (freq_s2[s1[i]].count == 0) { + result[idx++] = s1[i]; + } + } + for (int i = 0; i < len2; i++) { + if (freq_s1[s2[i]].count == 0) { + result[idx++] = s2[i]; + } + } + result[idx] = '\0'; + if (idx == 0) { + strcpy(result, "-1"); + } + return result; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0065.md b/dsa-solutions/gfg-solutions/Basic/0065.md new file mode 100644 index 000000000..242fd3b98 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0065.md @@ -0,0 +1,101 @@ +--- +id: pattern-1 +title: Pattern 1 +sidebar_label: 0065 Pattern 1 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print square pattern in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a square pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a square pattern with the help of * such that each * is space-separated in each line. + +### Examples: +**Example 1:** +``` +Input: +n = 3 +Output: +* * * +* * * +* * * +``` + +**Example 2:** +``` +Input: +n = 5 +Output: +* * * * * +* * * * * +* * * * * +* * * * * +* * * * * +``` + +### Your task: + +You don't need to input anything. Complete the function **printSquare()** which takes an integer n as the input parameter and print the pattern. + +- **Expected Time Complexity:** $O(N^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= n <= 1000$ + +## Solution +### Python +```python +def printSquare(self, N): + for i in range(N): + for j in range(N): + print("* ", end="") + print() +``` + +### Java +```java +void printSquare(int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printSquare(int n) { + for(int i = 0; i < n; i++) { + for(int j = 0; j < n; j++) { + cout << "* "; + } + cout << endl; + } +} +``` + +### C +```c +void printSquare(int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(N^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0066.md b/dsa-solutions/gfg-solutions/Basic/0066.md new file mode 100644 index 000000000..8b0e5748a --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0066.md @@ -0,0 +1,124 @@ +--- +id: anagram-of-string +title: Anagram of String +sidebar_label: 0066 Anagram of String +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if two strings are anagrams of each other in various programming languages." +--- + +## Problem + +Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters. + +### Examples: +**Example 1:** +``` +Input: +S1 = bcadeh +S2 = hea +Output: 3 +Explanation: We need to remove b, c and d from S1. +``` + +**Example 2:** +``` +Input: +S1 = cddgk +S2 = gcd +Output: 2 +Explanation: We need to remove d and k from S1. +``` + +### Your task: + +Complete the function **remAnagram()** which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted. + +- **Expected Time Complexity:** $O(max(|S1|, |S2|))$, where |S| = length of string S +- **Expected Auxiliary Space:** $O(26)$ + +### Constraints: + +- $1 <= |S1|, |S2| <= 10^5$ + +## Solution +### Python +```python +def remAnagram(str1,str2): + CHARS = 26 + count1 = [0]*CHARS + count2 = [0]*CHARS + i = 0 + while i < len(str1): + count1[ord(str1[i])-ord('a')] += 1 + i += 1 + i =0 + while i < len(str2): + count2[ord(str2[i])-ord('a')] += 1 + i += 1 + result = 0 + for i in range(26): + result += abs(count1[i] - count2[i]) + return result +``` + +### Java +```java +public int remAnagrams(String s,String s1) { + int count1[] = new int[26]; + int count2[] = new int[26]; + for (int i = 0; i < s.length() ; i++) + count1[s.charAt(i) -'a']++; + for (int i = 0; i < s1.length() ; i++) + count2[s1.charAt(i) -'a']++; + int result = 0; + for (int i = 0; i < 26; i++) + result += Math.abs(count1[i] - count2[i]); + return result; +} +``` + +### C++ +```cpp +int remAnagram(string str1, string str2) { + int count1[26] = {0}; + int count2[26] = {0}; + for (char c : str1) { + count1[c - 'a']++; + } + for (char c : str2) { + count2[c - 'a']++; + } + int result = 0; + for (int i = 0; i < 26; i++) { + result += abs(count1[i] - count2[i]); + } + return result; +} +``` + +### C +```c +int remAnagram(const char* str1, const char* str2) { + int count1[26] = {0}; + int count2[26] = {0}; + for (int i = 0; str1[i] != '\0'; i++) { + count1[str1[i] - 'a']++; + } + for (int i = 0; str2[i] != '\0'; i++) { + count2[str2[i] - 'a']++; + } + int result = 0; + for (int i = 0; i < 26; i++) { + result += abs(count1[i] - count2[i]); + } + return result; +} +``` + +- **Time Complexity:** $O(max(|S1|, |S2|))$ +- **Auxiliary Space:** $O(26)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0067.md b/dsa-solutions/gfg-solutions/Basic/0067.md new file mode 100644 index 000000000..2e2426454 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0067.md @@ -0,0 +1,116 @@ +--- +id: number-sparse-or-not +title: Number is Sparse or Not +sidebar_label: 0067 Number is Sparse or Not +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to determine if a number is sparse or not in various programming languages." +--- + +## Problem + +Given a number N. The task is to check whether it is sparse or not. A number is said to be a sparse number if no two or more consecutive bits are set in the binary representation. + +### Examples: +**Example 1:** +``` +Input: N = 2 +Output: 1 +Explanation: Binary Representation of 2 is 10, which is not having consecutive set bits. So, it is sparse number. +``` + +**Example 2:** +``` +Input: N = 3 +Output: 0 +Explanation: Binary Representation of 3 is 11, which is having consecutive set bits in it. So, it is not a sparse number. +``` + +### Your task: + +The task is to complete the function **checkSparse()** that takes n as a parameter and returns 1 if the number is sparse else returns 0. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ + +## Solution +### Python +```python +def isSparse(self,n): + if (n == 1): + return True + global prev + while(n > 0): + prev = n & 1 + n = n >> 1 + curr = n & 1 + if(prev == curr and prev == 1): + return False + prev = curr + return True +``` + +### Java +```java +public static boolean isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +### C++ +```cpp +bool isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +### C +```c +bool isSparse(int n) { + int prev; + if (n == 1) + return true; + while (n > 0) { + prev = n & 1; + n = n >> 1; + int curr = n & 1; + if (prev == curr && prev == 1) + return false; + prev = curr; + } + return true; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0068.md b/dsa-solutions/gfg-solutions/Basic/0068.md new file mode 100644 index 000000000..29e6082b4 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0068.md @@ -0,0 +1,111 @@ +--- +id: delete-alternate-nodes +title: Delete Alternate Nodes +sidebar_label: 0068 Delete Alternate Nodes +tags: +- Linked List +- Python +- Java +- C++ +- C +description: "This document covers methods to delete alternate nodes from a linked list in various programming languages." +--- + +## Problem + +Given a Singly Linked List of size n, delete all alternate nodes of the list. + +### Examples: +**Example 1:** +``` +Input: +LinkedList: 1->2->3->4->5->6 +Output: 1->3->5 +Explanation: Deleting alternate nodes results in the linked list with elements 1->3->5. +``` + +**Example 2:** +``` +Input: +LinkedList: 99->59->42->20 +Output: 99->42 +``` + +### Your task: + +Your task is to complete the function **deleteAlt()** which takes the **head** of the linked list in the input parameter and modifies the given linked list accordingly. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^5$ +- $1<=node.data<=10^6$ + +## Solution +### Python +```python +def deleteAlt(self, head): + if (head == None): + return + prev = head + now = head.next + while (prev != None and now != None): + prev.next = now.next + now = None + prev = prev.next + if (prev != None): + now = prev.next +``` + +### Java +```java +public void deleteAlternate (Node head){ + if (head == null) + return; + Node node = head; + while (node != null && node.next != null) { + node.next = node.next.next; + node = node.next; + } +} +``` + +### C++ +```cpp +void deleteAlt(struct Node *head){ + if (head == NULL) + return + Node *prev = head; + Node *node = head->next; + while (prev != NULL && node != NULL) { + prev->next = node->next; + delete(node); + prev = prev->next; + if (prev != NULL) + node = prev->next; + } +} +``` + +### C +```c +void deleteAlt(struct Node *head) { + if (head == NULL) + return; + struct Node *prev = head; + struct Node *node = head->next; + while (prev != NULL && node != NULL) { + prev->next = node->next; + free(node); + prev = prev->next; + if (prev != NULL) + node = prev->next; + } +} + +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0069.md b/dsa-solutions/gfg-solutions/Basic/0069.md new file mode 100644 index 000000000..8d16a190b --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0069.md @@ -0,0 +1,116 @@ +--- +id: ishaan-loves-chocolates +title: Ishaan Loves Chocolates +sidebar_label: 0069 Ishaan Loves Chocolates +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods for determining the tastiness level of the square which his sister gets in various programming languages." +--- + +## Problem + +As we know, Ishaan has a love for chocolates. He has bought a huge chocolate bar that contains N chocolate squares. Each of the squares has a tastiness level which is denoted by an array A[]. + +Ishaan can eat the first or the last square of the chocolate at once. Ishaan has a sister who loves chocolates too and she demands the last chocolate square. Now, Ishaan being greedy eats the more tasty square first. + +Determine the tastiness level of the square which his sister gets. + +### Examples: +**Example 1:** +``` +Input : arr[ ] = {5, 3, 1, 6, 9} +Output : 1 +Explanation: +Initially: 5 3 1 6 9 +In first step: 5 3 1 6 +In Second step: 5 3 1 +In Third step: 3 1 +In Fourth step: 1 +Return 1 +``` + +**Example 2:** +``` +Input : arr[ ] = {5, 9, 2, 6} +Output : 2 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **chocolates()** that takes an array (arr), sizeOfArray (n) and return the tastiness level of the square which his sister gets. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 ≤ A[i] ≤ 10^9$ + +## Solution +### Python +```python +def chocolates(self, n : int, arr : List[int]) -> int: + low = 0 + high = n-1 + while lowarr[high]: + low+=1 + else: + high-=1 + return arr[low] +``` + +### Java +```java +public static int chocolates(int n, int[] arr) { + int low = 0, high = n-1; + while(lowarr[high]) { + low++; + } + else { + high--; + } + } + return arr[low]; +} +``` + +### C++ +```cpp +int chocolates(int n, vector &arr) { + int low = 0, high = n-1; + while(lowarr[high]) { + low++; + } + else { + high--; + } + } + return arr[low]; +} +``` + +### C +```c +int chocolates(int arr[], int l, int r) { + while(larr[r]) { + l++; + } + else { + r--; + } + } + return arr[l]; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0070.md b/dsa-solutions/gfg-solutions/Basic/0070.md new file mode 100644 index 000000000..7a0cb30bf --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0070.md @@ -0,0 +1,100 @@ +--- +id: binary-to-decimal +title: Binary Number to Decimal Number +sidebar_label: 0070 Binary Number to Decimal Number +tags: +- Binary +- Python +- Java +- C++ +- C +description: "This document covers methods to convert a binary number to a decimal number in various programming languages." +--- + +## Problem + +Given a Binary Number B, find its decimal equivalent. + +### Examples: +**Example 1:** +``` +Input: B = 10001000 +Output: 136 +``` + +**Example 2:** +``` +Input: B = 101100 +Output: 44 +``` + +### Your task: + +You don't need to read or print anything. Your task is to complete the function **binary_to_decimal()** which takes the binary number as string input parameter and returns its decimal equivalent. + +- **Expected Time Complexity:** $O(K * Log(K))$, where K is number of bits in binary number. +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <=$ number of bits in binary number $<= 16$ + +## Solution +### Python +```python +def binary_to_decimal(self, str): + num = int(str); + dec_value = 0; + base = 1; + temp = num; + while(temp): + last_digit = temp % 10; + temp = int(temp / 10); + dec_value += last_digit * base; + base = base * 2; + return dec_value; +``` + +### Java +```java +public int binary_to_decimal(String str) { + int decValue = 0; + int base = 1; + for (int i = str.length() - 1; i >= 0; i--) { + if (str.charAt(i) == '1') { + decValue += base; + } + base = base * 2; + } + return decValue; +} +``` + +### C++ +```cpp +int binary_to_decimal(string str) { + unsigned long long num = bitset<64>(str).to_ullong(); + int decValue = static_cast(num); + return decValue; +} +``` + +### C +```c +int binary_to_decimal(char str[]) { + int len = strlen(str); + int dec_value = 0; + int base = 1; + int i; + for (i = len - 1; i >= 0; i--) { + if (str[i] == '1') { + dec_value += base; + } + base *= 2; + } + return dec_value; +} +``` + +- **Time Complexity:** $O(K * Log(K))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0071.md b/dsa-solutions/gfg-solutions/Basic/0071.md new file mode 100644 index 000000000..e571e57c4 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0071.md @@ -0,0 +1,124 @@ +--- +id: isogram-check +title: Check if a String is Isogram or Not +sidebar_label: 0071 Check if a String is Isogram or Not +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if a string is an isogram (a string with no repeating characters) in various programming languages." +--- + +## Problem + +Given a string S of lowercase alphabets, check if it is isogram or not. An Isogram is a string in which no letter occurs more than once. + +### Examples: +**Example 1:** +``` +Input: +S = machine +Output: 1 +Explanation: machine is an isogram as no letter has appeared twice. Hence we print 1. +``` + +**Example 2:** +``` +Input: +S = geeks +Output: 0 +Explanation: geeks is not an isogram as 'e' appears twice. Hence we print 0. +``` + +### Your task: + +This is a function problem. You only need to complete the function **isIsogram()** that takes a string as a parameter and returns either true or false. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O$(Number of distinct characters) + +Note: N = |S| + +### Constraints: + +- $1 <= |s| <= 10^3$ + +## Solution +### Python +```python +def isIsogram(self,s): + length = len(s) + mapHash = [0] * 26 + for i in range(length): + mapHash[ord(s[i]) - ord('a')] += 1 + if (mapHash[ord(s[i]) - ord('a')] > 1): + return False + return True +``` + +### Java +```java +static boolean isIsogram(String data){ + int length = data.length(); + int[] mapHash = new int[26]; + for (int i = 0; i < length; i++) { + char currentChar = data.charAt(i); + if (Character.isLetter(currentChar)) { + currentChar = Character.toLowerCase(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return false; + } + } + } + return true; +} +``` + +### C++ +```cpp +bool isIsogram(string s) { + int length = s.length(); + vector mapHash(26, 0); + for (int i = 0; i < length; i++) { + char currentChar = s[i]; + if (isalpha(currentChar)) { + currentChar = tolower(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return false; + } + } + } + return true; +} +``` + +### C +```c +int isIsogram(const char* s) { + int mapHash[26] = {0}; + int length = 0; + const char* ptr = s; + while (*ptr != '\0') { + length++; + ptr++; + } + for (int i = 0; i < length; i++) { + char currentChar = s[i]; + if (isalpha(currentChar)) { + currentChar = tolower(currentChar); + mapHash[currentChar - 'a']++; + if (mapHash[currentChar - 'a'] > 1) { + return 0; + } + } + } + return 1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O$(Number of distinct characters) \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0072.md b/dsa-solutions/gfg-solutions/Basic/0072.md new file mode 100644 index 000000000..87bf92035 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0072.md @@ -0,0 +1,110 @@ +--- +id: size-of-binary-tree +title: Size of Binary Tree +sidebar_label: 0072 Size of Binary Tree +tags: +- Binary Tree +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the size (number of nodes) of a binary tree in various programming languages." +--- + +## Problem + +Given a binary tree of size n, you have to count the number of nodes in it. For example, the count of nodes in the tree below is 4. + +``` + 1 + / \ + 10 39 + / +5 +``` + +### Examples: +**Example 1:** +``` +Input: +1 2 3 +Output: +3 +Explanation: +Given Tree is : + 1 + / \ + 2 3 +There are 3 nodes in the tree. +``` + +**Example 2:** +``` +Input: +10 5 9 N 1 3 6 +Output: +6 +Explanation: +Given Tree is : + 10 + / \ + 5 9 + \ / \ + 1 3 6 +There are 6 nodes in the tree. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **getSize()** which takes the tree head node and returns an integer representing the number of nodes in the tree. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(h)$, where h is the height of the binary tree + +### Constraints: + +- $1<=n<=10^5$ +- $1 <=$ values of nodes $<= 10^6$ + +## Solution +### Python +```python +def getSize(self, node : Optional['Node']) -> int: + if node is None: + return 0 + else: + return self.getSize(node.left) + 1 + self.getSize(node.right) +``` + +### Java +```java +public static int getSize(Node node) { + if(node==null) + return 0; + else + return getSize(node.left) + 1 + getSize(node.right); +} +``` + +### C++ +```cpp +int getSize(Node* node) { + if (node == nullptr) + return 0; + else + return getSize(node->left) + 1 + getSize(node->right); +} +``` + +### C +```c +int getSize(struct Node* node) { + if (node == NULL) + return 0; + else + return getSize(node->left) + 1 + getSize(node->right); +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(h)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0073.md b/dsa-solutions/gfg-solutions/Basic/0073.md new file mode 100644 index 000000000..843fc2bfb --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0073.md @@ -0,0 +1,163 @@ +--- +id: elements-in-the-range +title: Elements in the Range +sidebar_label: 0073 Elements in the Range +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find elements within a specified range in an array in various programming languages." +--- + +## Problem + +Given an array arr[] containing positive elements. A and B are two numbers defining a range. The task is to check if the array contains all elements in the given range. + +### Examples: +**Example 1:** +``` +Input: N = 7, A = 2, B = 5 +arr[] = {1, 4, 5, 2, 7, 8, 3} +Output: Yes +Explanation: It has elements between range 2-5 i.e 2,3,4,5 +``` + +**Example 2:** +``` +Input: N = 7, A = 2, B = 6 +arr[] = {1, 4, 5, 2, 7, 8, 3} +Output: No +Explanation: Array does not contain 6. +``` + +### Your task: + +This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function **check_elements()** that takes array arr, integer N, integer A, and integer B as parameters and returns the boolean True if array elements contain all elements in the given range else boolean False. + +**Note:** If the array contains all elements in the given range then driver code outputs Yes otherwise, it outputs No + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^7$ + +## Solution +### Python +```python +def check_elements(self, arr, n, A, B): + rangeV = B - A + for i in range(0, n): + if A <= abs(arr[i]) <= B: + z = abs(arr[i]) - A + if 0 <= z < n and arr[z] > 0: + arr[z] = arr[z] * -1 + count = 0 + for i in range(0, rangeV + 1): + if i >= n: + break + if arr[i] > 0: + return False + else: + count += 1 + if count != (rangeV + 1): + return False + return True +``` + +### Java +```java +boolean check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (Math.abs(arr[i]) >= A && Math.abs(arr[i]) <= B) { + int z = Math.abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +### C++ +```cpp +bool check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (abs(arr[i]) >= A && abs(arr[i]) <= B) { + int z = abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +### C +```c +bool check_elements(int arr[], int n, int A, int B) { + int rangeV = B - A; + for (int i = 0; i < n; i++) { + if (abs(arr[i]) >= A && abs(arr[i]) <= B) { + int z = abs(arr[i]) - A; + if (z >= 0 && z < n && arr[z] > 0) { + arr[z] = arr[z] * -1; + } + } + } + int count = 0; + for (int i = 0; i <= rangeV; i++) { + if (i >= n) { + break; + } + if (arr[i] > 0) { + return false; + } else { + count++; + } + } + if (count != (rangeV + 1)) { + return false; + } + return true; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0074.md b/dsa-solutions/gfg-solutions/Basic/0074.md new file mode 100644 index 000000000..cc67ad64f --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0074.md @@ -0,0 +1,99 @@ +--- +id: game-with-numbers +title: Game with Numbers +sidebar_label: 0074 Game with Numbers +tags: +- Number Games +- Python +- Java +- C++ +- C +description: "This document provides solutions for forming the array by xoring the consecutive elements in various programming languages." +--- + +## Problem + +You are given an array arr[], and you have to re-construct an array arr[]. + +The values in arr[] are obtained by doing Xor of consecutive elements in the array. + +### Examples: +**Example 1:** +``` +Input : n=5, arr[ ] = {10, 11, 1, 2, 3} +Output : 1 10 3 1 3 +Explanation: +At index 0, arr[0] xor arr[1] = 1 +At index 1, arr[1] xor arr[2] = 10 +At index 2, arr[2] xor arr[3] = 3 +... +At index 4, No element is left So, it will remain as +it is. +New Array will be {1, 10, 3, 1, 3}. +``` + +**Example 2:** +``` +Input : n=4, arr[ ] = {5, 9, 7, 6} +Output : 12 14 1 6 +Explanation: +At index 0, arr[0] xor arr[1] = 12 +At index 1, arr[1] xor arr[2] = 14 +At index 2, arr[2] xor arr[3] = 1 +At index 3, No element is left So, it will remain as it is. +New Array will be {12, 14, 1, 6}. +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **game_with_number()** that takes an array (arr), sizeOfArray (n) and return the array re-constructed array arr. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1<=arr[i]<=10^7$ + +## Solution +### Python +```python +def game_with_number (arr, n) : + for i in range(0,n-1): + arr[i] = arr[i]^arr[i+1] + return arr +``` + +### Java +```java +public static int[] game_with_number (int arr[], int n) { + for(int i = 0; i None: + print("Hello World") +``` + +### Java +```java +public static void printHello() { + System.out.println("Hello World"); +} +``` + +### C++ +```cpp +void printHello() { + cout<<"Hello World"; +} +``` + +### C +```c +void printHello() { + printf("Hello World\n"); +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ diff --git a/dsa-solutions/gfg-solutions/Basic/0077.md b/dsa-solutions/gfg-solutions/Basic/0077.md new file mode 100644 index 000000000..3e0027d4c --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0077.md @@ -0,0 +1,152 @@ +--- +id: angle-between-hour-and-minute-hand +title: Angle between Hour and Minute Hand +sidebar_label: 0077 Angle between Hour and Minute Hand +tags: +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the angle between the hour and minute hands of a clock at a given time in various programming languages." +--- + +## Problem + +Calculate the angle between the hour hand and minute hand. + +Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10. + +### Examples: +**Example 1:** +``` +Input: +H = 9 , M = 0 +Output: +90 +Explanation: +The minimum angle between hour and minute hand when the time is 9 is 90 degress. +``` + +**Example 2:** +``` +Input: +H = 3 , M = 30 +Output: +75 +Explanation: +The minimum angle between hour and minute hand when the time is 3:30 is 75 degress. +``` + +### Your task: + +You don't need to read, input, or print anything. Your task is to complete the function **getAngle()**, which takes 2 Integers H and M as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≤ H ≤ 12$ +- $0 ≤ M < 60$ + +H and M are Integers + +## Solution +### Python +```python +def getAngle(self, H , M): + if H < 0 or M < 0 or H > 12 or M > 60: + print('Wrong input') + return None + if H == 12: + H = 0 + if M == 60: + M = 0 + H += 1 + if H > 12: + H -= 12 + hour_angle = 0.5 * (H * 60 + M) + minute_angle = 6 * M + angle = abs(hour_angle - minute_angle) + angle = min(360 - angle, angle) + return int(angle) +``` + +### Java +```java +static int getAngle(int H , int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + System.out.println("Wrong input"); + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = Math.abs(hourAngle - minuteAngle); + angle = Math.min(360 - angle, angle); + return (int) angle; +} +``` + +### C++ +```cpp +int getAngle(int H , int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + cout << "Wrong input" << endl; + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = abs(hourAngle - minuteAngle); + angle = min(360 - angle, angle); + return static_cast(angle); +} +``` + +### C +```c +int getAngle(int H, int M) { + if (H < 0 || M < 0 || H > 12 || M > 60) { + printf("Wrong input\n"); + return -1; + } + if (H == 12) { + H = 0; + } + if (M == 60) { + M = 0; + H += 1; + if (H > 12) { + H -= 12; + } + } + double hourAngle = 0.5 * (H * 60 + M); + double minuteAngle = 6 * M; + double angle = fabs(hourAngle - minuteAngle); + angle = fmin(360 - angle, angle); + return (int)angle; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0078.md b/dsa-solutions/gfg-solutions/Basic/0078.md new file mode 100644 index 000000000..0692050a2 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0078.md @@ -0,0 +1,152 @@ +--- +id: sorted-matrix +title: Sorted Matrix +sidebar_label: 0078 Sorted Matrix +tags: +- Matrix +- Sorting +- Python +- Java +- C++ +- C +description: "This document covers methods to sort elements of a matrix in non-decreasing order in various programming languages." +--- + +## Problem + +Given an NxN matrix Mat. Sort all elements of the matrix. + +### Examples: +**Example 1:** +``` +Input: +N=4 +Mat=[[10,20,30,40], +[15,25,35,45] +[27,29,37,48] +[32,33,39,50]] +Output: +10 15 20 25 +27 29 30 32 +33 35 37 39 +40 45 48 50 +Explanation: +Sorting the matrix gives this result. +``` + +**Example 2:** +``` +Input: +N=3 +Mat=[[1,5,3],[2,8,7],[4,6,9]] +Output: +1 2 3 +4 5 6 +7 8 9 +Explanation: +Sorting the matrix gives this result. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **sortedMatrix()** which takes the integer N and the matrix Mat as input parameters and returns the sorted matrix. + +- **Expected Time Complexity:** $O(N^2LogN)$ +- **Expected Auxiliary Space:** $O(N^2)$ + +### Constraints: + +- $1<=N<=1000$ +- $1<=Mat[i][j]<=10^5$ + +## Solution +### Python +```python +def sortedMatrix(self,N,Mat): + temp = [0] * (N * N) + k = 0 + for i in range(0, N) : + for j in range(0, N) : + temp[k] = Mat[i][j] + k += 1 + temp.sort() + k = 0 + for i in range(0, N) : + for j in range(0, N) : + Mat[i][j] = temp[k] + k += 1 + return Mat +``` + +### Java +```java +int[][] sortedMatrix(int N, int Mat[][]) { + int[] temp = new int[N * N]; + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k] = Mat[i][j]; + k++; + } + } + Arrays.sort(temp); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k]; + k++; + } + } + return Mat; +} +``` + +### C++ +```cpp +vector> sortedMatrix(int N, vector> Mat) { + vector temp(N * N); + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k++] = Mat[i][j]; + } + } + sort(temp.begin(), temp.end()); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k++]; + } + } + return Mat; +} +``` + +### C +```c +int compare(const void *a, const void *b) { + return (*(int *)a - *(int *)b); +} + +int** sortedMatrix(int N, int **Mat) { + int *temp = (int *)malloc(N * N * sizeof(int)); + int k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + temp[k++] = Mat[i][j]; + } + } + qsort(temp, N * N, sizeof(int), compare); + k = 0; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + Mat[i][j] = temp[k++]; + } + } + free(temp); + return Mat; +} +``` + +- **Time Complexity:** $O(N^2LogN)$ +- **Auxiliary Space:** $O(N^2)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0079.md b/dsa-solutions/gfg-solutions/Basic/0079.md new file mode 100644 index 000000000..8b5694af2 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0079.md @@ -0,0 +1,116 @@ +--- +id: check-for-subsequence +title: Check for Subsequence +sidebar_label: 0079 Check for Subsequence +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to check if one string is a subsequence of another string in various programming languages." +--- + +## Problem + +Given two strings A and B, find if A is a subsequence of B. + +### Examples: +**Example 1:** +``` +Input: +A = AXY +B = YADXCP +Output: 0 +Explanation: A is not a subsequence of B as 'Y' appears before 'A'. +``` + +**Example 2:** +``` +Input: +A = gksrek +B = geeksforgeeks +Output: 1 +Explanation: A is a subsequence of B. +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **isSubSequence()** which takes A and B as input parameters and returns a boolean value denoting if A is a subsequence of B or not. + +- **Expected Time Complexity:** $O(N)$, where N is length of string B +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= |A|,|B| <=10^4$ + +## Solution +### Python +```python +def isSubSequence(self, A, B): + n, m = len(A), len(B) + i, j = 0, 0 + while (i < n and j < m): + if (A[i] == B[j]): + i += 1 + j += 1 + return i == n +``` + +### Java +```java +boolean isSubSequence(String A, String B){ + int n = A.length(); + int m = B.length(); + int i = 0, j = 0; + while (i < n && j < m) { + if (A.charAt(i) == B.charAt(j)) { + i++; + } + j++; + } + return i == n; +} +``` + +### C++ +```cpp +bool isSubSequence(string A, string B) { + int n = A.length(); + int m = B.length(); + int i = 0, j = 0; + while (i < n && j < m) { + if (A[i] == B[j]) { + i++; + } + j++; + } + return i == n; +} +``` + +### C +```c +int isSubSequence(const char *A, const char *B) { + int n = 0; + while (A[n] != '\0') { + n++; + } + int m = 0; + while (B[m] != '\0') { + m++; + } + int i = 0, j = 0; + while (i < n && j < m) { + if (A[i] == B[j]) { + i++; + } + j++; + } + return i == n; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0080.md b/dsa-solutions/gfg-solutions/Basic/0080.md new file mode 100644 index 000000000..4e3557444 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0080.md @@ -0,0 +1,110 @@ +--- +id: multiply-left-right-array-sum +title: Multiply Left and Right Array Sum +sidebar_label: 0080 Multiply Left and Right Array Sum +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the product of the left and right array sums for a given array in various programming languages." +--- + +## Problem + +Pitsy needs help with the given task by her teacher. The task is to divide an array into two sub-array (left and right) containing n/2 elements each and do the sum of the subarrays and then multiply both the subarrays. + +**Note:** If the length of the array is odd then the right half will contain one element more than the left half. + +### Examples: +**Example 1:** +``` +Input : arr[ ] = {1, 2, 3, 4} +Output : 21 +Explanation: +Sum up an array from index 0 to 1 = 3 +Sum up an array from index 2 to 3 = 7 +Their multiplication is 21. +``` + +**Example 2:** +``` +Input : arr[ ] = {1, 2} +Output : 2 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **multiply()** that takes an array (arr), sizeOfArray (n), and return the sum of the subarrays and then multiply both the subarrays. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≤ T ≤ 100$ +- $1 ≤ N ≤ 1000$ +- $1 ≤ A[i] ≤ 100$ + +## Solution +### Python +```python +def multiply (arr, n) : + sum_left, sum_right=0, 0 + for i in range(0, n//2): + sum_left = sum_left+arr[i] + for j in range(n//2, n): + sum_right = sum_right+arr[j] + result = sum_left*sum_right + return result +``` + +### Java +```java +public static int multiply (int arr[], int n) { + int sum_left=0, sum_right=0; + for(int i=0; i 0$ + +## Solution +### Python +```python +def fractionalNodes(head,k): + if (k <= 0 or head == None): + return None + fractionalNode = None + i = 0 + temp = head + while (temp != None): + if (i % k == 0): + if (fractionalNode == None): + fractionalNode = head + else: + fractionalNode = fractionalNode.next + i = i + 1 + temp = temp.next + return fractionalNode.data +``` + +### Java +```java +public static int nknode(Node head, int k) { + if (k <= 0 || head == null) + return -1; + Node fractionalNode = null; + int i = 0; + Node temp = head; + while (temp != null) { + if (i % k == 0) { + if (fractionalNode == null) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode.next; + } + } + i++; + temp = temp.next; + } + if (fractionalNode != null) { + return fractionalNode.data; + } + else { + return -1; + } +} +``` + +### C++ +```cpp +int fractional_node(struct Node *head, int k) { + if (k <= 0 || head == nullptr) + return -1; + Node* fractionalNode = nullptr; + int i = 0; + Node* temp = head; + while (temp != nullptr) { + if (i % k == 0) { + if (fractionalNode == nullptr) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode->next; + } + } + i++; + temp = temp->next; + } + if (fractionalNode != nullptr) { + return fractionalNode->data; + } + else { + return -1; + } +} +``` + +### C +```c +int fractional_node(struct Node *head, int k) { + if (k <= 0 || head == NULL) + return -1; + struct Node *fractionalNode = NULL; + int i = 0; + struct Node *temp = head; + while (temp != NULL) { + if (i % k == 0) { + if (fractionalNode == NULL) { + fractionalNode = head; + } else { + fractionalNode = fractionalNode->next; + } + } + i++; + temp = temp->next; + } + if (fractionalNode != NULL) { + return fractionalNode->data; + } + else { + return -1; + } +} +``` diff --git a/dsa-solutions/gfg-solutions/Basic/0083.md b/dsa-solutions/gfg-solutions/Basic/0083.md new file mode 100644 index 000000000..7a099cf12 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0083.md @@ -0,0 +1,158 @@ +--- +id: first-last-occurrences-x +title: First and Last Occurrences of X +sidebar_label: 0083 First and Last Occurrences of X +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the first and last occurrences of a specified element X in an array in various programming languages." +--- + +## Problem + +Given a sorted array having N elements, find the indices of the first and last occurrences of an element X in the given array. + +**Note:** If the number X is not found in the array, return '-1' as an array. + +### Examples: +**Example 1:** +``` +Input: +N = 4 , X = 3 +arr[] = { 1, 3, 3, 4 } +Output: +1 2 +Explanation: +For the above array, first occurence of X = 3 is at index = 1 and last occurence is at index = 2. +``` + +**Example 2:** +``` +Input: +N = 4, X = 5 +arr[] = { 1, 2, 3, 4 } +Output: +-1 +Explanation: +As 5 is not present in the array, so the answer is -1. +``` + +### Your task: + +ou don't need to read input or print anything. Complete the function **firstAndLast()** that takes the array arr, its size N and the value X as input parameters and returns a list of integers containing the indices of first and last occurence of X. + +- **Expected Time Complexity:** $O(log(N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0 <= arr[i], X <= 10^9$ + +## Solution +### Python +```python +def firstAndLast(self, arr, n, x): + first = -1 + last = -1 + for i in range(n): + if x != arr[i]: + continue + if first == -1: + first = i + last = i + if first != -1: + return [first, last] + else: + return [-1] +``` + +### Java +```java +public ArrayList firstAndLast(int arr[], int n, int x){ + ArrayList result = new ArrayList<>(); + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result.add(first); + result.add(last); + } + else { + result.add(-1); + } + return result; +} +``` + +### C++ +```cpp +vector firstAndLast(vector &arr, int n, int x) { + vector result; + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result.push_back(first); + result.push_back(last); + } + else { + result.push_back(-1); + } + return result; +} +``` + +### C +```c +int* firstAndLast(int *arr, int n, int x, int *resultSize) { + int *result = (int *)malloc(2 * sizeof(int)); + if (result == NULL) { + perror("Memory allocation failed"); + exit(EXIT_FAILURE); + } + int first = -1; + int last = -1; + for (int i = 0; i < n; i++) { + if (x != arr[i]) { + continue; + } + if (first == -1) { + first = i; + } + last = i; + } + if (first != -1) { + result[0] = first; + result[1] = last; + *resultSize = 2; + } + else { + result[0] = -1; + *resultSize = 1; + } + return result; +} +``` + +- **Time Complexity:** $O(log(N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0084.md b/dsa-solutions/gfg-solutions/Basic/0084.md new file mode 100644 index 000000000..093c0f3da --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0084.md @@ -0,0 +1,79 @@ +--- +id: maximum-money +title: Maximum Money +sidebar_label: 0084 Maximum Money +tags: +- Problem Solving +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the maximum amount of money that can be collected from a sequence of houses where every house has some amount of money in various programming languages." +--- + +## Problem + +Given a street of N houses (a row of houses), each house having K amount of money kept inside; now there is a thief who is going to steal this money but he has a constraint/rule that he cannot steal/rob two adjacent houses. Find the maximum money he can rob. + +### Examples: +**Example 1:** +``` +Input: +N = 5 , K = 10 +Output: +30 +Explanation: +The Robber can rob from the first, third and fifth houses which will result in 30. +``` + +**Example 2:** +``` +Input: +N = 2 , K = 12 +Output: +12 +Explanation: +The Robber can only rob from the first or second which will result in 12. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **maximizeMoney()** which takes 2 Integers N and K as input and returns the answer. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= N,K <= 10^3$ + +## Solution +### Python +```python +def maximizeMoney(self, N , K): + return ((N+1)//2)*K; +``` + +### Java +```java +static int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +### C++ +```cpp +int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +### C +```c +int maximizeMoney(int N , int K) { + return ((N+1)/2)*K; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0085.md b/dsa-solutions/gfg-solutions/Basic/0085.md new file mode 100644 index 000000000..b99f495d4 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0085.md @@ -0,0 +1,99 @@ +--- +id: pattern-5 +title: Pattern 5 +sidebar_label: 0085 Pattern 5 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to printinverted pyramid in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek build a star pattern. + +### Examples: +**Example 1:** +``` +Input: 5 +Output: +* * * * * +* * * * +* * * +* * +* +``` + +**Example 2:** +``` +Input: 3 +Output: +* * * +* * +* +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and prints the pattern. + +- **Expected Time Complexity:** $O(n^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<= n <= 100$ + +## Solution +### Python +```python +def printTriangle(self, N): + for i in range(1, N + 1): + for j in range(N, i - 1, -1): + print("* ", end="") + print() +``` + +### Java +```java +void printTriangle(int n) { + for(int i = 1; i<=n; i++) { + for(int j = n; j>=i; j--) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for(int i = 1; i<=n; i++) { + for(int j = n; j>=i; j--) { + cout<<"* "; + } + cout<= i; j--) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(n^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0086.md b/dsa-solutions/gfg-solutions/Basic/0086.md new file mode 100644 index 000000000..674300a5c --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0086.md @@ -0,0 +1,114 @@ +--- +id: balanced-array +title: Balanced Array +sidebar_label: 0086 Balanced Array +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to check if an array is balanced in various programming languages." +--- + +## Problem + +Given an array of even size N, task is to find minimum value that can be added to an element so that array become balanced. An array is balanced if the sum of the left half of the array elements is equal to the sum of right half. + +### Examples: +**Example 1:** +``` +Input: +N = 4 +arr[] = {1, 5, 3, 2} +Output: 1 +Explanation: +Sum of first 2 elements is 1 + 5 = 6, +Sum of last 2 elements is 3 + 2 = 5, +To make the array balanced you can add 1. +``` + +**Example 2:** +``` +Input: +N = 6 +arr[] = { 1, 2, 1, 2, 1, 3 } +Output: 2 +Explanation: +Sum of first 3 elements is 1 + 2 + 1 = 4, +Sum of last three elements is 2 + 1 + 3 = 6, +To make the array balanced you can add 2. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **minValueToBalance()** which takes the array a[] and N as inputs and returns the desired result. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $2<=N<=10^7$ +- $N\%2==0$ + +## Solution +### Python +```python +def minValueToBalance(self,a,n): + sum1 = 0 + for i in range( int(n / 2)): + sum1 += a[i] + sum2 = 0; + i = int(n / 2) + while i < n: + sum2 += a[i] + i = i + 1 + return abs(sum1 - sum2) +``` + +### Java +```java +long minValueToBalance(long a[] ,int n) { + long sum1 = 0; + for (int i = 0; i < n / 2; i++) + sum1 += a[i]; + long sum2 = 0; + for (int i = n/2; i < n; i++) + sum2 += a[i]; + return Math.abs(sum1 - sum2); + +} +``` + +### C++ +```cpp +int minValueToBalance(int a[], int n) { + int sum1 = 0; + for (int i = 0; i < n/2; i++) + sum1 += a[i]; + int sum2 = 0; + for (int i = n/2; i < n; i++) + sum2 += a[i]; + return abs(sum1 - sum2); +} +``` + +### C +```c +int minValueToBalance(int a[], int n) { + int sum1 = 0; + int sum2 = 0; + for (int i = 0; i < n / 2; i++) { + sum1 += a[i]; + } + for (int i = n / 2; i < n; i++) { + sum2 += a[i]; + } + int balanceValue = abs(sum1 - sum2); + return balanceValue; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0087.md b/dsa-solutions/gfg-solutions/Basic/0087.md new file mode 100644 index 000000000..b34e0789d --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0087.md @@ -0,0 +1,125 @@ +--- +id: product-max-first-min-second +title: Product of Maximum in First Array and Minimum in Second +sidebar_label: 0087 Product of Maximum in First Array and Minimum in Second +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the product of the maximum element in the first array and the minimum element in the second array in various programming languages." +--- + +## Problem + +Given two arrays of A and B respectively of sizes N1 and N2, the task is to calculate the product of the maximum element of the first array and minimum element of the second array. + +### Examples: +**Example 1:** +``` +Input : A[] = {5, 7, 9, 3, 6, 2}, + B[] = {1, 2, 6, -1, 0, 9} +Output : -9 +Explanation: +The first array is 5 7 9 3 6 2. +The max element among these elements is 9. +The second array is 1 2 6 -1 0 9. +The min element among these elements is -1. +The product of 9 and -1 is 9*-1=-9. + +``` + +**Example 2:** +``` +Input : A[] = {0, 0, 0, 0}, + B[] = {1, -1, 2} +Output : 0 +``` + +### Your task: + +This is a function problem. The input is already taken care of by the driver code. You only need to complete the function **find_multiplication()** that takes an array of integer (A), another array of integer (B), size of array A(n), size of array B(m) and return the product of the max element of the first array and the minimum element of the second array. The driver code takes care of the printing. + +- **Expected Time Complexity:** $O(N+M)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≤ N, M ≤ 10^6$ +- $-10^8 ≤ Ai, Bi ≤ 10^8$ + +## Solution +### Python +```python +def find_multiplication (self, arr, brr, n, m) : + max_arr = arr[0] + min_brr = brr[0] + for i in range(1, n): + if arr[i] > max_arr: + max_arr = arr[i] + for i in range(1, m): + if brr[i] < min_brr: + min_brr = brr[i] + return max_arr * min_brr +``` + +### Java +```java +public static long find_multiplication (int arr[], int brr[], int n, int m) { + int maxArr = arr[0]; + int minBrr = brr[0]; + for (int i = 1; i < n; ++i) { + if (arr[i] > maxArr) { + maxArr = arr[i]; + } + } + for (int i = 1; i < m; ++i) { + if (brr[i] < minBrr) { + minBrr = brr[i]; + } + } + return (long) maxArr * minBrr; +} +``` + +### C++ +```cpp +long long find_multiplication(int a[], int b[], int n, int m) { + int max_a = INT_MIN; + int min_b = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] > max_a) { + max_a = a[i]; + } + } + for (int i = 0; i < m; ++i) { + if (b[i] < min_b) { + min_b = b[i]; + } + } + return (long long) max_a * min_b; +} +``` + +### C +```c +long long find_multiplication(int a[], int b[], int n, int m) { + int max_a = INT_MIN; + int min_b = INT_MAX; + for (int i = 0; i < n; ++i) { + if (a[i] > max_a) { + max_a = a[i]; + } + } + for (int i = 0; i < m; ++i) { + if (b[i] < min_b) { + min_b = b[i]; + } + } + return (long long) max_a * min_b; +} +``` + +- **Time Complexity:** $O(N+M)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0088.md b/dsa-solutions/gfg-solutions/Basic/0088.md new file mode 100644 index 000000000..db1b8638a --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0088.md @@ -0,0 +1,134 @@ +--- +id: find-the-fine +title: Find the Fine +sidebar_label: 0088 Find the Fine +tags: +- Problem Solving +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate total fines based from the cars in various programming languages." +--- + +## Problem + +Given an array of penalties fine[], an array of car numbers car[], and also the date. The task is to find the total fine which will be collected on the given date. Fine is collected from odd-numbered cars on even dates and vice versa. + +### Examples: +**Example 1:** +``` +Input: +N = 4, date = 12 +car[] = {2375, 7682, 2325, 2352} +fine[] = {250, 500, 350, 200} +Output: +600 +Explantion: +The date is 12 (even), so we collect the fine from odd numbered cars. The odd numbered cars and the fines associated with them are as follows: +2375 -> 250 +2325 -> 350 +The sum of the fines is 250+350 = 600 +``` + +**Example 2:** +``` +Input: +N = 3, date = 8 +car[] = {2222, 2223, 2224} +fine[] = {200, 300, 400} +Output: +300 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **totalFine()** which takes the array car[] and fine[] its size N and an integer date as inputs and returns the total fine. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 <= Car_i <= 10^5$ +- $1 <= Date <= 10^5$ +- $1 <= Fine_i <= 10^5$ + +## Solution +### Python +```python +def totalFine(self, n, date, car, fine): + totalFine = 0 + for i in range(n): + if date % 2 == 0: + if car[i] % 2 != 0: + totalFine += fine[i] + else: + if car[i] % 2 == 0: + totalFine += fine[i] + return totalFine +``` + +### Java +```java +public long totalFine( long n, long date, long car[], long fine[]) { + long totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { / + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +### C++ +```cpp +long long int totalFine(int n, int date, int car[], int fine[]) { + long long int totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +### C +```c +long long int totalFine(int n, int date, int car[], int fine[]) { + long long int totalFine = 0; + for (int i = 0; i < n; i++) { + if (date % 2 == 0) { + if (car[i] % 2 != 0) { + totalFine += fine[i]; + } + } + else { + if (car[i] % 2 == 0) { + totalFine += fine[i]; + } + } + } + return totalFine; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0089.md b/dsa-solutions/gfg-solutions/Basic/0089.md new file mode 100644 index 000000000..128bf5f79 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0089.md @@ -0,0 +1,135 @@ +--- +id: ways-to-tile-a-floor +title: Ways To Tile A Floor +sidebar_label: 0089 Ways To Tile A Floor +tags: +- Dynamic Programming +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the number of ways to tile a floor of given dimensions using tiles of given sizes in various programming languages." +--- + +## Problem + +Given a floor of dimensions 2 x n and tiles of dimensions 2 x 1, the task is to find the number of ways the floor can be tiled. A tile can either be placed horizontally i.e as a 1 x 2 tile or vertically i.e as 2 x 1 tile. return the answer with modulo $10^9+7$. + +### Examples: +**Example 1:** +``` +Input: +n = 3 +Output: 3 +Explanation: +We need 3 tiles to tile the boardof size 2 x 3. +We can tile in following ways: +1) Place all 3 tiles vertically. +2) Place first tile verticallyand remaining 2 tiles horizontally. +3) Place first 2 tiles horizontally and remaining tiles vertically. +``` + +**Example 2:** +``` +Input: +n = 4 +Output:5 +Explanation: +For a 2 x 4 board, there are 5 ways +1) All 4 vertical +2) All 4 horizontal +3) First 2 vertical, remaining 2 horizontal. +4) First 2 horizontal, remaining2 vertical. +5) Corner 2 vertical, middle 2 horizontal. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **numberOfWays()** which takes an Integer n as input and returns the answer. + +- **Expected Time Complexity:** $O(n)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^5$ + +## Solution +### Python +```python +def numberOfWays(self, N): + if N == 1: + return 1 + elif N == 2: + return 2 + MOD = 1000000007 + dp = [0] * (N + 1) + dp[1] = 1 + dp[2] = 2 + for i in range(3, N + 1): + dp[i] = (dp[i-1] + dp[i-2]) % MOD + return dp[N] +``` + +### Java +```java +static int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + int MOD = 1000000007; + int[] dp = new int[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +### C++ +```cpp +int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + const int MOD = 1000000007; + int dp[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +### C +```c +int numberOfWays(int n) { + if (n == 1) { + return 1; + } + else if (n == 2) { + return 2; + } + const int MOD = 1000000007; + int dp[n + 1]; + dp[1] = 1; + dp[2] = 2; + for (int i = 3; i <= n; i++) { + dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; + } + return dp[n]; +} +``` + +- **Time Complexity:** $O(n)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0090.md b/dsa-solutions/gfg-solutions/Basic/0090.md new file mode 100644 index 000000000..271c62dbc --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0090.md @@ -0,0 +1,131 @@ +--- +id: index-first-1-sorted-array +title: Index of First 1 in a Sorted Array of 0s and 1s +sidebar_label: 0090 Index of First 1 in a Sorted Array of 0s and 1s +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the index of the first occurrence of 1 in a sorted array of 0s and 1s in various programming languages." +--- + +## Problem + +Given a sorted array consisting 0s and 1s. The task is to find the index of first 1 in the given array. + +NOTE: If one is not present then, return -1. + +### Examples: +**Example 1:** +``` +Input : +arr[] = {0, 0, 0, 0, 0, 0, 1, 1, 1, 1} +Output : +6 +Explanation: +The index of first 1 in the array is 6. +``` + +**Example 2:** +``` +Input : +arr[] = {0, 0, 0, 0} +Output : +-1 +Explanation: +1's are not present in the array. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstIndex()** which takes the array A[] and its size N as inputs and returns the index of first 1. If 1 is not present in the array then return -1. + +- **Expected Time Complexity:** $O(Log (N))$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ +- $0<=A_i<=1$ + +## Solution +### Python +```python +def firstIndex(self, arr, n): + low = 0 + high = n - 1 + first_one_index = -1 + while low <= high: + mid = (low + high) // 2 + if arr[mid] == 1: + first_one_index = mid + high = mid - 1 + else: + low = mid + 1 + return first_one_index +``` + +### Java +```java +public long firstIndex(long arr[], long n) { + long low = 0; + long high = n - 1; + long firstOneIndex = -1; + while (low <= high) { + long mid = (low + high) / 2; + if (arr[(int)mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +### C++ +```cpp +int firstIndex(int a[], int n) { + int low = 0; + int high = n - 1; + int firstOneIndex = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (a[mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +### C +```c +int firstIndex(int a[], int n) { + int low = 0; + int high = n - 1; + int firstOneIndex = -1; + while (low <= high) { + int mid = low + (high - low) / 2; + if (a[mid] == 1) { + firstOneIndex = mid; + high = mid - 1; + } + else { + low = mid + 1; + } + } + return firstOneIndex; +} +``` + +- **Time Complexity:** $O(Log (N))$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0091.md b/dsa-solutions/gfg-solutions/Basic/0091.md new file mode 100644 index 000000000..ff31182f9 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0091.md @@ -0,0 +1,114 @@ +--- +id: remove-character +title: Remove Character +sidebar_label: 0091 Remove Character +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to remove a characters from the first string that are present in the second string in various programming languages." +--- + +## Problem + +Given two strings string1 and string2, remove those characters from first string(string1) which are present in second string(string2). Both the strings are different and contain only lowercase characters. + +**NOTE:** Size of first string is always greater than the size of second string( |string1| > |string2|). + +### Examples: +**Example 1:** +``` +Input: +string1 = "computer" +string2 = "cat" +Output: "ompuer" +Explanation: After removing characters(c, a, t) from string1 we get "ompuer". +``` + +**Example 2:** +``` +Input: +string1 = "occurrence" +string2 = "car" +Output: "ouene" +Explanation: After removing characters (c, a, r) from string1 we get "ouene". +``` + +### Your task: + +You dont need to read input or print anything. Complete the function **removeChars()** which takes string1 and string2 as input parameter and returns the result string after removing characters from string2 from string1. + +- **Expected Time Complexity:** $O(|String1| + |String2|)$ +- **Expected Auxiliary Space:** $O(|String1|)$ + +### Constraints: + +- $1 <= |String1| , |String2| <= 50$ + +## Solution +### Python +```python +def removeChars (ob, string1, string2): + set_string2 = set(string2) + result = [] + for char in string1: + if char not in set_string2: + result.append(char) + return ''.join(result) +``` + +### Java +```java +static String removeChars(String string1, String string2){ + Set setString2 = new HashSet<>(); + for (char c : string2.toCharArray()) { + setString2.add(c); + } + StringBuilder result = new StringBuilder(); + for (char c : string1.toCharArray()) { + if (!setString2.contains(c)) { + result.append(c); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string removeChars(string string1, string string2) { + unordered_set setString2; + for (char c : string2) { + setString2.insert(c); + } + string result; + for (char c : string1) { + if (setString2.find(c) == setString2.end()) { + result += c; + } + } + return result; +} +``` + +### C +```c +void removeChars(char *string1, char *string2) { + int map[256] = {0}; + for (int i = 0; i < strlen(string2); ++i) { + map[(int)string2[i]] = 1; + } + int index = 0; + for (int i = 0; i < strlen(string1); ++i) { + if (!map[(int)string1[i]]) { + string1[index++] = string1[i]; + } + } + string1[index] = '\0'; +} +``` + +- **Time Complexity:** $O(|String1| + |String2|)$ +- **Auxiliary Space:** $O(|String1|)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0092.md b/dsa-solutions/gfg-solutions/Basic/0092.md new file mode 100644 index 000000000..06898dc08 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0092.md @@ -0,0 +1,108 @@ +--- +id: print-first-letter-every-word +title: Print First Letter of Every Word in the String +sidebar_label: 0092 Print First Letter of Every Word in the String +tags: +- Strings +- Python +- Java +- C++ +- C +description: "This document covers methods to print the first letter of every word in a given string in various programming languages." +--- + +## Problem + +Given a string S, the task is to create a string with the first letter of every word in the string. + +### Examples: +**Example 1:** +``` +Input: +S = "geeks for geeks" +Output: gfg +``` + +**Example 2:** +``` +Input: +S = "bad is good" +Output: big +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **firstAlphabet()** which takes string S as input parameter and returns a string that contains the first letter of every word in S. + +- **Expected Time Complexity:** $O(|S|)$ +- **Expected Auxiliary Space:** $O(|S|)$ + +### Constraints: + +- $1<=N<=10^5$ +- $0<=a[i]<=10^5$ + +## Solution +### Python +```python +def firstAlphabet(self, S): + words = S.split() + result = "" + for word in words: + result += word[0] + return result +``` + +### Java +```java +String firstAlphabet(String S) { + String[] words = S.split("\\s+"); + StringBuilder result = new StringBuilder(); + for (String word : words) { + if (!word.isEmpty()) { + result.append(word.charAt(0)); + } + } + return result.toString(); +} +``` + +### C++ +```cpp +string firstAlphabet(string S) { + istringstream iss(S); + string word; + string result; + while (iss >> word) { + result += word[0]; + } + return result; +} +``` + +### C +```c +char* firstAlphabet(char S[]) { + char result[100000]; + int result_index = 0; + int i = 0; + while (S[i] != '\0') { + while (isspace(S[i])) { + i++; + } + if (!isspace(S[i])) { + result[result_index++] = S[i]; + } + while (S[i] != '\0' && !isspace(S[i])) { + i++; + } + } + result[result_index] = '\0'; + char* final_result = (char*) malloc(strlen(result) + 1); + strcpy(final_result, result); + return final_result; +} +``` + +- **Time Complexity:** $O(|S|)$ +- **Auxiliary Space:** $O(|S|)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0093.md b/dsa-solutions/gfg-solutions/Basic/0093.md new file mode 100644 index 000000000..9cd7b226c --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0093.md @@ -0,0 +1,117 @@ +--- +id: replace-zeros-with-fives +title: Replace All 0's with 5 +sidebar_label: 0093 Replace All 0's with 5 +tags: +- Python +- Java +- C++ +- C +description: "This document covers methods to replace all occurrences of the digit 0 with the digit 5 in a given number in various programming languages." +--- + +## Problem + +Given a number N. The task is to complete the function **convertFive()** which replaces all zeros in the number with 5 and returns the number. + +### Examples: +**Example 1:** +``` +Input +2 +1004 +121 + +Output +1554 +121 + +Explanation: +Testcase 1: At index 1 and 2 there is 0 so we replace it with 5. +Testcase 2: There is no,0 so output will remain the same. +``` + +### Input: + +The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. +Each test case contains a single integer N denoting the number. + +### Output: + +The function will return an integer where all zero's are converted to 5. + +### Your task: + +Since this is a functional problem you don't have to worry about input, you just have to complete the function **convertFive()**. + +### Constraints: + +- $1 <= T <= 10^3$ +- $1 <= N <= 10^4$ + +## Solution +### Python +```python +def convertFive(self,n): + num_str = str(n) + result = "" + for char in num_str: + if char == '0': + result += '5' + else: + result += char + return int(result) +``` + +### Java +```java +public static int convertFive(int n){ + String numStr = String.valueOf(n); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < numStr.length(); i++) { + char currentChar = numStr.charAt(i); + if (currentChar == '0') { + result.append('5'); + } + else { + result.append(currentChar); + } + } + int convertedNumber = Integer.parseInt(result.toString()); + return convertedNumber; +} +``` + +### C++ +```cpp +int convertFive(int n) { + string numStr = to_string(n); + for (char &c : numStr) { + if (c == '0') { + c = '5'; + } + } + int convertedNumber = stoi(numStr); + return convertedNumber; +} +``` + +### C +```c +int convertFive(int n) { + int result = 0; + int position = 1; + while (n != 0) { + int digit = n % 10; + if (digit == 0) { + result += 5 * position; + } + else { + result += digit * position; + } + n /= 10; + position *= 10; + } + return result; +} +``` diff --git a/dsa-solutions/gfg-solutions/Basic/0094.md b/dsa-solutions/gfg-solutions/Basic/0094.md new file mode 100644 index 000000000..b0b7bd27e --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0094.md @@ -0,0 +1,101 @@ +--- +id: pattern-6 +title: Pattern 6 +sidebar_label: 0094 Pattern 6 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print triangle number in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a pattern. + +### Examples: +**Example 1:** +``` +Input: 5 + +Output: +1 2 3 4 5 +1 2 3 4 +1 2 3 +1 2 +1 +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and print the pattern. + +### Constraints: + +- $1<= N <= 20$ + +## Solution +### Python +```python +def printTriangle(self, N): + for i in range(N, 0, -1): + for j in range(1, i + 1): + if j == 1: + print(j, end='') + else: + print(' ' + str(j), end='') + print() +``` + +### Java +```java +void printTriangle(int n) { + for (int i = n; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + if (j == 1) { + System.out.print(j); + } else { + System.out.print(" " + j); + } + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for (int i = n; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + if (j == 1) { + cout << j; + } else { + cout << " " << j; + } + } + cout << endl; + } +} +``` + +### C +```c +void printTriangle(int n) { + int i, j; + for (i = n; i >= 1; i--) { + for (j = 1; j <= i; j++) { + if (j == 1) { + printf("%d", j); + } else { + printf(" %d", j); + } + } + printf("\n"); + } +} +``` \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0095.md b/dsa-solutions/gfg-solutions/Basic/0095.md new file mode 100644 index 000000000..b494cf23c --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0095.md @@ -0,0 +1,90 @@ +--- +id: set-kth-bit +title: Set kth Bit +sidebar_label: 0095 Set kth Bit +tags: +- Bit Manipulation +- Python +- Java +- C++ +- C +description: "This document covers methods to set the kth bit of a number to 1 in various programming languages." +--- + +## Problem + +Given a number N and a value K. From the right, set the Kth bit in the binary representation of N. The position of Least Significant Bit(or last bit) is 0, the second last bit is 1 and so on. + +### Examples: +**Example 1:** +``` +Input: +N = 10 +K = 2 +Output: +14 +Explanation: +Binary representation of the given number 10 is: 1 0 1 0, number of bits in the binary reprsentation is 4. Thus 2nd bit from right is 0. The number after changing this bit to 1 is: 14(1 1 1 0). +``` + +**Example 2:** +``` +Input: +N = 15 +K = 3 +Output: +15 +Explanation: +The binary representation of the given number 15 is: 1 1 1 1, number of bits in the binary representation is 4. Thus 3rd bit from the right is 1. The number after changing this bit to 1 is 15(1 1 1 1). +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **setKthBit()** which takes two integer N and K as input parameter and returns an integer after setting the K'th bit in N. + +- **Expected Time Complexity:** $O(1)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^9$ +- $0 <= K < X$, where X is the number of bits in the binary representation of N. + +## Solution +### Python +```python +def setKthBit(self, N, K): + mask = 1 << K + result = N | mask + return result +``` + +### Java +```java +static int setKthBit(int N,int K){ + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +### C++ +```cpp +int setKthBit(int N, int K) { + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +### C +```c +int setKthBit(int N, int K) { + int mask = 1 << K; + int result = N | mask; + return result; +} +``` + +- **Time Complexity:** $O(1)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0096.md b/dsa-solutions/gfg-solutions/Basic/0096.md new file mode 100644 index 000000000..23fb763a5 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0096.md @@ -0,0 +1,142 @@ +--- +id: gcd-of-array +title: GCD of Array +sidebar_label: 0096 GCD of Array +tags: +- Array +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to calculate the Greatest Common Divisor (GCD) of an array of integers in various programming languages." +--- + +## Problem + +Given an array of N positive integers, find GCD of all the array elements. + +### Examples: +**Example 1:** +``` +Input: N = 3, arr[] = {2, 4, 6} +Output: 2 +Explanation: GCD of 2,4,6 is 2. +``` + +**Example 2:** +``` +Input: N = 1, arr[] = {1} +Output: 1 +Explanation: Greatest common divisor of all the numbers is 1. +``` + +### Your task: + +You don't need to read input or print anything. Complete the function **gcd()** which takes N and array as input parameters and returns the gcd. + +- **Expected Time Complexity:** $O(N logN)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 ≤ N, arr[i] ≤ 10^5$ + +## Solution +### Python +```python +def gcd(self, n, arr): + def compute_gcd(a, b): + while b != 0: + a, b = b, a % b + return a + if n == 1: + return arr[0] + current_gcd = arr[0] + for i in range(1, n): + current_gcd = compute_gcd(current_gcd, arr[i]) + if current_gcd == 1: + return 1 + return current_gcd +``` + +### Java +```java +public int gcd(int N , int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +private int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +### C++ +```cpp +int gcd(int N, int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +### C +```c +int gcd(int N, int arr[]) { + if (N == 1) { + return arr[0]; + } + int currentGCD = arr[0]; + for (int i = 1; i < N; i++) { + currentGCD = computeGCD(currentGCD, arr[i]); + if (currentGCD == 1) { + return 1; + } + } + return currentGCD; +} + +int computeGCD(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +``` + +- **Time Complexity:** $O(N logN)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0097.md b/dsa-solutions/gfg-solutions/Basic/0097.md new file mode 100644 index 000000000..490023741 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0097.md @@ -0,0 +1,120 @@ +--- +id: greater-on-right-side +title: Greater on Right Side +sidebar_label: 0097 Greater on Right Side +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to replace every element with the greatest element in various programming languages." +--- + +## Problem + +You are given an array Arr of size N. Replace every element with the next greatest element (greatest element on its right side) in the array. Also, since there is no element next to the last element, replace it with -1. + +### Examples: +**Example 1:** +``` +Input: +N = 6 +Arr[] = {16, 17, 4, 3, 5, 2} +Output: +17 5 5 5 2 -1 +Explanation: For 16 the greatest element +on its right is 17. For 17 it's 5. +For 4 it's 5. For 3 it's 5. For 5 it's 2. +For 2 it's -1(no element to its right). +So the answer is 17 5 5 5 2 -1 +``` + +**Example 2:** +``` +Input: +N = 4 +Arr[] = {2, 3, 1, 9} +Output: +9 9 9 -1 +Explanation: For each element except 9 the greatest element on its right is 9. +So the answer is 9 9 9 -1 +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **nextGreatest()** which takes the array of integers arr and n as parameters and returns void. You need to change the array itself. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^5$ +- $1 <= Arr_i <= 10^6$ + +## Solution +### Python +```python +def nextGreatest(self,arr, n): + if n == 0: + return + max_right = -1 + for i in range(n-1, -1, -1): + current = arr[i] + arr[i] = max_right + max_right = max(max_right, current) + arr[n-1] = -1 +``` + +### Java +```java +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = Math.max(maxRight, current); + } + arr[n - 1] = -1; +} +``` + +### C++ +```cpp +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = std::max(maxRight, current); + } + arr[n - 1] = -1; +} +``` + +### C +```c +void nextGreatest(int arr[], int n) { + if (n == 0) { + return; + } + + int maxRight = -1; + for (int i = n - 1; i >= 0; i--) { + int current = arr[i]; + arr[i] = maxRight; + maxRight = (maxRight > current) ? maxRight : current; + } + arr[n - 1] = -1; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0098.md b/dsa-solutions/gfg-solutions/Basic/0098.md new file mode 100644 index 000000000..5259686f3 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0098.md @@ -0,0 +1,106 @@ +--- +id: max-days-without-darkness +title: Maximum Days Without Darkness +sidebar_label: 0098 Maximum Days Without Darkness +tags: +- Array +- Python +- Java +- C++ +- C +description: "This document covers methods to find the maximum number of days the room remains illuminated using candles that reduce by 1 unit each day, given an array representing the sizes of the candles." +--- + +## Problem + +Given an array arr[] of size N representing the size of candles which reduce by 1 unit each day. The room is illuminated using the given N candles. Find the maximum number of days the room is without darkness. + +### Examples: +**Example 1:** +``` +Input: N = 3, arr[] = {1,1,2} +Output: 2 +Explanation: The candles' length reduce by 1 in 1 day. So, at the end of day 1: +Sizes would be 0 0 1, So, at end of day 2: Sizes would be 0 0 0. This means the room was illuminated for 2 days. +``` + +**Example 2:** +``` +Input: N = 5, arr[] = {2,3,4,2,1} +Output: 4 +``` + +### Your task: + +This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function **maxDays()** that takes array A[] and integer N as parameters and returns the desired output. + +- **Expected Time Complexity:** $O(N)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=N<=10^6$ + +## Solution +### Python +```python +def maxDays(self, arr, n): + if n == 0: + return 0 + max_initial_height = 0 + for height in arr: + if height > max_initial_height: + max_initial_height = height + return max_initial_height +``` + +### Java +```java +long maxDays(long arr[], int n){ + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +### C++ +```cpp +int maxDays(int arr[],int n){ + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +### C +```c +int maxDays(int arr[], int n) { + if (n == 0) { + return 0; + } + long maxInitialHeight = 0; + for (int i = 0; i < n; i++) { + if (arr[i] > maxInitialHeight) { + maxInitialHeight = arr[i]; + } + } + return maxInitialHeight; +} +``` + +- **Time Complexity:** $O(N)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0099.md b/dsa-solutions/gfg-solutions/Basic/0099.md new file mode 100644 index 000000000..6f3779fd5 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0099.md @@ -0,0 +1,123 @@ +--- +id: pattern-10 +title: Pattern 10 +sidebar_label: 0099 Pattern 10 +tags: +- Patterns +- Python +- Java +- C++ +- C +description: "This document covers methods to print a pattern in various programming languages." +--- + +## Problem + +Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern. + +Help Geek to build a star pattern. + +### Examples: +**Example 1:** +``` +Input: 5 +Output: +* +* * +* * * +* * * * +* * * * * +* * * * +* * * +* * +* +``` + +**Example 2:** +``` +Input: 3 +Output: +* +* * +* * * +* * +* +``` + +### Your task: + +You don't need to input anything. Complete the function **printTriangle()** which takes an integer n as the input parameter and prints the pattern. + +- **Expected Time Complexity:** $O(n^2)$ +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1 <= n <= 1000$ + +## Solution +### Python +```python +def printTriangle(self, n): + for i in range(1, n+1): + print('* ' * i) + for i in range(n-1, 0, -1): + print('* ' * i) +``` + +### Java +```java +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + System.out.print("* "); + } + System.out.println(); + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + System.out.print("* "); + } + System.out.println(); + } +} +``` + +### C++ +```cpp +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + std::cout << "* "; + } + std::cout << std::endl; + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + std::cout << "* "; + } + std::cout << std::endl; + } +} +``` + +### C +```c +void printTriangle(int n) { + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= i; j++) { + printf("* "); + } + printf("\n"); + } + for (int i = n - 1; i >= 1; i--) { + for (int j = 1; j <= i; j++) { + printf("* "); + } + printf("\n"); + } +} +``` + +- **Time Complexity:** $O(n^2)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/gfg-solutions/Basic/0100.md b/dsa-solutions/gfg-solutions/Basic/0100.md new file mode 100644 index 000000000..d4b26ba0d --- /dev/null +++ b/dsa-solutions/gfg-solutions/Basic/0100.md @@ -0,0 +1,107 @@ +--- +id: factorial-numbers-less-than-n +title: Find All Factorial Numbers Less Than or Equal to n +sidebar_label: 0100 Find All Factorial Numbers Less Than or Equal to n +tags: +- Mathematics +- Python +- Java +- C++ +- C +description: "This document covers methods to find all factorial numbers less than or equal to a given number n in various programming languages." +--- + +## Problem + +A number n is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are 1, 2, 6, 24, 120, + +Given a number n, the task is to return the list/vector of the factorial numbers smaller than or equal to n. + +### Examples: +**Example 1:** +``` +Input: n = 3 +Output: 1 2 +Explanation: The first factorial number is 1 which is less than equal to n. The second number is 2 which is less than equal to n,but the third factorial number is 6 which is greater than n. So we print only 1 and 2. +``` + +**Example 2:** +``` +Input: n = 6 +Output: 1 2 6 +Explanation: The first three factorial numbers are less than equal to n but the fourth factorial number 24 is greater than n. So we print only first three factorial numbers. +``` + +### Your task: + +You don't need to read input or print anything. Your task is to complete the function **rotate()** which takes the array **A[]** and its size **N** as inputs and modify the array in place. + +- **Expected Time Complexity:** $O(K)$, Where K is the number of factorial numbers. +- **Expected Auxiliary Space:** $O(1)$ + +### Constraints: + +- $1<=n<=10^{18}$ + +## Solution +### Python +```python +def factorialNumbers(self, n): + factorial = 1 + factorials = [] + i = 1 + while factorial <= n: + factorials.append(factorial) + i += 1 + factorial *= i + + return factorials +``` + +### Java +```java +static ArrayList factorialNumbers(long n) { + ArrayList factorials = new ArrayList<>(); + long factorial = 1; + int i = 1; + while (factorial <= n) { + factorials.add(factorial); + i++; + factorial *= i; + } + return factorials; +} +``` + +### C++ +```cpp +vector factorialNumbers(long long n) { + vector factorials; + long long factorial = 1; + int i = 1; + while (factorial <= n) { + factorials.push_back(factorial); + i++; + factorial *= i; + } + return factorials; +} +``` + +### C +```c +long long factorialNumbers(long long n, long long *out, int *out_size) { + long long factorial = 1; + int i = 1; + *out_size = 0; + while (factorial <= n) { + out[(*out_size)++] = factorial; + i++; + factorial *= i; + } + return factorial; +} +``` + +- **Time Complexity:** $O(K)$ +- **Auxiliary Space:** $O(1)$ \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md b/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md new file mode 100644 index 000000000..76a29c9c4 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0017-letter-combinations-of-a-phone-number.md @@ -0,0 +1,325 @@ +--- +id: letter-combinations-of-a-phone-number +title: Letter Combinations of a Phone Number (LeetCode) +sidebar_label: 0017 Letter Combinations of a Phone Number +tags: + - Back Tracking + - Mapping + - String +description: The problem requires generating all letter combinations corresponding to given digits (2-9). The solution utilizes backtracking to explore all combinations efficiently, employing a recursive approach in Java. +sidebar_position: 17 +--- + +## Problem Description + +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- | +| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | + +### Problem Description + +## Problem Statement: + +Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. + +### Examples + +#### Example 1 + +- **Input:** `digits = "23"` +- **Output:** `["ad","ae","af","bd","be","bf","cd","ce","cf"]` + +#### Example 2 + +- **Input:** `digits = ""` +- **Output:** `[]` + +#### Example 3 + +- **Input:** `2` +- **Output:** `["a","b","c"]` + +### Constraints: +- `0 ≤ digits.length ≤ 4` +- `0 ≤ digits.length ≤ 4digits[𝑖]` +- `digits[i] is a digit in the range ['2', '9'].` +- `A mapping of digits to letters (similar to telephone buttons) is given below. Note that 1 does not map to any letters.` + +### Approach + +1. **Mapping Digits to Letters:** + + - Define a mapping of digits to their corresponding letters, similar to telephone buttons. + +2. **Backtracking Function:** + + - Define a recursive backtracking function to generate all possible combinations. + - The function takes four parameters: + - `index`: The current index in the digits string. + - `path`: The current combination of letters. + - If the index is equal to the length of the digits string, it means we have reached the end of a combination, so we add it to the result list. + - Otherwise, for each letter corresponding to the current digit, we append it to the current combination and recursively call the function with the next index. + - After the recursive call, we remove the last character from the combination (backtracking). + +3. **Base Case:** + + - If the length of the current combination is equal to the length of the input digits string, we add the combination to the result list. + +4. **Main Function:** + - Initialize an empty list to store the combinations. + - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. + - Return the list of combinations. + +This approach ensures that all possible combinations are generated using backtracking, and the result is returned in the desired format. + +### Solution Code +#### Python + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + if not digits: + return [] + + digit_to_letters = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'pqrs', + '8': 'tuv', + '9': 'wxyz' + } + + def backtrack(index, path): + if index == len(digits): + combinations.append(path) + return + for letter in digit_to_letters[digits[index]]: + backtrack(index + 1, path + letter) + + combinations = [] + backtrack(0, '') + return combinations +``` + +#### Java + +```java +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Solution { + private Map digitToLetters = new HashMap<>(); + + public Solution() { + digitToLetters.put('2', "abc"); + digitToLetters.put('3', "def"); + digitToLetters.put('4', "ghi"); + digitToLetters.put('5', "jkl"); + digitToLetters.put('6', "mno"); + digitToLetters.put('7', "pqrs"); + digitToLetters.put('8', "tuv"); + digitToLetters.put('9', "wxyz"); + } + + public List letterCombinations(String digits) { + List combinations = new ArrayList<>(); + if (digits == null || digits.isEmpty()) { + return combinations; + } + backtrack(combinations, digits, 0, new StringBuilder()); + return combinations; + } + + private void backtrack(List combinations, String digits, int index, StringBuilder path) { + if (index == digits.length()) { + combinations.add(path.toString()); + return; + } + String letters = digitToLetters.get(digits.charAt(index)); + for (char letter : letters.toCharArray()) { + path.append(letter); + backtrack(combinations, digits, index + 1, path); + path.deleteCharAt(path.length() - 1); + } + } + + public static void main(String[] args) { + Solution solution = new Solution(); + List result = solution.letterCombinations("23"); + System.out.println(result); // Output: [ad, ae, af, bd, be, bf, cd, ce, cf] + } +} +``` + +#### CPP: + +```cpp +#include +#include +#include + +using namespace std; + +class Solution { +private: + unordered_map digitToLetters; + vector combinations; + +public: + Solution() { + digitToLetters = { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + } + + vector letterCombinations(string digits) { + if (digits.empty()) return {}; + backtrack(digits, 0, ""); + return combinations; + } + + void backtrack(const string& digits, int index, string path) { + if (index == digits.length()) { + combinations.push_back(path); + return; + } + for (char letter : digitToLetters[digits[index]]) { + backtrack(digits, index + 1, path + letter); + } + } +}; + +int main() { + Solution solution; + vector result = solution.letterCombinations("23"); + for (const string& comb : result) { + cout << comb << " "; + } + // Output: ad ae af bd be bf cd ce cf + return 0; +} +``` + +#### JavaScript + +```js +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function (digits) { + if (digits.length === 0) return []; + + const digitToLetters = { + 2: "abc", + 3: "def", + 4: "ghi", + 5: "jkl", + 6: "mno", + 7: "pqrs", + 8: "tuv", + 9: "wxyz", + }; + + const combinations = []; + + const backtrack = (index, path) => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } + }; + + backtrack(0, ""); + return combinations; +}; + +// Example usage: +console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] +``` + +#### TypeScript + +```ts +class Solution { + private digitToLetters: { [key: string]: string } = { + "2": "abc", + "3": "def", + "4": "ghi", + "5": "jkl", + "6": "mno", + "7": "pqrs", + "8": "tuv", + "9": "wxyz", + }; + + letterCombinations(digits: string): string[] { + const combinations: string[] = []; + + const backtrack = (index: number, path: string): void => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = this.digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } + }; + + if (digits.length !== 0) { + backtrack(0, ""); + } + + return combinations; + } +} + +// Example usage: +const solution = new Solution(); +console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] +``` + +### Step-by-Step Algorithm + +Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking: + +1. **Define a mapping of digits to letters:** + + - Create a map where each digit from 2 to 9 is mapped to its corresponding letters on a telephone keypad. + +2. **Define a backtracking function:** + + - The function will take the following parameters: + - `index`: The current index in the digits string. + - `path`: The current combination of letters. + - If the index is equal to the length of the digits string, it means we have formed a complete combination, so add it to the result list. + - Otherwise, for each letter corresponding to the current digit at the given index, append it to the current combination and recursively call the function with the next index. + - After the recursive call, remove the last character from the combination (backtracking). + +3. **Base Case:** + + - If the length of the current combination is equal to the length of the input digits string, add the combination to the result list. + +4. **Main Function:** + - Initialize an empty list to store the combinations. + - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. + - Return the list of combinations. + +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking.