Arrays (1-Dimension)

AbhinavAbhinav
5 min read

In C++, an array is a data structure used to store a collection of elements of the same data type in contiguous memory locations. These elements are accessed using an index, which represents their position within the array.


In any data type You need to understand 3 important things first.

  1. How to define that particular data-type.

  2. How to assign any value to the data-type.

  3. How to access any value from the data-type.

Representation of Arrays:

 // first define the data-type than name and then size of array you want to make.

int Abhinav[5] = {1,2,4,7,9}; // correct way to represent the array. // initialisation

int hello[]; // will give error.

int hello[] = {1,4,7,9}; // No error, it will automatically know 4 is the elements.

hello[0]; // will output as 1 , its called accessing the value.

There are two terminologies that you should keep in mind.

  • Assignment

  • Initialisation

Assignment: You can understand it like your homework, i.e., you will put the values later.

Initialisation: This is like your ongoing process; you need to put values instantly.


Find the Maximum value element in an Array?

  • Method ONE

We will assume a negative value and then iterate over the array’s elements, comparing each with the assumed value, and then output the max element as my answer.

// Example // int array[5] = {1,2,4,6,9};

void maxValueElement(int array[],int size)
{
int max = -1;
for (int i = 0; i < size ; i++){
    if(array[i] > max){
        max = array[i];
        }
    }
}
// As we can see from this concept we can determine the max value element in an array.

**Drawbacks:**In this method, we assumed the array only has positive values, which is not always true. If the last element becomes -7, then the concept will give the wrong answer.

  • Method TWO

We will assume that the first element of the array is max, and then we apply the same concept of comparing each element and updating the value in the max variable.

// Example // int array[4] = {2,5,9,-6};

int maxValueElement(int array[],int size){

int max = array[0];
for (int i = 1; i < size ;i++){
    if(array[i]>max){
        max = array[i];
        }
    }return max;

    if(size == 0) {
    cout << "Empty array"<<endl;
    }
}
// now in this case we can tackle the problem of negative number easily.

Question 26: Leetcode (Remove the duplicate elements from the sorted Array)

First, read and understand the question. We realize that the elements are sorted, so their duplicates will only exist in nearby locations. We also need to provide the answer in the same array and return the number of unique values as ‘k’.

  • The logic is something like this: if there is only a single element in the array, it will always be unique, so start with k = 1 (k is the number of unique elements).
int removeDuplicate(int array[],int size){
    int k = 1; // assuming 1 element is always unique.
    int temp[size]; // a temperory array which will have only unique values.
    int temp[0] = array[0]; // making 1st values as unique.

    for(int i = 1; i < size; i++){ // starting from 1 becz already oth value assumed to be unique.

        if(array[i] == array[i-1]){
            continue: // then proceed to do i++ if find duplicate.
            }
        else{
            temp[k] = array[i]; // push unique value in temp.
            k++; // for counting unique values.
            }
        }
    for (int i = 0 ; i < k; i++){
        array[i] = temp[i]; // assign the value of temp back to original array.
    }return k;
}

Question 66: Leetcode (You need to add 1 to the given number and display the result in an array.)

First, read and understand the question. However, sometimes it's easier to grasp the concept with the examples provided below.

  • The logic is straightforward: simply add 1 to the last element of the array and then display the result in the array.

  • But the tricky part is the corner case. If the last element is 9, the value changes to 0, and an extra 1 appears in front.

  • Here, we will use a vector to solve the question because, in dynamic situations, the array size keeps changing. Vectors have many built-in functions that help us get results more quickly.

vector<int> digits; // delare and assign the vector.
// what we need is the number of elements of array to access the last value.

int n = size.digits(); // this will give you length

for( int i = n-1 ; i >= 0 ; i--){ // start from end

    if( digits[i] < 9 ) {
        digits[i]++; // just add 1 in them.
        return digits; // return that array digits.
        }
    else{
        digit[i] = 0; // make it zero
        }
    digits.insert(digits.begin(),1); // add 1 on front now.(STL syntax)
    return digits; // return the digits array.
        }

Question 88: Leetcode (Merge the two sorted array)

We are given two sorted arrays, and we need to merge them together in a sorted manner. This is my understanding. Additionally, we can consider the num1 array as having a length of m+n.

  • The logic is to compare the values and start inserting from the end because some elements at the end are empty.
void mergeTwoArray(int num1[], int m, int num2[],int n){

    int k = m + n - 1; // final array's last index.
    int i = m - 1; // for last index of num1 array.
    int j = n - 1; // for last index of num2 array.

    while(i >= 0 && j >= 0) // either of 2 array become empty we exit the loop
    {
        if(num1[i] >= num2[j]){
            num1[k] = num1[i]; // assign num1 value at kth position of num1.
            i--; // decrement i
            k--; // decrement k because its value already assigned above
          }
        else{
            num1[k] = num2[j]; // assign num2 value at kth position of num1.
            j--;
            k--;
           }
    }
    while(j >=0){ // this case happen when lets suppose num1 elements get empty first,
                    // in that case we need to assign the rest of num2 value back to num1.
// if num2 elements gets empty first than its okay, because its what we need.
    num1[k] = num2[j]; // assign num2 to num1 at rest of position on k.
    j--;
    k--;
    }
}

Conclusion:

Always take the time to read and understand the problem. Look at the examples and think through the logic. DSA isn't that hard if you think carefully.

0
Subscribe to my newsletter

Read articles from Abhinav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abhinav
Abhinav

I am B-Tech 2nd year Student (Electrical Engineering)