Arrays, Matrices, and Tensors

Array

An array is a simple data structure that consists of a collection of elements, each identified by an index or a key. It is a fundamental structure used to store multiple items of the same type together.

Space Complexity: O(n)
Time Complexity: O(1) for access and update
Best Case: Ω(1)
Average Case: Θ(1)
Worst Case: O(1)


class Array:
    def __init__(self, size):
        self.items = [random.randint(0, 100) for _ in range(size)]

    def get(self, index):
        return self.items[index]

    def set(self, index, value):
        self.items[index] = value

    def display(self):
        return ' -> '.join(map(str, self.items))

# Example Usage
arr = Array(10)
arr.display()

Matrix

A matrix is a two-dimensional array. It consists of rows and columns, allowing for the storage of data in a grid format. Matrices are widely used in mathematics, physics, and engineering.

Space Complexity: O(n²)
Time Complexity: O(1) for access and update
Best Case: Ω(1)
Average Case: Θ(1)
Worst Case: O(1)


class Matrix:
    def __init__(self, rows, cols):
        self.items = [[random.randint(0, 100) for _ in range(cols)] for _ in range(rows)]

    def get(self, row, col):
        return self.items[row][col]

    def set(self, row, col, value):
        self.items[row][col] = value

    def display(self):
        return '\n'.join([' -> '.join(map(str, row)) for row in self.items])

# Example Usage
matrix = Matrix(3, 3)
matrix.display()

Tensor

A tensor is a multi-dimensional array. It generalizes the concept of matrices to higher dimensions. Tensors are essential in fields such as physics, computer graphics, and machine learning.

Space Complexity: O(n³)
Time Complexity: O(1) for access and update
Best Case: Ω(1)
Average Case: Θ(1)
Worst Case: O(1)


class Tensor:
    def __init__(self, dim1, dim2, dim3):
        self.items = [[[random.randint(0, 100) for _ in range(dim3)] for _ in range(dim2)] for _ in range(dim1)]

    def get(self, dim1, dim2, dim3):
        return self.items[dim1][dim2][dim3]

    def set(self, dim1, dim2, dim3, value):
        self.items[dim1][dim2][dim3] = value

    def display(self):
        return '\n\n'.join(['\n'.join([' -> '.join(map(str, row)) for row in matrix]) for matrix in self.items])

# Example Usage
tensor = Tensor(2, 2, 2)
tensor.display()

Time Complexity Comparison

Space Complexity Comparison