The Wayback Machine - https://web.archive.org/web/20240819102610/https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/
Open In App

How do Dynamic arrays work?

Last Updated : 13 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Dynamic array (vector in C++, ArrayList in Java) automatically grows when we try to make an insertion and there is no more space left for the new item. Usually the area doubles in size. A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required. The elements of the dynamic array are stored contiguously at the start of the underlying array, and the remaining positions towards the end of the underlying array are reserved, or unused. Elements can be added at the end of a dynamic array in constant time by using the reserved space until this space is completely consumed. When all space is consumed, and an additional element is to be added, the underlying fixed-sized array needs to be increased in size. Typically resizing is expensive because you have to allocate a bigger array and copy over all of the elements from the array you have overgrow before we can finally append our item. 

Approach: When we enter an element in array but array is full then you create a function, this function creates a new array double size or as you wish and copy all element from the previous array to a new array and return this new array. Also, we can reduce the size of the array. and add an element at a given position, remove the element at the end default and at the position also.

Key Features of Dynamic Array

Add Element: Add element at the end if the array size is not enough then extend the size of the array and add an element at the end of the original array as well as given index. Doing all that copying takes O(n) time, where n is the number of elements in our array. That’s an expensive cost for an append. In a fixed-length array, appends only take O(1) time. But appends take O(n) time only when we insert into a full array. And that is pretty rare, especially if we double the size of the array every time we run out of space. So in most cases appending is still O(1) time, and sometimes it’s O(n) time. In dynamic array you can create fixed-size array when required added some more element in array then use this approach:

Delete Element: Delete an element from array, default remove() method delete an element from end, simply store zero at last index and you also delete element at specific index by calling removeAt(i) method where i is index. removeAt(i) method shift all right element in the left side from the given index.

Resize of Array Size: When the array has null/zero data (aside from an element added by you) at the right side of the array, meaning it has unused memory, the method shrinkSize() can free up the extra memory. When all space is consumed, and an additional element is to be added, then the underlying fixed-size array needs to increase in size. Typically resizing is expensive because you have to allocate a bigger array and copy over all of the elements from the array you have outgrown before we can finally append our item.

Simple code for dynamic array. In below code then the array will become full of size we copy all element to new double size array(variable size array).sample code is below 

C++




#include <iostream>
using namespace std;
 
class DynamicArray {
private:
    // Pointer to store array created
    // using new keyword
    int* array = NULL;
    // Size of array
    int size;
 
    // Container size
    int capacity;
 
public:
    // Default constructor with size 1
    DynamicArray()
    {
        capacity = 1;
        size = 0;
        array = new int[capacity];
    }
 
    // Taking size from the user
    DynamicArray(int capacity)
    {
        this->capacity = capacity;
        array = new int[capacity];
        size = 0;
    }
 
    // Returns the size of Array
    // i.e Total elements stored currently
    int getSize() { return size; }
 
    // Returns the size of container
    int getCapacity() { return capacity; }
 
    // Inserting element after last stored index
    void push_back(int value)
    {
        // check is array having size to store element or
        // not
        if (size == capacity) {
 
            // if not then grow the array by double
            growArray();
        }
 
        // insert element
        array[size] = value;
        // increment the size or last_index+1
        size++;
    }
 
    // Deleting element at last stored index
    void pop_back()
    {
        // Replace the last index by 0
        array[size - 1] = 0;
 
        // Decrement the array size
        size--;
 
        // Reduce if the container half element of its
        // capacity
        if (size == (capacity / 2)) {
            shrinkArray();
        }
    }
 
    // Increase the array size by double of current capacity
    void growArray()
    {
 
        // Creating new array of double size
        int* temp = new int[capacity * 2];
 
        capacity = capacity * 2;
        // copy element of old array in newly created array
        for (int i = 0; i < size; i++) {
            temp[i] = array[i];
        }
 
        // Delete old array
        delete[] array;
 
        // Assign newly created temp array to original array
        array = temp;
    }
 
    // Reduce the size of array by half
    void shrinkArray()
    {
 
        // Creating new array of half size
        capacity = size;
        int* temp = new int[capacity];
 
        // copy element of old array in newly created array
        for (int i = 0; i < size; i++) {
            temp[i] = array[i];
        }
 
        // Delete old array
        delete[] array;
 
        // Assign newly created temp array to original array
        array = temp;
    }
 
    // Searching element in the given array
    int search(int key)
    {
        for (int i = 0; i < size; i++) {
            if (array[i] == key) {
                // If element found return its index
                return i;
            }
        }
 
        // Return -1 if element not found;
        return -1;
    }
 
    // Insert element at given index
    void insertAt(int index, int value)
    {
        // check is array having size to store element or
        // not
        if (size == capacity) {
 
            // if not then grow the array by double
            growArray();
        }
 
        for (int i = size - 1; i >= index; i--) {
            array[i + 1] = array[i];
        }
 
        array[index] = value;
        size++;
    }
 
    // Delete element at given index
    void deleteAt(int index)
    {
        for (int i = index; i < size; i++) {
            array[i] = array[i + 1];
        }
 
        // Replace the last index by 0
        array[size - 1] = 0;
 
        // Decrement the array size
        size--;
 
        // Reduce if the container half element of its
        // capacity
        if (size == (capacity / 2)) {
            shrinkArray();
        }
    }
 
    // To Print Array
    void printArrayDetails()
    {
        cout << "Elements of array : ";
        for (int i = 0; i < size; i++) {
            cout << array[i] << " ";
        }
        cout << endl;
        cout << "No of elements in array : " << size
             << ", Capacity of array :" << capacity << endl;
    }
 
    bool isEmpty()
    {
        if (size == 0) {
            return true;
        }
        else {
            return false;
        }
    }
};
 
int main()
{
    DynamicArray da;
 
    da.push_back(1);
    da.push_back(2);
    da.push_back(3);
    da.push_back(4);
    da.push_back(5);
    da.push_back(6);
    da.push_back(7);
    da.push_back(8);
    da.push_back(9);
    da.push_back(10);
    da.push_back(11);
 
    da.printArrayDetails();
 
    da.shrinkArray();
    cout << "\nCapacity of array  after shrinking : "
         << da.getCapacity() << endl;
 
    cout << "\nAfter inserting at index 3 " << endl;
    da.insertAt(3, 50);
    da.printArrayDetails();
 
    cout << "\nAfter delete last element ";
    da.pop_back();
    da.printArrayDetails();
 
    cout << "\nAfter deleting at index 3 ";
    da.deleteAt(3);
    da.printArrayDetails();
 
    cout << "\nSearching 5 in array ";
    int index = da.search(5);
    if (index != -1) {
        cout << "Element found at index : " << index << endl;
    }
    else {
        cout << "Element not found " << endl;
    }
    return 0;
}
 
// This code is contributed by Aniket Tiwari


Java




// Java program deals with all operation of a dynamic array
// add, remove, resize memory of array is the main feature
public class DynamicArray {
 
    // create three variable array[] is a array,
    // count will deal with no of element add by you and
    // size will with size of array[]
    private int array[];
    private int count;
    private int size;
    // constructor initialize value to variable
 
    public DynamicArray()
    {
        array = new int[1];
        count = 0;
        size = 1;
    }
    // function add an element at the end of array
 
    public void add(int data)
    {
 
        // check no of element is equal to size of array
        if (count == size) {
            growSize(); // make array size double
        } // insert element at end of array
        array[count] = data;
        count++;
    }
 
    // function makes size double of array
    public void growSize()
    {
 
        int temp[] = null;
        if (count == size) {
 
            // temp is a double size array of array
            // and store array elements
            temp = new int[size * 2];
            {
                for (int i = 0; i < size; i++) {
                    // copy all array value into temp
                    temp[i] = array[i];
                }
            }
        }
 
        // double size array temp initialize
        // into variable array again
        array = temp;
 
        // and make size is double also of array
        size = size * 2;
    }
 
    // function shrink size of array
    // which block unnecessary remove them
    public void shrinkSize()
    {
        int temp[] = null;
        if (count > 0) {
 
            // temp is a count size array
            // and store array elements
            temp = new int[count];
            for (int i = 0; i < count; i++) {
 
                // copy all array value into temp
                temp[i] = array[i];
            }
 
            size = count;
 
            // count size array temp initialize
            // into variable array again
            array = temp;
        }
    }
    // function add an element at given index
 
    public void addAt(int index, int data)
    {
        // if size is not enough make size double
        if (count == size) {
            growSize();
        }
 
        for (int i = count - 1; i >= index; i--) {
 
            // shift all element right
            // from given index
            array[i + 1] = array[i];
        }
 
        // insert data at given index
        array[index] = data;
        count++;
    }
 
    // function remove last element or put
    // zero at last index
    public void remove()
    {
        if (count > 0) {
            array[count - 1] = 0;
            count--;
        }
    }
 
    // function shift all element of right
    // side from given index in left
    public void removeAt(int index)
    {
        if (count > 0) {
            for (int i = index; i < count - 1; i++) {
 
                // shift all element of right
                // side from given index in left
                array[i] = array[i + 1];
            }
            array[count - 1] = 0;
            count--;
        }
    }
 
    public static void main(String[] args)
    {
        DynamicArray da = new DynamicArray();
 
        // add 9 elements in array
        da.add(1);
        da.add(2);
        da.add(3);
        da.add(4);
        da.add(5);
        da.add(6);
        da.add(7);
        da.add(8);
        da.add(9);
 
        // print all array elements after add 9 elements
        System.out.println("Elements of array:");
        for (int i = 0; i < da.size; i++) {
            System.out.print(da.array[i] + " ");
        }
 
        System.out.println();
 
        // print size of array and no of element
        System.out.println("Size of array: " + da.size);
        System.out.println("No of elements in array: "
                           + da.count);
 
        // shrinkSize of array
        da.shrinkSize();
 
        // print all array elements
        System.out.println("Elements of array "
                           + "after shrinkSize of array:");
        for (int i = 0; i < da.size; i++) {
            System.out.print(da.array[i] + " ");
        }
        System.out.println();
 
        // print size of array and no of element
        System.out.println("Size of array: " + da.size);
        System.out.println("No of elements in array: "
                           + da.count);
 
        // add an element at index 1
        da.addAt(1, 22);
 
        // print Elements of array after adding an
        // element at index 1
        System.out.println("Elements of array after"
                           + " add an element at index 1:");
        for (int i = 0; i < da.size; i++) {
            System.out.print(da.array[i] + " ");
        }
 
        System.out.println();
 
        // print size of array and no of element
        System.out.println("Size of array: " + da.size);
        System.out.println("No of elements in array: "
                           + da.count);
 
        // delete last element
        da.remove();
 
        // print Elements of array after delete last
        // element
        System.out.println("Elements of array after"
                           + " delete last element:");
        for (int i = 0; i < da.size; i++) {
            System.out.print(da.array[i] + " ");
        }
 
        System.out.println();
 
        // print size of array and no of element
        System.out.println("Size of array: " + da.size);
        System.out.println("No of elements in array: "
                           + da.count);
 
        // delete element at index 1
        da.removeAt(1);
 
        // print Elements of array after delete
        // an element index 1
        System.out.println("Elements of array after"
                           + " delete element at index 1:");
        for (int i = 0; i < da.size; i++) {
            System.out.print(da.array[i] + " ");
        }
        System.out.println();
 
        // print size of array and no of element
        System.out.println("Size of array: " + da.size);
        System.out.println("No of elements in array: "
                           + da.count);
    }
}


Python3




# Python 3 program deals with all operation of a dynamic array
# add, remove, resize memory of array is the main feature
 
 
class DynamicArray:
 
    # create three variable array[] is a array,
    # count will deal with no of element add by you and
    # size will with size of array[]
    array = None
    count = 0
    size = 0
 
    # constructor initialize value to variable
    def __init__(self):
        self.array = [0] * (1)
        self.count = 0
        self.size = 1
 
    # function add an element at the end of array
    def add(self, data):
 
        # check no of element is equal to size of array
        if (self.count == self.size):
            self.growSize()
 
        # insert element at end of array
        self.array[self.count] = data
        self.count += 1
 
    # function makes size double of array
    def growSize(self):
        temp = None
        if (self.count == self.size):
 
            # temp is a double size array of array
            # and store array elements
            temp = [0] * (self.size * 2)
            i = 0
            while (i < self.size):
 
                # copy all array value into temp
                temp[i] = self.array[i]
                i += 1
 
        # double size array temp initialize
        # into variable array again
        self.array = temp
 
        # and make size is double also of array
        self.size = self.size * 2
 
    # function shrink size of array
    # which block unnecessary remove them
    def shrinkSize(self):
        temp = None
        if (self.count > 0):
 
            # temp is a count size array
            # and store array elements
            temp = [0] * (self.count)
            i = 0
            while (i < self.count):
 
                # copy all array value into temp
                temp[i] = self.array[i]
                i += 1
            self.size = self.count
 
            # count size array temp initialize
            # into variable array again
            self.array = temp
 
    # function add an element at given index
    def addAt(self, index,  data):
 
        # if size is not enough make size double
        if (self.count == self.size):
            self.growSize()
        i = self.count - 1
        while (i >= index):
 
            # shift all element right
            # from given index
            self.array[i + 1] = self.array[i]
            i -= 1
 
        # insert data at given index
        self.array[index] = data
        self.count += 1
 
    # function remove last element or put
    # zero at last index
    def remove(self):
        if (self.count > 0):
            self.array[self.count - 1] = 0
            self.count -= 1
    # function shift all element of right
    # side from given index in left
 
    def removeAt(self, index):
        if (self.count > 0):
            i = index
            while (i < self.count - 1):
 
                # shift all element of right
                # side from given index in left
                self.array[i] = self.array[i + 1]
                i += 1
            self.array[self.count - 1] = 0
            self.count -= 1
 
    @staticmethod
    def main(args):
        da = DynamicArray()
 
        # add 9 elements in array
        da.add(1)
        da.add(2)
        da.add(3)
        da.add(4)
        da.add(5)
        da.add(6)
        da.add(7)
        da.add(8)
        da.add(9)
 
        # print all array elements after add 9 elements
        print("Elements of array:")
        i = 0
        while (i < da.size):
            print(str(da.array[i]) + " ", end="")
            i += 1
        print()
 
        # print size of array and no of element
        print("Size of array: " + str(da.size))
        print("No of elements in array: " + str(da.count))
 
        # shrinkSize of array
        da.shrinkSize()
 
        # print all array elements
        print("Elements of array after shrinkSize of array:")
        i = 0
        while (i < da.size):
            print(str(da.array[i]) + " ", end="")
            i += 1
        print()
 
        # print size of array and no of element
        print("Size of array: " + str(da.size))
        print("No of elements in array: " + str(da.count))
 
        # add an element at index 1
        da.addAt(1, 22)
 
        # print Elements of array after adding an
        # element at index 1
        print("Elements of array after add an element at index 1:")
        i = 0
        while (i < da.size):
            print(str(da.array[i]) + " ", end="")
            i += 1
        print()
 
        # print size of array and no of element
        print("Size of array: " + str(da.size))
        print("No of elements in array: " + str(da.count))
 
        # delete last element
        da.remove()
 
        # print Elements of array after delete last
        # element
        print("Elements of array after delete last element:")
        i = 0
        while (i < da.size):
            print(str(da.array[i]) + " ", end="")
            i += 1
        print()
 
        # print size of array and no of element
        print("Size of array: " + str(da.size))
        print("No of elements in array: " + str(da.count))
 
        # delete element at index 1
        da.removeAt(1)
 
        # print Elements of array after delete
        # an element index 1
        print("Elements of array after delete element at index 1:")
        i = 0
        while (i < da.size):
            print(str(da.array[i]) + " ", end="")
            i += 1
        print()
 
        # print size of array and no of element
        print("Size of array: " + str(da.size))
        print("No of elements in array: " + str(da.count))
 
 
# Driver code
if __name__ == "__main__":
    DynamicArray.main([])
 
    # This code is contributed by aadityaburujwale.


C#




// C# program deals with all operation
// of dynamic array add, remove, resize
// memory of array is the main feature
using System;
 
public class DynamicArray {
 
    // create three variable array[] is
    // a array, count will deal with no
    // of element add by you and
    // size will with size of array[]
    private int[] array;
    private int count;
    private int size;
 
    // constructor initialize value to variable
    public DynamicArray()
    {
        array = new int[1];
        count = 0;
        size = 1;
    }
 
    // function add an element at the end of array
    public void add(int data)
    {
 
        // check no of element is equal to size of array
        if (count == size) {
            growSize(); // make array size double
        }
 
        // insert element at end of array
        array[count] = data;
        count++;
    }
 
    // function makes size double of array
    public void growSize()
    {
 
        int[] temp = null;
        if (count == size) {
 
            // temp is a double size array of array
            // and store array elements
            temp = new int[size * 2];
            {
                for (int i = 0; i < size; i++) {
                    // copy all array value into temp
                    temp[i] = array[i];
                }
            }
        }
 
        // double size array temp initialize
        // into variable array again
        array = temp;
 
        // and make size is double also of array
        size = size * 2;
    }
 
    // function shrink size of array
    // which block unnecessary remove them
    public void shrinkSize()
    {
        int[] temp = null;
        if (count > 0) {
 
            // temp is a count size array
            // and store array elements
            temp = new int[count];
            for (int i = 0; i < count; i++) {
 
                // copy all array value into temp
                temp[i] = array[i];
            }
 
            size = count;
 
            // count size array temp initialize
            // into variable array again
            array = temp;
        }
    }
 
    // function add an element at given index
    public void addAt(int index, int data)
    {
        // if size is not enough make size double
        if (count == size) {
            growSize();
        }
 
        for (int i = count - 1; i >= index; i--) {
 
            // shift all element right
            // from given index
            array[i + 1] = array[i];
        }
 
        // insert data at given index
        array[index] = data;
        count++;
    }
 
    // function remove last element or put
    // zero at last index
    public void remove()
    {
        if (count > 0) {
            array[count - 1] = 0;
            count--;
        }
    }
 
    // function shift all element of right
    // side from given index in left
    public void removeAt(int index)
    {
        if (count > 0) {
            for (int i = index; i < count - 1; i++) {
 
                // shift all element of right
                // side from given index in left
                array[i] = array[i + 1];
            }
            array[count - 1] = 0;
            count--;
        }
    }
 
    // Driver code
    public static void Main()
    {
        DynamicArray da = new DynamicArray();
 
        // add 9 elements in array
        da.add(1);
        da.add(2);
        da.add(3);
        da.add(4);
        da.add(5);
        da.add(6);
        da.add(7);
        da.add(8);
        da.add(9);
 
        // print all array elements after add 9 elements
        Console.WriteLine("Elements of array:");
        for (int i = 0; i < da.size; i++) {
            Console.Write(da.array[i] + " ");
        }
 
        Console.WriteLine();
 
        // print size of array and no of element
        Console.WriteLine("Size of array: " + da.size);
        Console.WriteLine("No of elements in array: "
                          + da.count);
 
        // shrinkSize of array
        da.shrinkSize();
 
        // print all array elements
        Console.WriteLine("Elements of array "
                          + "after shrinkSize of array:");
        for (int i = 0; i < da.size; i++) {
            Console.Write(da.array[i] + " ");
        }
        Console.WriteLine();
 
        // print size of array and no of element
        Console.WriteLine("Size of array: " + da.size);
        Console.WriteLine("No of elements in array: "
                          + da.count);
 
        // add an element at index 1
        da.addAt(1, 22);
 
        // print Elements of array after adding an
        // element at index 1
        Console.WriteLine("Elements of array after"
                          + " add an element at index 1:");
        for (int i = 0; i < da.size; i++) {
            Console.Write(da.array[i] + " ");
        }
 
        Console.WriteLine();
 
        // print size of array and no of element
        Console.WriteLine("Size of array: " + da.size);
        Console.WriteLine("No of elements in array: "
                          + da.count);
 
        // delete last element
        da.remove();
 
        // print Elements of array after delete last
        // element
        Console.WriteLine("Elements of array after"
                          + " delete last element:");
        for (int i = 0; i < da.size; i++) {
            Console.Write(da.array[i] + " ");
        }
 
        Console.WriteLine();
 
        // print size of array and no of element
        Console.WriteLine("Size of array: " + da.size);
        Console.WriteLine("No of elements in array: "
                          + da.count);
 
        // delete element at index 1
        da.removeAt(1);
 
        // print Elements of array after delete
        // an element index 1
        Console.WriteLine("Elements of array after"
                          + " delete element at index 1:");
        for (int i = 0; i < da.size; i++) {
            Console.Write(da.array[i] + " ");
        }
        Console.WriteLine();
 
        // print size of array and no of element
        Console.WriteLine("Size of array: " + da.size);
        Console.WriteLine("No of elements in array: "
                          + da.count);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript




class DynamicArray {
    // Pointer to store array created using new keyword
    #array;
    // Size of array
    #size;
    // Container size
    #capacity;
 
    // Default constructor with size 1
    constructor() {
        this.#capacity = 1;
        this.#size = 0;
        this.#array = new Array(this.#capacity);
    }
 
    // Taking size from the user
    // constructor(capacity) {
    // this.#capacity = capacity;
    // this.#array = new Array(this.#capacity);
    // this.#size = 0;
    // }
 
    // Returns the size of Array i.e Total elements stored currently
    getSize() {
        return this.#size;
    }
 
    // Returns the size of container
    getCapacity() {
        return this.#capacity;
    }
 
    // Inserting element after last stored index
    push_back(value) {
        // check is array having size to store element or not
        if (this.#size == this.#capacity) {
            // if not then grow the array by double
            this.growArray();
        }
        // insert element
        this.#array[this.#size] = value;
        // increment the size or last_index+1
        this.#size++;
    }
 
    // Deleting element at last stored index
    pop_back() {
        // Replace the last index by 0
        this.#array[this.#size - 1] = 0;
        // Decrement the array size
        this.#size--;
        // Reduce if the container half element of its capacity
        if (this.#size == Math.floor(this.#capacity / 2)) {
            this.shrinkArray();
        }
    }
 
    // Increase the array size by double of current capacity
    growArray() {
        // Creating new array of double size
        let temp = new Array(this.#capacity * 2);
        this.#capacity = this.#capacity * 2;
        // copy element of old array in newly created array
        for (let i = 0; i < this.#size; i++) {
            temp[i] = this.#array[i];
        }
        // Delete old array
        this.#array = null;
        // Assign newly created temp array to original array
        this.#array = temp;
    }
 
    // Reduce the size of array by half
    shrinkArray() {
        // Creating new array of half size
        this.#capacity = this.#size;
        let temp = new Array(this.#capacity);
        // copy element of old array in newly created array
        for (let i = 0; i < this.#size; i++) {
            temp[i] = this.#array[i];
        }
        // Delete old array
        this.#array = null;
        // Assign newly created temp array to original array
        this.#array = temp;
    }
 
    // Searching element in the given array
    search(key) {
        for (let i = 0; i < this.#size; i++) {
            if (this.#array[i] == key) {
                // If element found return its index
                return i;
            }
        }
        // Return -1 if element not found;
        return -1;
    }
 
    // Insert element at given index
    insertAt(index, value) {
        // check is array having size to store element or not
        if (this.#size == this.#capacity) {
            // if not then grow the array by double
            this.growArray();
        }
        for (let i = this.#size - 1; i >= index; i--) {
            this.#array[i + 1] = this.#array[i];
        }
        this.#array[index] = value;
        this.#size++;
    }
 
    // Delete element at given index
    // Delete element at given index
    deleteAt(index) {
        for (let i = index; i < this.#size; i++) {
            this.#array[i] = this.#array[i + 1];
        }
 
        // Replace the last index by 0
        this.#array[this.#size - 1] = 0;
 
        // Decrement the array size
        this.#size--;
 
        // Reduce if the container half element of its
        // capacity
        if (this.#size == (this.#capacity / 2)) {
            shrinkArray();
        }
    }
 
    // To Print Array
    printArrayDetails() {
        console.log("Elements of array : ");
        console.log(this.#array);
        console.log("No of elements in array : ", this.#size
            , ", Capacity of array :", this.#capacity);
    }
 
    isEmpty() {
        if (size == 0) {
            return true;
        }
        else {
            return false;
        }
    }
};
 
const da = new DynamicArray();
 
da.push_back(1);
da.push_back(2);
da.push_back(3);
da.push_back(4);
da.push_back(5);
da.push_back(6);
da.push_back(7);
da.push_back(8);
da.push_back(9);
da.push_back(10);
da.push_back(11);
 
da.printArrayDetails();
 
da.shrinkArray();
console.log("\nCapacity of array  after shrinking : "
    , da.getCapacity());
 
console.log("\nAfter inserting at index 3 ");
da.insertAt(3, 50);
da.printArrayDetails();
 
console.log("\nAfter delete last element ");
da.pop_back();
da.printArrayDetails();
 
console.log("\nAfter deleting at index 3 ");
da.deleteAt(3);
da.printArrayDetails();
 
console.log("\nSearching 5 in array ");
let index = da.search(5);
if (index >= 0) {
    console.log("Element found at index : ", index);
}
else {
    console.log("Element not found ");
}
 
// This code is contributed by akashish__


Output

Elements of array : 1 2 3 4 5 6 7 8 9 10 11 
No of elements in array : 11, Capacity of array :16

Capacity of array  after shrinking : 11

After inserting at index 3 
Elements of array : 1 2 3 50 4 5 6 7 8 9 10 11 
No of elements in array : 12, Capacity of array :22

After delete last element Elements of array : 1 2 3 50 4 5 6 7 8 9 10 
No of elements in array : 11, Capacity of array :11

After deleting at index 3 Elements of array : 1 2 3 4 5 6 7 8 9 10 
No of elements in array : 10, Capacity of array :11

Searching 5 in array Element found at index : 4


Similar Reads

Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basically two types of arrays: Static Array: In this type
5 min read
How Does Dynamic Programming Work?
Dynamic programming, popularly known as DP, is a method of solving problems by breaking them down into simple, overlapping subproblems and then solving each of the subproblems only once, storing the solutions to the subproblems that are solved to avoid redundant computations. This technique is useful for optimization-based problems, where the goal
15 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12, 1} Output : 22 Explanation: Here, one way to get m
5 min read
Merge k sorted arrays | Set 2 (Different Sized Arrays)
Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ;Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ;Output: 1 2 3 4 6 20 We have discussed a solution that works for all arrays of the same size in Merge k sorted a
7 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Count of possible arrays from prefix-sum and suffix-sum arrays
Given 2*N integers which are elements of a prefix and suffix array(in shuffled order) of an array of size N, the task is to find the no of possible array's of the size N which can be made from these elements Examples: Input: arr[] = {5, 2, 3, 5} Output: 2 Explanation: 1st array can be : {2, 3} Its prefix array:{2, 5} Its suffix array:{5, 3} 2nd arr
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array storing any type of object can be Integer, String or
3 min read
Count of possible unique arrays after swapping elements at same index of given Arrays
Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[] = {1, 2, 3, 4}, arr2[] = {2, 1, 4, 3}, N = 4Outpu
12 min read
Overlapping Subproblems Property in Dynamic Programming | DP-1
Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem can be solved using Dynamic programming. Overlapp
10 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Introduction to Dynamic Programming on Trees
Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied on trees to solve some specific problems.Pre-requisite: DFSGiven a tree with N nodes and N-1 edges
10 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Dynamic Fragment in Android
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments are more responsive and flexible than Static Fragme
4 min read
Sorting a dynamic 2-dimensional array of Strings
Prerequisite: How to dynamically allocate a 2D array in C? Double pointer: A pointer pointing to another pointer is known as a Double pointer. To represent the double pointer ' ** ' is used. Double pointer is also called as pointer to pointer. Example: Input: Geeks, Gfg, Placement, Sudo, Gate Output: Gate, Geeks, Gfg, Placement, Sudo The idea is to
5 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.Examples:
9 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Implement dynamic deque using templates class and a circular array
The task is to implement a dynamic Deque using templates class and a circular array, having the following functionalities: front(): Get the front item from the deque.back(): Get the last item from the deque.push_back(X): Push X at the end of the deque.push_front(X): Push X at the start of the deque.pop_front(): Delete an element from the start of t
9 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1-&gt;3-&gt;2-&gt;4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read
Count of numbers from range [L, R] whose sum of digits is Y using Dynamic Programming
Pre-requisites: Recursion, Dynamic Programming, Digit DP Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples: Input: L = 0, R = 11, Y = 2 Output: 2 2 -&gt; 2 11 -&gt; 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3 Constraints: 0 &lt;= L &lt;= R &lt;=
10 min read
Minimum time required to rot all oranges | Dynamic Programming
Given a matrix of dimension m * n where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges So the task is to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh or
15 min read
Extendible Hashing (Dynamic approach to DBMS)
Extendible Hashing is a dynamic hashing method wherein directories, and buckets are used to hash data. It is an aggressively flexible method in which the hash function also experiences dynamic changes. Main features of Extendible Hashing: The main features in this hashing technique are: Directories: The directories store addresses of the buckets in
7 min read
Reliability Design Problem in Dynamic Programming
The reliability design problem is the designing of a system composed of several devices connected in series or parallel. Reliability means the probability to get the success of the device. Let's say, we have to set up a system consisting of D1, D2, D3, ............, and Dn devices, each device has some costs C1, C2, C3, ........, Cn. Each device ha
6 min read
Convert N to M with given operations using dynamic programming
Given two integers N and M and the task is to convert N to M with the following operations: Multiply N by 2 i.e. N = N * 2.Subtract 1 from N i.e. N = N - 1. Examples: Input: N = 4, M = 6 Output: 2 Perform operation 2: N = N - 1 = 4 - 1 = 3 Perform operation 1: N = N * 2 = 3 * 2 = 6 Input: N = 10, M = 1 Output: 9 Approach: Create an array dp[] of si
7 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
three90RightbarBannerImg