Table of contents
- Q1. Implement a function to merge two sorted arrays.
- Q2. Write a program to find the union and intersection of two arrays.
- Q3. Solve the problem of finding a subarray with a given sum (for positive numbers).
- Q4. Implement Kadane's Algorithm to find the maximum sum subarray.
- Q5. Solve the problem of rearranging an array with alternate positive and negative numbers.
Welcome to Day 3 of my 100 Days of DSA journey! Today, I focused on solving a variety of problems involving arrays, one of the most commonly used data structures in programming. Arrays allow us to store and efficiently manipulate collections of data, making them essential for solving numerous algorithmic challenges. I tackled five distinct problems, ranging from merging two sorted arrays to finding subarrays with specific sums, and I even implemented Kadane’s algorithm to identify the maximum sum subarray. These exercises were a great way to reinforce my understanding of array manipulation. Let’s dive in!
I have also maintained a GitHub repository for the same, so feel free to check it out: github.com/AayJayTee/100-Days-DSA.
Q1. Implement a function to merge two sorted arrays.
#include <iostream>
using namespace std;
void mergearrays(int arr1[], int len1, int arr2[], int len2, int merged[], int len3) {
// Copy elements from arr1 to merged
for (int i = 0; i < len1; i++) {
merged[i] = arr1[i];
}
// Copy elements from arr2 to merged
for (int i = 0; i < len2; i++) {
merged[len1 + i] = arr2[i];
}
// Output the merged array
cout << "The merged array is: ";
for (int i = 0; i < len3; i++) {
cout << merged[i];
}
}
int main() {
int n1, n2, n3;
cout << "Enter length of first array: ";
cin >> n1;
int arr1[n1];
cout << "Enter elements of the array: ";
for (int i = 0; i < n1; i++) {
cin >> arr1[i]; // Input the elements of the first array
}
cout << "Enter length of second array: ";
cin >> n2;
int arr2[n2];
cout << "Enter elements of the array: ";
for (int i = 0; i < n2; i++) {
cin >> arr2[i]; // Input the elements of the second array
}
n3 = n1 + n2;
int merged[n3]; // Create an array to store the merged result
mergearrays(arr1, n1, arr2, n2, merged, n3); // Call function to merge the arrays
return 0;
}
The goal of this problem is to merge two already sorted arrays into a single sorted array. This is done by copying the elements of both arrays into a new array in a sequential manner. The merging process does not require any additional sorting since the arrays are already sorted individually. Once the elements from both arrays are copied into the new array, it is printed as the merged result. This simple yet effective approach demonstrates the concept of array merging.
Q2. Write a program to find the union and intersection of two arrays.
#include <iostream>
using namespace std;
bool isPresent(int arr[], int n, int a) {
for (int i = 0; i < n; i++) {
if (arr[i] == a) {
return true; // Return true if element is found
}
}
return false; // Return false if element is not found
}
void union_array(int arr1[], int n1, int arr2[], int n2) {
int n3 = n1 + n2;
int j = 0;
int arr3[n3];
for (int i = 0; i < n1; i++) {
if (!isPresent(arr3, j, arr1[i])) {
arr3[j] = arr1[i]; // Add unique elements from arr1
j++;
}
}
for (int i = 0; i < n2; i++) {
if (!isPresent(arr3, j, arr2[i])) {
arr3[j] = arr2[i]; // Add unique elements from arr2
j++;
}
}
cout << "The union of the arrays are: ";
for (int i = 0; i < j; i++) {
cout << arr3[i]; // Output the union
}
}
void intersection_array(int arr1[], int n1, int arr2[], int n2) {
int n3 = n1 + n2;
int arr4[n3];
int j = 0;
for (int i = 0; i < n1; i++) {
if (isPresent(arr2, n2, arr1[i]) && !isPresent(arr4, j, arr1[i])) {
arr4[j] = arr1[i]; // Add common elements to intersection array
j++;
}
}
cout << "The intersection of the arrays are: ";
for (int i = 0; i < j; i++) {
cout << arr4[i]; // Output the intersection
}
}
int main() {
int n1, n2, n3;
cout << "Enter length of first array: ";
cin >> n1;
int arr1[n1];
cout << "Enter elements of the array: ";
for (int i = 0; i < n1; i++) {
cin >> arr1[i];
}
cout << "Enter length of second array: ";
cin >> n2;
int arr2[n2];
cout << "Enter elements of the array: ";
for (int i = 0; i < n2; i++) {
cin >> arr2[i];
}
union_array(arr1, n1, arr2, n2); // Find union of arrays
cout << endl;
intersection_array(arr1, n1, arr2, n2); // Find intersection of arrays
return 0;
}
This solution tackles finding both the union and intersection of two arrays. The union includes all unique elements from both arrays, while the intersection consists only of the elements common to both. To compute the union, the program checks each element of the second array and ensures that it hasn't already been added to the result. Similarly, for the intersection, it identifies common elements and ensures that no duplicates are included. The solution is efficient in identifying these key relationships between arrays and outputs the results accordingly.
Q3. Solve the problem of finding a subarray with a given sum (for positive numbers).
#include <iostream>
using namespace std;
int sum_subarray(int arr[], int n, int sum) {
int i = 0;
int temp = 0;
int start = 0;
while (i < n) {
for (int j = i; j < n; j++) {
temp += arr[j]; // Add elements to the sum until it exceeds or matches the target sum
if (temp > sum) {
i++;
temp = 0;
break;
} else if (temp == sum) {
start = i; // Found the subarray
cout << "The subarray giving sum is: ";
for (int k = start; k <= j; k++) {
cout << arr[k];
}
cout << endl;
}
}
}
}
int main() {
int n, sum;
cout << "Enter length of array: ";
cin >> n;
int arr[n];
cout << "Enter elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the sum: ";
cin >> sum;
sum_subarray(arr, n, sum); // Call the function to find the subarray
return 0;
}
This problem focuses on finding a contiguous subarray that sums up to a given target value. It is solved using a sliding window approach, where the program iterates through the array while maintaining a running sum of the current subarray. Once the sum matches the target, the program outputs the subarray. If the sum exceeds the target, the window is adjusted by moving the starting index forward and resetting the sum, ensuring that the subarray remains within bounds. This approach efficiently solves the problem while maintaining simplicity.
Q4. Implement Kadane's Algorithm to find the maximum sum subarray.
#include <iostream>
using namespace std;
void max_sum_subarray(int arr[], int n) {
int max_sum = 0; // Initialize max_sum to 0 (can also be set to arr[0] to handle negative sums)
int current = 0; // Variable to track the current subarray sum
int start = 0, end = 0, temp_start = 0; // Indices to store the start and end of the max subarray
for (int i = 0; i < n; i++) {
current += arr[i]; // Add the current element to the current subarray sum
max_sum = max(max_sum, current); // Update the max_sum if the current sum is larger
start = temp_start; // Set start index of max subarray
end = i; // Set end index of max subarray
if (current < 0) {
current = 0; // Reset the current sum if it becomes negative
temp_start = i + 1; // Move the start index of subarray to the next element
}
}
cout << "Max sum is: " << max_sum << endl; // Output the maximum sum
cout << "The elements giving max sum are: ";
for (int j = start; j <= end; j++) { // Output the elements of the subarray
cout << arr[j] << ",";
}
}
int main() {
int n;
cout << "Enter length of array: ";
cin >> n;
int arr[n];
cout << "Enter elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
max_sum_subarray(arr, n); // Call the function to find the maximum sum subarray
return 0;
}
Kadane's Algorithm is a well-known technique for solving the Maximum Subarray Sum problem. It works by iterating through the array while maintaining the maximum sum seen so far. The key idea is that at each step, we decide whether to add the current element to the existing sum or start a new subarray with the current element if the sum becomes negative. This dynamic programming solution provides an optimal way to find the maximum sum subarray in linear time, making it highly efficient for large arrays.
Q5. Solve the problem of rearranging an array with alternate positive and negative numbers.
#include <iostream>
using namespace std;
void rearrange(int arr[], int n) {
int posIndex = 0; // To find the next positive number
int negIndex = 1; // To find the next negative number
while (posIndex < n && negIndex < n) {
while (posIndex < n && arr[posIndex] <= 0) {
posIndex += 2; // Move to the next potential position for a positive number
}
while (negIndex < n && arr[negIndex] >= 0) {
negIndex += 2; // Move to the next potential position for a negative number
}
if (posIndex < n && negIndex < n) {
swap(arr[posIndex], arr[negIndex]); // Swap positive and negative numbers
}
}
cout << "Rearranged array is: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " "; // Output the rearranged array
}
cout << endl;
}
int main() {
int n;
cout << "Enter length of array: ";
cin >> n;
int arr[n];
cout << "Enter elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
rearrange(arr, n); // Call the rearrange function
return 0;
}
The challenge here is to rearrange an array such that positive and negative numbers alternate. The approach used in the solution involves two pointers: one for finding the next positive number and one for finding the next negative number. The program then swaps these elements, ensuring that they alternate. The solution works by iterating through the array and making sure that each position in the array holds the correct type of number (positive or negative) based on its index. This rearrangement is done in place, making it both space and time efficient.
Today’s practice enhanced my grasp of various array operations and algorithms. I explored merging sorted arrays, finding subarrays with a given sum, and rearranging arrays with alternating positive and negative numbers. Implementing Kadane's algorithm for the maximum sum subarray further solidified my problem-solving skills. While some solutions are straightforward, others highlight areas for further optimization. I'm excited to continue the journey and tackle even more challenging problems ahead. Onward to Day 4!