Day 2: Arrays Basics

Day 2: Arrays Basics

In Day 2 of my 100 Days of DSA challenge, I delved into the world of arrays, one of the most fundamental data structures. Arrays form the backbone of countless algorithms, and understanding their operations is key to efficient problem-solving.

Today, I tackled five array-based problems, exploring various operations and techniques to manipulate and process data. Each solution was implemented in C++, and the experience deepened my grasp of this versatile data structure.

Stay tuned as I share the problems, their solutions, and the thought process behind each one! 🚀👩‍💻

Check out my GitHub repository for all the solutions and progress at: 100 Days of DSA


1. Largest and Smallest Elements in Array

This program finds the largest and smallest elements in a given array. It iterates through the array, comparing each element to track the smallest and largest values. By the end of the loop, the smallest and largest numbers are identified and displayed.

Code:

#include <iostream> 
using namespace std;

// Function to find and display the largest and smallest elements in an array
void min_max(int arr[], int n) {
    int largest = arr[0];  // Initialize the largest element as the first element
    int smallest = arr[0]; // Initialize the smallest element as the first element

    // Traverse the array to find the smallest and largest elements
    for (int i = 0; i < n; i++) {
        if (arr[i] < smallest) { // Update smallest if the current element is smaller
            smallest = arr[i];
        }
        else if (arr[i] > largest) { // Update largest if the current element is larger
            largest = arr[i];
        }
    }

    cout << "The largest element is: " << largest << endl;
    cout << "The smallest element is: " << smallest << endl;
}

int main() {
    int n; 
    cout << "Enter number of elements in array: ";
    cin >> n;
    int *arr = new int[n];
    cout << "Enter elements: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    min_max(arr, n);
    delete[] arr;
    return 0;
}

Output:


2. Second Largest Element in Array

This program finds the second largest element in a given array. It iterates through the array to identify the largest element, while also keeping track of the second largest. The results are displayed to the user.

Code:

#include <iostream>
#include <climits>
using namespace std;

// Function to find and display the second largest element in an array
void second_largest(int arr[], int n) {
    // Initialize the largest and second largest elements
    int largest = arr[0];
    int second = INT_MIN; // Use INT_MIN for second largest to handle edge cases

    for (int i = 1; i < n; i++) {
        if (arr[i] > largest) {
            // Update second largest before changing the largest
            second = largest;
            largest = arr[i];
        }
        else if (arr[i] > second && arr[i] != largest) {
            // Update second largest if the current element is smaller than the largest
            second = arr[i];
        }
    }

    // Check if a valid second largest element exists
    if (second == INT_MIN) {
        cout << "Second largest element does not exist." << endl;
    }
    else {
        cout << "The second largest element is: " << second << endl;
    }
}

int main() {
    int n;
    cout << "Enter number of elements in array: ";
    cin >> n;
    int *arr = new int[n];
    cout << "Enter elements: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    second_largest(arr, n);
    delete[] arr;
    return 0; 
}

Output:


3. Rotate an Array to the Left by ‘k’ Positions

This program rotates an array to the left by k positions using a reversal-based approach. It takes user input for the size of the array, the array elements, and the number of positions to rotate. The program uses three steps of array reversal to achieve efficient rotation. Below is a breakdown of each part:

  • Array Rotation:
    Left rotation by k positions means that the first k elements of the array are moved to the end, while the rest of the elements shift to the left.

  • Reversal Algorithm:
    The reversal method efficiently rotates the array in O(n) time complexity and O(1) space complexity.

Code:

#include <iostream>
using namespace std;

// Function to reverse a portion of the array
void reverse(int arr[], int start, int end) {
    while (start < end) {
        swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

// Function to rotate an array to the left by k positions
void rotate_left(int arr[], int n, int k) {
    k = k % n; // Handle cases where k >= n

    // Step 1: Reverse the first k elements
    reverse(arr, 0, k - 1);

    // Step 2: Reverse the remaining n-k elements
    reverse(arr, k, n - 1);

    // Step 3: Reverse the entire array
    reverse(arr, 0, n - 1);
}

int main() {
    int n, k;
    cout << "Enter the size of the array: ";
    cin >> n;
    int *arr = new int[n];
    cout << "Enter the elements of the array: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    cout << "Enter the number of positions to rotate: ";
    cin >> k;
    rotate_left(arr, n, k);
    cout << "The rotated array is: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    delete[] arr;
    return 0;
}

Output:


4. Count the Occurrences of Given Element in Array

This program counts the number of occurrences of a given element in an array. The user inputs the size of the array, the elements of the array, and the element to be searched. The program then iterates through the array to count how many times the specified element appears.

Code:

#include <iostream>
using namespace std;

// Function to count the occurrences of an element in the array
void occurrences(int arr[], int n, int x) {
    int count = 0; 
    for (int i = 0; i < n; i++) {
        if (arr[i] == x) {     // Check if the current element matches x
            count++;           // Increment counter if there's a match
        }
    }
    cout << "There are " << count << " occurrences of element " << x << "." << endl;
}

int main() {
    int n;
    cout << "Enter number of elements in array: ";
    cin >> n;
    int *arr = new int[n];
    cout << "Enter elements: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int x;
    cout << "Enter element whose number of occurrences to check: ";
    cin >> x;
    occurrences(arr, n, x);
    delete[] arr;
    return 0;
}

Output:


5. All Elements that Appear More Than Once in Array

This C++ program is designed to find and print all the elements in an array that appear more than once (i.e., duplicates). It works by scanning through the array and checking each element to see if it has already been seen and marked as "visited." If a duplicate is found, it prints that element only once.

Code:

#include <iostream>
using namespace std;

// Function to find and print elements with duplicates in the array
void findDuplicateElements(int arr[], int n) {
    bool *visited = new bool[n](); // Create a visited array to mark processed elements
    cout << "Elements with duplicates are: ";

    bool found = false;
    for (int i = 0; i < n; i++) {
        // Skip the element if it's already marked as visited
        if (visited[i])
            continue;

        bool isDuplicate = false;
        // Check for duplicates of arr[i] from the next position
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                isDuplicate = true;
                visited[j] = true;   // Mark the duplicate element
            }
        }

        // If a duplicate was found, print the element
        if (isDuplicate) {
            cout << arr[i] << " ";
            visited[i] = true;      // Mark the current element as visited as well
            found = true;
        }
    }

    if (!found) {
        cout << "None";
    }
    cout << endl;
    delete[] visited;
}

int main() {
    cout << "Enter number of elements: ";
    int count;
    cin >> count;
    int *arr = new int[count];
    cout << "Enter elements of the array: ";
    for (int i = 0; i < count; i++) {
        cin >> arr[i];
    }
    findDuplicateElements(arr, count);
    delete[] arr;
    return 0;
}

Output:


Day 2 was a great learning experience as I dove deeper into array operations. Arrays are fundamental to many problems, and today I honed my skills in handling and manipulating them. These operations will be crucial for tackling more complex challenges down the road.

Excited for Day 3, where I'll explore more advanced array techniques and take on new challenges! 🚀