0% found this document useful (0 votes)
8 views71 pages

2 Arrays

Uploaded by

aamirneyazi92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views71 pages

2 Arrays

Uploaded by

aamirneyazi92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Chapter 4

Array
Table of Contents
4.1 Introduction ...................................................................................................................................... 4
4.1.1 Definition ................................................................................................................................... 5
4.1.1.1 Properties of an Array: ....................................................................................................... 5
4.1.1.2 Declaration of an array: ..................................................................................................... 6
4.1.1.3 Accessing the array elements ............................................................................................ 6
4.1.1.4 Memory representation..................................................................................................... 7
4.2 Types of the Arrays........................................................................................................................... 8
4.2.1 One-Dimensional array ............................................................................................................. 8
4.2.2 Two-Dimensional Array ............................................................................................................ 9
4.2.3 Three-Dimensional Array ........................................................................................................ 12
4.3 Index Formula Derivation for Array............................................................................................... 13
4.3.1 One Dimensional Array ........................................................................................................... 13
4.3.2 Two-Dimensional Array .......................................................................................................... 16
4.3.2.1 Row Major Order Arrangement....................................................................................... 16
4.3.2.1 Column Major Order Arrangement ................................................................................. 18
4.3.3 Three–Dimensional Array ....................................................................................................... 20
4.3.3.1 Row Major Order Arrangement....................................................................................... 20
4.3.3.2 Column Major Order Arrangement ................................................................................. 22
4.3.4 N-Dimensional Array ............................................................................................................... 25
4.4 Primitive operations on Array ....................................................................................................... 26
4.4.1 Traversal .................................................................................................................................. 26
4.4.2 Insertion .................................................................................................................................. 27
4.4.3 Deletion ................................................................................................................................... 28
4.5 Application Problems Related to Array ......................................................................................... 29
4.5.1 Insertion in sorted 1-D array................................................................................................... 29
4.5.2 Finding the number which is not repeated in Array of integers ........................................... 30
4.5.3 Merging of two sorted arrays ................................................................................................. 31
4.5.4 Finding the elements of one set that does not belong to the other set ............................... 33
4.5.5 Set Union operation ................................................................................................................ 34
4.5.6 Set Intersection Operation ..................................................................................................... 37
4.5.7 Set Difference Operation ........................................................................................................ 38
4.5.8 Symmetric Difference of two sets .......................................................................................... 40
4.6 Applications of 2-D Arrays ............................................................................................................. 43
4.6.1 Matrix Operations through Array ........................................................................................... 43
4.6.1.1 Matrix Traversal ............................................................................................................... 44
4.6.1.2 Matrix Addition ................................................................................................................ 45
4.6.1.3 Matrix Subtraction ........................................................................................................... 46
4.6.1.4 Matrix Multiplication ....................................................................................................... 47
4.6.1.5 Transpose of a matrix ...................................................................................................... 48
4.6.1.6 Determinant of a Matrix .................................................................................................. 49
4.7 Types of Problem in Array.............................................................................................................. 50
4.7.1 Type 1: Rotation Type Problem .............................................................................................. 50
4.7.2 Type 2: Arrangement and de–arrangement problem ............................................................ 52
4.7.3 Type 3: Order Statistics Problem ............................................................................................ 54
4.7.4 Type 4: Range query problem ................................................................................................. 55
4.7.5 Type 5: Optimization problem ................................................................................................ 56
4.7.6 Type 6: Sorting problem .......................................................................................................... 58
4.7.7 Type 7: Searching Problem ..................................................................................................... 60
4.8 Generic Array.................................................................................................................................. 61
4.9 Competitive Coding Questions ...................................................................................................... 62
Multiple Choice Questions ................................................................................................................... 66
4.1 Introduction

Suppose we want to store the marks of 10 students as shown in the below figure.

This can be done in two ways: by declaring different 10 variables to store marks of an
individual student or we can think of defining an array to store all these elements under one
name.

Method 1: Requires taking 10 different variables M1, M2, M3 … M10.


M1 = 12
M2 = 15
M3 = 10

M10 = 14

Method 2: Storing of marks under a single array variable sequentially.

We can see that using method 1 we need to remember the names of the 10 variables but
In method 2 we need to remember only one variable name to access the elements.
The data structure that stores elements of the same type and access using one name is
known as Array.

We will learn the concept of array as data structure in detail, terminologies, address
calculation, various algorithms around arrays etc., in this chapter.

4.1.1 Definition
An array is a data structure that is used to collect multiple values of the same data type
together into one variable. The idea is to store multiple items of the same type together.

Example: In the below image, we have shown an array containing age of five students. The
name of the array is “Age”. All the elements stored in Age array is of the same datatype. So,
in place of taking five different variables to store the age of 5 students, we took only one
variable name “Age”.

4.1.1.1 Properties of an Array:


• It is a linear data structure.
• It stores the elements of the same data type. So, it comes under the category of
homogenous data structure.
• The elements are stored at contiguous memory locations in an array.

• Arrays have a fixed size where the size of the array is defined when the array is
declared. In the below given figure, the size of the array is fixed i.e., the size 5 is fixed
and we cannot add one more element in the array.

• Array can also be termed as subscripted (details shared later in the chapter) variable.

4.1.1.2 Declaration of an array:


Arrays are declared in various ways in different languages. Generally, we do three things to
declare an array.
- Provide a name to an array.
- Define the type of elements that it will store i.e. Data type of element you want to
store in an array.
- Define its size (the maximum number of elements) i.e. Length of the array.

Example:
In C language, we declare array as shown below:
<data_type> <name_of_array>[<size_of_array>];

To store 6 integers in an array with name A, we declared it as


int A[6]; // here A is the name of array, int is the data type and 6 is the length of the array A.

4.1.1.3 Accessing the array elements


The amazing power of arrays comes from their efficiency in accessing their elements. To
perform any operation on array, accessing the element is necessary. Accessing an element in
an array means to read the element stored at a location in an array with the help of the index
value of the array. In accessing the elements of an array, indices play an important role.
Indices:
This is a number that refers to the location where the value is stored. It is also called an
“index” (“indices” in plural) or ”subscript."

As you can see in the diagram below, the first element in the array is referred to using index
0. As you move further to the right, the index increases by one for each space in the
memory.

The general syntax to access an element is: <name_of_array>[<index>]

Example:
To access the first element of Age array (as declare above), we write Age[0] and to access the
third element of Age array, we will write Age[2], as shown in the figure given below.

Note: There are 3 types of indexing provided by different languages to access the array.

0 (zero-based indexing): The first element of the array is indexed by a subscript 0. The index
of nth element is “n-1” in this case. (C, C++, etc.).

1 (one-based indexing): The first element of the array is indexed by the subscript 1. (Basic,
MATLAB, R, Mathematica

n (n-based indexing): The base index of an array can be freely chosen. Usually, programming
languages allowing n-based indexing also allow negative index values. (Fortran, Pascal,
ALGOL, etc.)

4.1.1.4 Memory representation


Having understood the way to access the elements, let us see how arrays are stored in the
computer's memory.
When you define the size of the array, all the required space for array is “reserved” in
memory. (Static memory allocation)

Note: If you do not fill the array with values, that space will be kept reserved and empty.

Example:
Let us say that we define an Age array of size 5 but only insert one value. All that remaining
space will be empty and “reserved” in memory, waiting for future assignments.

As we know, in Array all the elements are stored in contiguous spaces in memory (as shown
in the above figure above, 301, 302, 303, 304, 305 are contiguous memory locations for
storing age of 5 students in the array of size 5). This way, the computer knows exactly where
to look to find the information you requested when you want to access any element of an
array.

The array is represented in various ways based on the number of dimensions. In the below
mentioned topic, we will see various types of array and the application of various concepts
mentioned above on an array.

4.2 Types of the Arrays

Based on the dimension, various types of arrays can be defined. Such as for one dimension,
we have one-dimensional array. For two dimensions we have 2-dimensional array and so on.

Here we will see various concepts for the below mentioned types of arrays:
1. One-Dimensional array
2. Two-Dimensional array
3. Three-Dimensional array

4.2.1 One-Dimensional array


A one-dimensional array (or single dimension array) is an array with one subscript only.

Declaration of one-dimensional array


Syntax: <Data Type> <Arrayname> [<Array_Size>]
Example: Declaration of one-dimensional array "A" having "int" data type and size 10
elements in C. int A[10]

Accessing the element in one-dimensional array


Accessing its elements involves a single subscript.

Syntax: Arrayname[index]
Example:
To access 2nd element in the above-mentioned array A, we write A[1]
To access 9th element in the above-mentioned array A, we write A[8]
(Here, we that assume the first index is 0)

Memory Representation of one-dimensional array


The memory representation of one-dimensional array is shown in below diagram.

In the above diagram A[0], A[1], A[2],. . . , A[9] are the array elements. The address mentioned
for these elements represent the physical location of data elements in the main memory. It is
assumed that each element requires 4 bytes for storage in this scenario.
(In most of the programming languages, the index is considered to be starting from 0)

4.2.2 Two-Dimensional Array


A two-dimensional array (2-D array) has two subscripts. The elements are stored in the form
of rows and columns. It can also be termed as an array of one-dimensional arrays.
Matrix is an example of two-dimensional array. Consider a matrix that involves rows and
columns for storage of the elements, as shown in below diagram.
If the number of rows in the matrix is m and columns is n, then there will be m x n elements
in the matrix.
As shown in the above figure, there are 6 rows and 5 columns, so total number of elements
is 6 X 5 = 30.

Declaration the two-dimensional array:


Syntax: <Data Type> <Arrayname> [m][n]
Where,
m → Number of rows
n → Number of columns

Example: Declaration of two-dimensional array “A” having “int” datatype and row size 6 and
column size 5. int A[6][5]

Accessing the element in two-dimensional array


Accessing its elements involves two subscripts; one for row and second for column.

Syntax: Arrayname[ row_index][column_index]


Example:
To access 2nd element of 1st row in the above-mentioned array A, we write A[0][1]
To access 9th element of 3rd row in the above-mentioned array A, we write A[2][8]
(Here, we assume the first index for row and column is 0)

Memory Representation of two-dimensional array:


There are two-ways by which the 2D array elements can be represented in Memory.
a) Row-major Representation
b) Column-major Representation
Some programming languages support row-major order representation, such as
C/C++/Objective-C (for C-style arrays), PL/I, Pascal, Speakeasy, SAS, and Rasdaman.

Similarly, languages that support column-major order representation are: Fortran, MATLAB,
GNU Octave, S-Plus, R, Julia, and Scilab.

Row-major Representation: In row-major order, storage of the elements in the memory is


row-wise i.e. storage of elements of first row is followed by the storage of elements of second
row and so on so forth.

Column-major Representation: In column-major order, elements are stored column wise i.e.,
storage of elements of the first column followed by storage of second column elements and
so on so forth.
4.2.3 Three-Dimensional Array
When an array is represented in the form of 3 different dimensions, it is called 3-D Array. It
can also be called as an array of 2-dimensional arrays.
Below given diagram shows a 3-Dimensional array which has 3 dimensions named U1, U2, and
U3.

If the array is declared as A[3][4][5], it will have a total of 3 x 4 x 5 = 60 elements.

Declaration of three-dimensional array:


Syntax: <Data Type> <Arrayname> [m][n][o]
Where,
m → 1st Dimension
n → 2nd Dimension
o → 3rd Dimension

Example: Declaration of three-dimensional array “A” having “int” datatype with first
dimension size 6, second dimension size 5, third dimension size 4. int A[6][5][4]

Accessing the element in three-dimensional array


Accessing its elements involves three subscripts, one for each dimension.
Syntax: Arrayname[index1][index2][index3]
Memory Representation in Row Major Order

Here, the first dimension is considered as row.


(Here, we assume the first index for row and column is 0)
In the similar way Column major order arrangement can be done. This is left to the readers
to prepare the memory representation in Column Major Order.

4.3 Index Formula Derivation for Array


The programming languages do use the index formula computation to reach to the address
of desired element in the memory. In this section, we are explaining the index formula
derivation for 1-D, 2-D, 3-D and N-D arrays.

4.3.1 One Dimensional Array


In a given array if the Base Address (which is the address of first element in the memory) is
known, we can find the address of any other element in an array.

Suppose there is a one-dimensional array A[L : U] where L is the first index and U is the last
index in the array.

Number of elements /lengths of the array can be found by the formula N = U – L + 1

Where U = Upper Bound of the array (Last index)


L = Lower Bound of the array (First index)

Examples:

1. A[0:9] has
N = 9-0+1
= 10 elements

2. A[2:18] has
N = 18-2+1
= 17 elements
Step 1: To find the address of ith index element, we will take two assumptions

In the first step, we will derive the equation to find the address of ith index element on the
basis of below mentioned assumptions:

Assumption 1: 1 Byte storage for each element.


Assumption 2: First element is at index 1.

• Suppose we have been given the base address of an array, say α.


• So, in consideration of the above-mentioned assumptions,
//address of 1st element of array A as given.
address of A[1]= α
//address of 2nd element of array A is address of base address + no. of bytes
i.e.1 (α +1)
address of A[2]= α +1
//address of 3rd element of array A is address of 2nd element + no. of bytes i.e.1
(α +1+1)
address of A[3]= α +2
//address of 4th element of array A is address of 3rd element + no. of bytes i.e.1
((α +1+1+1)
address of A[4]= α +3
And so on…
address of A[i]= α + (i-1) ………………. (equation 1)

Now, let us remove the assumptions one by one in subsequent steps to derive a generalized
formula.

Step 2: Removal of first assumption i.e., 1 Byte storage for each element.

First, we remove the assumption that each element requires 1 byte with n bytes for storage
per element.

Then, to get the address of A[i] we will multiply the number of bytes for storage (n bytes) in
equation 1 except α.

A[i]= α +(i-1) *n ………………. (equation 2)

Step 3: Removal of 2nd Assumption, i.e. First element is at index 1.

If index starts from L then, for some ith index element distance from first index will be i-L+1.
Address of A[i]= α +(i-1) *n //As given in equation 2.
Replacing i with i-L+1
Address of A[i] = α + (i-L+1-1) *n
So, Address of A[i] = α +(i-L) *n

Address of A[i] = Base Address +n*(i – Lower Bound)

Example:
Given A [-1:10], bytes per cell = 4, base address = 2000 find the address of A [7].
Solution:
Here, i = 7
n= 4
Lower Bound = -1
Upper Bound = 10
Address of A [i] = Base Address +n*(i-Lower Bound)
Address of A [7] = 2000 + 4*(7-(-1)) = 2032

Example:
Given A [1:15], bytes per cell = 3, base address = 1000 find the address of A [9].
Solution:
Here, i = 9
n= 3
Lower Bound = 1
Upper Bound = 15
Address of A [i] = Base Address +n*(i-Lower Bound)
Address of A [9] = 1000 + 3*(9 - 1)
= 1024

Question: Why does indexing in most of the languages start with 0?


Answer: In address calculation we can skip the offset value. E.g. A[10] = {1,2,3,4,5,6,7,8,9,10}.
If we start the indexing with 1, calculation of address of A[5] = 1000+(5-1)*2
If we start the indexing with 0, calculation of address of A[5] = 1000+(5-0) *2. This can directly
be written as 1000+5*2. In this case, we do not need to perform the additional arithmetic
operation i.e. subtraction.
(5-1) in the above computations is known as extra subtraction or offset value.
4.3.2 Two-Dimensional Array

4.3.2.1 Row Major Order Arrangement


Suppose we have a 2–D array A[L1:U1, L2:U2] given as below:

Row side indices are L1, L1+1, L1+2, …, U1–1, U1.


Column side indices are L2, L2+1, L2+2, …, U2–1, U2.
In memory it will look like 1-D array as it will be stored row-wise.

For simplicity, we will assume that the first index is 1 and each element requires 1 byte for
storage. The array becomes A[1:U1, 1:U2].

If the base address of array is α then,


Address of A[1,1] = α
Address of A[1,2] = α + 1
Address of A[1,3] = α + 2
Address of A[1,4] = α + 3

Address of A[1, U2] = α + (U2 – 1)
Address of A[2,1] = α + ( U2 – 1) + 1 (After storing all the elements of Row 1, first element of
row 2 will be stored in memory)
Address of A[2,1] = α + U2
Address of A[3,1] = α + U2 + U2 ( After storing all the elements of Row 2, first element of
row 3 will be stored in memory)
Address of A[3,1] = α + 2 U2

Address of A[i, 1] = α + (i – 1)*U2
Address of A[i,2] = α + (i – 1)*U2 +1
Address of A[i,3] = α + (i – 1)*U2 +2

Similarly, A[i, j] = α + (i – 1)*U2 + (j – 1)

Now, let us remove the assumption that every element takes 1 byte of storage with n bytes
for storage. So, the formula will change to
Address of A[i, j] = α +[(i – 1)*U2 + (j – 1)]*n

Now, remove the assumption that first index is 1 in row and column with L1 and L2,
respectively.
Replacing U2 as U2 – L2 +1 (length formula), i with i – L1 + 1 and j with j – L2 + 1

Address of A [i, j] = α + [(i – L1 + 1 – 1)*( U2 – L2 + 1) + (j – L2 + 1 – 1)] *n


Address of A [i, j] = α + [(i – L1)*( U2 – L2 + 1) + (j – L2)] *n

Address of A[i, j] = Base address + [(i – L1)*( U2 – L2 + 1) + (j – L2)] *n

Example: Suppose a 2D array A is declared as A[–2:2 , 2:6], words per cell = 4, base address
= 200. Consider Row major order arrangement.
a) Find out length of each dimension and the number of elements in array.
b) Find the location of A[1,2]
Solution:
Here Lower Bound of row(L1) = –2
Here Upper Bound of row(U1) = 2
Here Lower Bound of column(L2) = 2
Here Upper Bound of column(U2) = 6
n=4
a) Length of row = U1 – L1 + 1
= 2 – (–2) + 1 = 5
Length of column = U2 – L2 + 1
= 6 – 2 + 1 =5
No. of elements = 5*5 = 25
b) By formula:
A[i, j] = Base address + [(i – L1)*( U2 – L2 + 1) + (j – L2)] *n
A[1, 2]= 200 + [(1 – (–2) * (6 – 2 + 1) + (2 – 2)] * 4
= 200 + 15* 4
= 260

4.3.2.1 Column Major Order Arrangement


In this, we will discuss index–formula computation of 2–D array. We assume that the
elements are stored in Column–Major Order, which means the elements of the first column
are stored first, followed by the elements of 2nd column and so on. Suppose we have a 2–D
array A[L1:U1, L2:U2] given as below:

Row side indices are L1, L1+1, L1+2, …, U1–1, U1.


Column side indices are L2, L2+1, L2+2, …, U2–1, U2.
In memory it will look like 1-D array as it will be stored Column-wise.
For simplicity, we will assume that the first index is 1 and each element requires 1 byte for
storage. The Array becomes A[1:U1, 1:U2].
Another assumption: every element requiring 1 byte for storage. So that, address of first
element say:

If the base address of array is α then,


Address of A[1,1] = α
Address of A[2,1] = α + 1
Address of A[3,1] = α + 2
Address of A[4,1] = α + 3

Address of A[U1,1] = α + (U1 – 1)
Address of A[1,2] = α + ( U1 – 1) +1 (After storing all the elements of Column 1, first element
of Column 2 will be stored in memory)
Address of A[1,2] = α + U1
Address of A[1,3] = α + U1 + U1 ( After storing all the elements of Column 2, first element
of Column 3 will be stored in memory)
Address of A[1,3] = α + 2*U1

Address of A[1,j] = α + (j – 1)*U1
Address of A[2,j] = α + (j – 1)*U1 +1
Address of A[3,j] = α +(j – 1)*U1 +2

Similarly, A[i, j] = α +(j – 1)*U1 + (i – 1)

Now, let us remove the assumption that every element takes 1 byte of storage with n bytes
for storage. So, the formula will change to
Address of A[i, j] = α +[(j – 1)*U1 + (i – 1)]*n

Now, remove the assumption that first index is 1 in row and column with L1 and L2,
respectively.
Replacing U1 as U1 – L1 +1 (length formula), i with i – L1 + 1 and j with j – L2 + 1

Address of A [i, j] = α + [(j – L2 + 1 – 1)*( U1 – L1 + 1) + (i – L1 + 1 – 1)]*n


Address of A [i, j] = α + [(j – L2)*(U1 – L1 + 1) + (i – L1)] *n

Address of A[i, j] = Base address + [(j – L2)*( U1 – L1 + 1) + (i – L1)] *n

Example: Suppose a 2D array A is declared as A[–2:2, 2:6], words per cell = 4, base address =
1024. Consider Column Major order arrangement.
a) Find the length of each dimension and number of elements in array.
b) Find the location of A[2,5]
Solution:
Here Lower Bound of row(L1) = –2
Here Upper Bound of row(U1) = 2
Here Lower Bound of column(L2) = 2
Here Upper Bound of column(U2) = 6
n=4

a) Length of row = U1 – L1 + 1
= 2 – (–2) + 1 = 5
Length of column = U2 – L2 + 1
= 6 – 2 + 1 =5
No. of elements = 5*5 = 25
b) By formula:
Address of A[i, j] = Base address + [(j – L2)*( U1 – L1 + 1) + (i – L1)] *n
Address of A[2,5] = 1024 + [(5 – 2) * (2 – (–2) + 1) + (2 – (–2))] * 4
= 1024 + [15 + 4]*4
= 1024 + 76
= 1100

4.3.3 Three–Dimensional Array

4.3.3.1 Row Major Order Arrangement

Let us take a 3-dimensional Array in which the first dimension represents U1, Second
dimension U2 and third dimension U3. We can imagine this as a cuboid of size U1 x U2 x U3.
The 3-D Array can be represented as A[L1:U1, L2:U2, L3:U3]
L1, L2 and L3 are the lower bound of first, second and third dimension, respectively.

For simplicity we will assume that the first index is 1 and each element requires 1 byte for
storage. The Array becomes A[1:U1, 1:U2, 1:U3].
For making it even simpler, let us take different slices by cutting the cuboid horizontally across
the first dimension. The slices obtained are of size U2xU3. So there will be U1 such slices.

The above diagram can be viewed as U1 2-D arrays of size U2xU3.


If the base address of array is α then,
Address of A[1,1,1] = α
Address of A[2,1,1] = α + U2*U3 (There are U2xU3 elements in the first slice)
Address of A[3,1,1] = α + U2*U3 + U2*U3
= α + 2*U2*U3
Address of A[4,1,1] = α + 3*U2*U3

Address of A[i, 1, 1] = α + (i – 1)*U2*U3

Now let us expand the ith array. This will be a 2-D array of size U2xU3. The diagram given below
shows the storage pattern
Address of A[i,2,1] = α + (i – 1)*U2*U3 + U3 (There are U3 elements in the first row of this 2-D
array)
Address of A[i,3,1] = α + (i – 1)*U2*U3 + U3 + U3
Address of A[i,3,1] = α + (i – 1)*U2*U3 + 2*U3

Address of 1st element of jth row


Address of A[i,j,1] = α + (i – 1)*U2*U3 + (j – 1)*U3
Address of A[i,j,2]= α + (i – 1)*U2*U3 + (j – 1)*U3 +1
Address of A[i,j,3] = α + (i – 1)*U2*U3 + (j – 1)*U3 +2
Similarly, for kth element of jth row
Address of A[i, j, k] = α + (i – 1)*U2*U3 + (j – 1)*U3 + (k – 1)

Now, let us remove the assumption that every element takes 1 byte of storage with n bytes
for storage. So, the formula will change to
A[i, j, k] = α + [(i – 1)*U2*U3 + (j – 1)*U3 + (k – 1)]*n

Now, remove the assumption that first index is 1 in each dimension with L 1, L2 and L3
respectively.
i will be replaced by i–L1+1, j by j–L2+1 and k by k–L3+1
A[i, j, k] = α + [(i – L1)*(U2 – L2 + 1)*(U3 – L3 + 1) + (j – L2)*(U3 – L3 + 1) + (k – L3)]*n

A[i, j, k] = Base Address + [(i–L1)*(U2 –L2+1)*(U3–L3+1) + (j–L2)*(U3–L3+1) + (k–L3)]*n

4.3.3.2 Column Major Order Arrangement

Let us take a 3-dimensional Array in which the first dimension represents U1, Second
dimension U2 and third dimension U3. We can imagine this as a cuboid of size U1 x U2 x U3.
The 3-D Array can be represented as: A[L1:U1, L2:U2, L3:U3]
L1, L2 and L3 are the lower bound of first, second and third dimensions respectively.
For simplicity, we will assume that the first index is 1 and each element requires 1 byte for
storage. Thus, the Array becomes A[1:U1, 1:U2, 1:U3].
For making it even simpler, let us take different slices by cutting the cuboid horizontally across
the first dimension. The slices obtained are of size U1xU2. So there will be U3 such slices.

The above diagram can be viewed as U3 2-D arrays of size U1xU2.


If the base address of array is α then,
Address of A[1,1,1] = α
Address of A[1,1,2] = α + U1*U2 (There are U1xU2 elements in the first slice)
Address of A[1,1,3] = α + U1*U2 + U1*U2
= α + 2*U1*U2
Address of A[1,1,4] = α + 3*U1*U2

Address of A[1, 1, k]= α + (k – 1)*U1*U2
Address of A[1,2,k] = α + (k – 1)*U1*U2 + U1 (There are U1 elements in the first column of
this 2-D array)
Address of A[1,3,k] = α + (k – 1)*U1*U2 + U1 + U1
Address of A[1,3,k] = α + (k – 1)*U1*U2 + 2*U1
Address of 1st element of jth column
Address of A[1,j,k] = α + (k – 1)*U1*U2 + (j – 1)*U1

Address of A[2,j,k]= α + (k – 1)*U1*U2 + (j – 1)*U1 + 1


Address of A[3,j,k] = α + (k – 1)*U1*U2 + (j – 1)*U1 +2

Similarly, for kth element of jth column


Address of A[i,j,k] = α + (k – 1)*U1*U2 + (j – 1)*U1 + (i – 1)

Now, let us remove the assumption that every element takes 1 byte of storage with n bytes
for storage. So, the formula will change to
Address of A[i,j,k] = α + [(k – 1)*U1*U2 + (j – 1)*U1 + (i – 1)]*n

Now, remove the assumption that first index is 1 in each dimension with L1, L2 and L3
respectively.
i will be replaced by i–L1+1, j by j–L2+1 and k by k–L3+1

A[i, j, k] = α + [(k – L3)*(U1 – L1 + 1)*(U2 – L2 + 1) + (j – L2)*(U1 – L1 + 1) + (i – L1)]*n

A[i, j, k] = Base Address + [(k–L3)*(U1–L1+1)*(U2–L2+1) + (j–L2)*(U1–L1+1) + (i–L1)]*n

Example: Given a 3D array A[2:8, –4:1, 6:10] with Base(A)= 200. Number of words per cell =4.
Calculate address of A[5,–1,8] if elements are stored in
- Row major order fashion
- Column major order.

Solution:
Here Lower Bound of dimension 1(L1) = 2
Here Upper Bound of dimension 1 (U1) = 8
Here Lower Bound of dimension 2(L2) = -4
Here Upper Bound of dimension 2(U2) = 1
Here Lower Bound of dimension 3(L3) = 6
Here Upper Bound of dimension 3(U3) = 10
Base Address = 200
n=4
By formula (Row major order):
Address of A[i, j, k] = Base Address + [(i–L1)(U2 –L2+1)(U3–L3+1) + (j–L2)(U3–L3+1) + (k–L3)]*n
Address of A[5,-1,8] = 200 + [(5 – 2) * (1 – (-4) + 1)* (10 – 6+1) + (-1 –(-4)*(10-6 +1) + (8 -6) ] * 4
= 200 + [ 3 * 6* 5 + 3*5 + 2]*4
= 200 + 107*4 = 628

By formula (Column major order):


Address of A[i, j, k] = Base Address + [(k–L3)(U1–L1+1)(U2–L2+1) + (j–L2) (U1–L1+1) + (i–L1)]*n
Address of A[5,-1,8] = 200 + [(8 – 6) * (8 – 2 + 1)* (1 – (–4)+1) + (-1 –(-4)*(8 -2 +1) + (5 -2) ] * 4
= 200 + [ 2 * 7 *6 + 3*7 + 3]*4
= 200 + 432 = 632

4.3.4 N-Dimensional Array


An N–dimensional array is a fixed-size multidimensional container of items of the same type
and size. N–Dimensional array (A[L1:U1] [L2:U2] [L3:U3] … [LN:UN]) can be considered as the U1–
arrays of size U2 x U3 x…x UN .
Example: A 3-D array A[5][4][6] can be considered as the 5 two dimensional arrays of 4x6.
For writing the Index formula for a N-dimensional array, the observation of 2-D and 3-D array
derivations are used. Here it is assumed that an element requires B bytes for storage.

Row Major Order


A[k1, k2, …, kN] = Base address + [(k1–L1)(U2 –L2+1)(U3–L3+1)…(UN–LN+1) + (k2–L2) (U3–
L3+1)…(UN–LN+1) + … + (kN-1–LN-1) (UN–LN+1)+ (kN–LN)]*B

Column Major Order


A[k1, k2, …, kN] = Base address + [(kN–LN)(U1 –L1+1)(U2–L2+1)…(UN-1–LN-1+1) + (kN-1–LN-1)
(U1 –L1+1)(U2–L2+1)…(UN-2–LN-2+1)+ … + (k2–L2) (U1–L1+1)+ (k1–L1)]*B

The above can be used to write the index formula of array of any dimension.
Row Major
For N=1, i.e. 1-D array
Address of A[k1] = Base address + (k1 – L1)*B

For N=2, i.e. 2-D array


Address of A[k1,k2]=Base address + [(k1 – L1)*(U2 – L2 + 1) + (k2 – L2)]*B

For N=3, i.e. 3-D array


Address of A[k1,k2,k3]=Base address + [(k1 – L1)*(U2 – L2 + 1) (U3 – L3 + 1) + (k2 – L2) (U2 – L2 + 1)
+ (k3 – L3)]*B
Column Major
For N=1, i.e. 1-D array
Address of A[k1] = Base address + (K1 – L1)*B

For N=2, i.e. 2-D array


Address of A[k1,k2]= Base address + [(K2 – L2)*(U1 – L1 + 1) + (K1 – L1)]*B

For N=3, i.e. 3-D array


Address of A[k1,k2,k3]= Base address + [(K3 – L3)*(U1 – L1 + 1)(U2 – L2 + 1) + (K2 – L2) (U1 – L1 + 1)
+ (K1 – L1)]*B

4.4 Primitive operations on Array

In this section, we are going to explain various primitive operations on array. For writing the algorithm,
we are assuming that the lower bound of array is 1.

4.4.1 Traversal
This operation is used to explore the array elements one by one. This is also called the visiting
of an array.

In the given Algorithm, A[ ] is the array and N is the size of the array.

ALGORITHM Traverse (A[ ], N)


Input: Array A[ ] of size N
Output: Array elements in sequence
BEGIN:
FOR i = 1 TO N DO
WRITE(A[i]) Exploring the array elements from first index to last index.
END;

Time Complexity: ϴ(N)


The above algorithm requires execution of for loop N times. Hence, the number of statements
to be executed is N.
Space Complexity: ϴ(1)
The only extra variable taken here is i. Hence, the space complexity is constant.

4.4.2 Insertion
Insertion operation is performed to insert a data element in an array. A new element can be
added at the beginning, end, or at any given index based on the requirement.
In the given Algorithm, A[ ] is the original array where insertion is expected at ith index. The
item to be inserted is Key and N is the size of the array. The array size needs to be updated
upon the insertion. (It is assumed that array has sufficient space for insertion of new item)

ALGORITHM Insertion (A[ ], N, i, Key)


Input: Array A[ ] of size N, position of insertion i, data element for insertion Key
Output: Updated array after insertion
BEGIN:
FOR j = N TO i STEP–1 DO Shifting of elements from Nth index to ith index. An element
A[j+1] = A[j] is shifted at one higher index to the current index.
A[i] =Key Placing Key at ith index.

N = N+1 Incrementing the array size by 1.


END;

Example: Insert an element (Key=15) at specific index (i=5) in the given array of size 9.

Time Complexity:
When the element is to be inserted at the beginning, N number of shifting will be required
and two statements to assign the value and increase the value of N. Hence, N+2 statements
will be executed (Worst Case), O(N).
When the element is to be inserted at the end, no shifting is required. Therefore, only two
statements will be executed (Best Case), Ω(1).
Space Complexity:
The only extra variable taken here is j, hence the space complexity is ϴ(1).

4.4.3 Deletion
Deletion operation deletes an element from the given index in the array and re-organizes the
array elements with shifting.

ALGORITHM Deletion (A[ ], N, i)


Input: Array A[ ] of size N, position of deletion i
Output: Updated array after deletion

BEGIN:
x = A[i] Saving the element to be deleted

FOR j = i+1 TO N DO Shifting of elements from (i+1)th index to Nth index. An


A[j–1] =A[j] element is shifted at one lower index to the current index.

N = N–1 decrementing the array size by 1.

RETURN x Returning the deleted element


END; decrement the array size by 1.

Note: When we delete an element from any data structure, deleted element should be
returned to the calling function.

Example: Delete an element at index i=5 from the given array of size 10.
Time Complexity: In the above algorithm, there are 3 statements outside the loop that are
compulsory to be executed in any case. When the element is to be deleted from the
beginning, N-1 shifting will be required. Total statements for execution are N+2; hence the
complexity is O(N) in the worst case.
When the element is to be deleted from the end, no shifting is required. There will be 3
statements for execution in total, which is constant. This is the best case. Hence the Time
complexity in this case is Ω(1).

Space Complexity: ϴ(1)


The only variables taken here are x and j; hence the space complexity is constant, i.e. ϴ(1).

4.5 Application Problems Related to Array

4.5.1 Insertion in sorted 1-D array


In a sorted array, a search operation is required to be performed for the possible position
of insertion for the given element. Insertion of the element takes place as in section 4.4.2.

To insert an element “Key” in a sorted array (increasing order), the following steps need to
be performed:
1. A search operation for the appropriate position of insertion.
2. This position needs to be made vacant by shifting the elements to their right.
3. Insert the element at this position.

ALGORITHM InsertionSortedArray(A[ ], N, key)


Input: Array A[ ] of size N, data element for insertion Key
Output: Updated array after insertion
BEGIN:
i =1 Search operation to find the insertion location of the key to
WHILE A[i]<key DO be inserted. Here Key is compared with the elements present
i = i+1 in the sorted array and location is returned as index i

FOR j =N TO i STEP–1 DO Elements are shifting to make the location ‘i’


A[j+1] = A[j] vacant to insert the key
A[i] = key
Insertion of key at i location

N=N+1 Incrementing the array size by 1


END;

Example: Insert an element 15 (Key) in sorted array of size 9.


Time Complexity: ϴ(N)
If the desired place for the insertion is ‘I’ (found with the search) then ‘n–I’ shifting will be
required. Search operations require l statement executions and shifting requires n-l
statement executions. Apart from searching and shifting, three other statements will get
executed. Total statements execution is N+3 i.e. ϴ(N).
Space Complexity: ϴ (1)
The only variables taken here are i and j; hence the space complexity is constant, i.e. ϴ(1).

4.5.2 Finding the number which is not repeated in Array of integers


The method to find the number that is not repeated could be very simple if we use a Direct
Address Table (DAT)*. The method will initialize a DAT with all its elements as 0. The index of
this array refers to the element in the original array. This array would be used for finding the
frequency of the elements in the original array. In one traversal to original array, we will be
able to find the frequency of elements. In the second traversal to Direct address table we will
be able to find the elements with frequency equal to 1 (As elements with frequency 2 are
repeated in the original array). Frequency 0 means element is not present in the Array.
*Direct address table: This is an array where the index refers to the element in the original
array. Frequently used for problem-solving.
Here it is assumed that the range of the elements is 1 to k.

ALGORITHM: NonRepetitions(A[ ], N, k)
Input: Array A[ ] of size N, the largest element k
Output: The elements which are not repeated
BEGIN:
C[k] ={0} DAT of size k+1 with all elements initialized with 0
FOR i = 1 TO N DO
C[A[i]]=C[A[i]]+1 Frequency count of all elements in array

FOR i =1 TO k DO Finding the elements which have frequency 1 i.e.,


IF C[i]==1 THEN not repeated
WRITE(C[i])
END;

Time Complexity: ϴ(N+k)


If k represents the largest no of the array and N is the size of the original array, the first
traversal requires N statement execution and second requires k. Thus, time complexity will
be ϴ (N+k).
Space Complexity: ϴ (k)
The algorithm will require additional space for array of size k and a variable i. Hence the space
complexity is ϴ (k).

4.5.3 Merging of two sorted arrays


Given two sorted Arrays array1 and array2. The task is to combine these two sorted arrays to
form a single sorted array. The steps given below are used to perform the merging. It is
assumed that m represents the size of array1 and n represents the size of array2.

Step 1: Declare an output array of size m + n


Step 2: Simultaneously traverse array1 and array2. Pick smaller among the current elements
from array1 and array2, copy this smaller element to next position in output array. This step
is performed until there are elements in both arrays.
Step 3: If there are remaining elements in either array1 or array2, copy them into output
array one by one.

ALGORITHM: MergeArr(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Array after merging of elements in A[ ] and B[ ]
BEGIN:
C[m+n] Output array of size m+n
i=1, j=1, k=1
WHILE i<=m AND j<=n DO Comparison of current elements of both arrays.
IF A[i]<B[j] THEN Smaller element is stored in the output array.
C[k]=A[i]

i=i+1 Updating index of Array A


k=k+1 Updating index of output array C
ELSE
C[k]=B[j]
j=j+1 Updating index of Array B
k=k+1 Updating index of output array C
WHILE i<=m DO
C[k]=A[i]
Copy remaining elements of array
i=i+1 A one by one in output array C
k=k+1
WHILE j<=n DO
C[k]=B[j]
Copy remaining elements of array
J=j+1
B one by one in output array C
k=k+1
RETURN C Returning the output array
END;

Time Complexity: The process of merging requires the comparison of each element of array1
with that of array2. An element is added to the output array after the comparison. Since m+n
elements will be added in the output array, total m+n comparisons are required. Hence Time
Complexity is ϴ (m+n).

Space Complexity: An array of size m+n is required for storage of the output. Alongside, space
is required for variables i, j and k. So, the total space required is m+n+3 which can be
represented as ϴ (m+n).

Example: Merging of two given sorted Array1 and Array2.


4.5.4 Finding the elements of one set that does not belong to the other set
It is assumed here that the set elements are arranged in ascending sequence. The algorithm
traverses both the array simultaneously and finds the common elements. These elements are
not included in the output array. Rest of the elements from set A are added to the output
array. This is more like finding the set Difference of A from B.

Figure: Venn Diagram of A – B


ALGORITHM: A_AND_NOT_B(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Elements of Array A[ ] that does not belong to B[ ]
BEGIN:
C[m] Output array of size m
i=1, j=1, k=1
WHILE i<=m AND j<=n DO
Comparison of current elements of both arrays. If element
A[i]<B[j] THEN
in array A is smaller than array B, element from array A is
C[k]=A[i]
stored in the output array.
k=k+1
i=i+1
ELSE
IF A[i]==B[j] THEN If the current element of both the arrays are equal,
i=i+1 the elements are skipped.
j=j+1
ELSE
j=j+1
WHILE i<=m DO
Copy remaining elements of array A
C[k]=A[i]
one by one in output array C
i=i+1
k=k+1
RETURN C Returning the output array
END;

Time Complexity: This process requires comparison of each element of Array1 with that of
Array2. An element is added to the output array after the comparison. Total m+n
comparisons are required. Hence Time Complexity is ϴ(m+n).
Space Complexity: An array of size m is required for storage of the output. Alongside, space
is required for variables i, j and k. Therefore total space required is m+3 which can be
represented as ϴ(m).

4.5.5 Set Union operation


It is assumed here that the set elements are arranged in an array in ascending sequence. The
task is to combine these two sorted arrays to form a single sorted array (common elements
should be added only once in the output array). The steps given below are used to perform
the union operation. It is assumed that m represents the size of Set 1 (array1) and n, the size
of Set 2 (array2)

Step 1: Declare an output array of size m + n


Step 2: Simultaneously traverse array1 and array2. Pick smaller among the current elements
from array1 and array2, copy the smaller element to next position in the output array. For
common element, include it once in the final array and proceed to check the next elements
in the arrays. This step is performed until there are elements in both arrays.
Step 3: If there are remaining elements in array1 or array2, copy them into output array one
by one.

Figure: Venn Diagram of A U B

ALGORITHM: SetUnion(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Array after union of elements in A[ ] and B[ ]
BEGIN:
C[m+n] Output array of size m+n
i=1, j=1, k=1
WHILE i<=m AND j<=n DO
IF A[i]<B[j] THEN Comparison of current elements of both arrays. If
C[k]=A[i] element in array A is smaller than array B, element
i=i+1 from array A is stored in the output array.
k=k+1
ELSE
IF A[i]==B[j] THEN
If the current element of both the arrays are equal,
C[k]=B[j]
include it once in the output array.
i=i+1
j=j+1
k=k+1
ELSE
C[k]=B[j] If element in array B is smaller than array A, element
j=j+1 from array B is stored in the output array.
k=k+1
WHILE i<=m DO
C[k]=A[i] Copy remaining elements of array A
i=i+1 one by one in output array C
k=k+1
WHILE j<=n DO
C[k]=B[j] Copy remaining elements of array B
J=j+1 one by one in output array C
k=k+1
RETURN C Returning the output array
END;

Time Complexity: This process of merging requires comparison of each element of Array1
with that of Array2. An element is added to the output array after the comparison. Since
maximum m+n elements will be added in the output array, total m+n comparisons are
required. Hence Time Complexity is ϴ (m+n).
Space Complexity: An array of size m+n is required for storage of the output. Alongside, space
is required for variables i, j and k. Thus the total space required is m+n+3 which can be
represented as ϴ (m+n).

Example: Union of two given arrays.


4.5.6 Set Intersection Operation
It is assumed here that the set elements are arranged in an array in ascending sequence. The
task is to find the common elements and add them to the final array. The steps given below
are used to perform the intersection operation. It is assumed that m represents the size of
Set 1 (array1) and n, the size of Set 2 (array2)

Step1: Declare an output array of size Min(m,n)


Step 2: Simultaneously traverse array1 and array2. If current element in array1 is same as
that in array2, then copy the same element to the next position of the output array and
increment the pointers of both arrays. Otherwise, increment the pointer of the array whose
element is smaller.

Figure: Venn Diagram of A∩B

ALGORITHM: SetIntersection(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Array after intersection of elements in A[ ] and B[ ]
BEGIN:
IF m<n THEN
Min=m
ELSE
Min=n
C[Min] Output array of size Min(m,n)

i=1, j=1, k=1


WHILE i<=m AND j<=n DO
IF A[i]<B[j] THEN Comparison of current elements of both arrays.
i=i+1
ELSE
IF A[i]==B[j] THEN If the current element of both the arrays are equal,
C[k]=B[j] include it once in the output array.
i=i+1
j=j+1
k=k+1
ELSE
j=j+1
RETURN C Returning the output array
END;

Example: Intersection of two given Array1 and Array2

Time Complexity: The maximum effort required for finding the intersection elements is
O(m+n) as the elements can be added after the comparisons only. In the worst case the
comparison is required till the extreme ends of both the sets (arrays). In the best case last
element of one array will be smaller than first element of the second array. In such a case,
the effort required would be O(m) or O(n).
Space Complexity: ϴ(m) if m<n or ϴ(n) if n<m. Three extra variable amounts to constant
space.

4.5.7 Set Difference Operation


The difference (B–A) will output the elements from array B that are not in the array A. It is
assumed here that the set elements are arranged in ascending sequence. The algorithm
traverses both the array simultaneously and finds the common elements. These elements are
not included in the output array. The rest of the elements from set B are added in the output
array.

Step 1: Declare an output array of size n


Step 2: Simultaneously traverse array1 and array2. Compare the current elements from
array1 and array2. If the element of array2 is smaller, include it in the output array skip the
element otherwise (if element of array1 is smaller or elements are equal). This step is
performed until there are elements in both arrays.
Step 3: If there are remaining elements in array2, copy them into the output array one by
one.

Figure: Venn Diagram of B – A

ALGORITHM: SetDifference(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Array after set difference (B-A)
BEGIN:
C[n] Output array of size n
i=1, j=1, k=1
WHILE i<=m AND j<=n DO
IF A[i]<B[j] THEN Comparison of current elements of both arrays.
i=i+1
ELSE
IF A[i]==B[j] THEN If the current element of both arrays are equal, the
i=i+1 elements are skipped.
j=j+1
ELSE
C[k]=B[j] If element in array B is smaller than array A, element
j=j+1 from array B is stored in the output array.
k=k+1
WHILE j<=n DO
C[k]=B[j] Copy remaining elements of array B
J=j+1 one by one in output array C
k=k+1
RETURN C Returning the output array
END;

Example: Difference (B – A) in the given sorted array A and B.

Time Complexity: This process requires comparison of each element of Array A with that of
Array B. An element is added to the output array after the comparison. Total m+n
comparisons are required. Hence Time Complexity is ϴ(m+n).
Space Complexity: An array of size n is required for storage of the output. Alongside space is
required for variables i, j and k. Thus the total space required is m+3 which can be represented
as ϴ(n).

4.5.8 Symmetric Difference of two sets


Symmetric difference (AꚚB) of sets A and B contain the elements of Set A that do not belong
to Set B and elements Set B that do not belong to Set A., i.e. (AꚚB) = (A – B) U (B – A).
It is assumed here that the set elements are arranged in ascending sequence. The algorithm
traverses both the array simultaneously and finds the common elements. These elements are
not included in the output array. The rest of the elements from set A and B are added to the
output array.

Figure: Venn Diagram of AꚚB

Step 1: Declare an output array of size m+n


Step 2: Simultaneously traverse array1 and array2. Pick smaller among the current elements
from array1 and array2, copy the smaller element to next position in the output array. For
common element, skip it and proceed to check the next elements in the arrays. This step is
performed until there are elements in both arrays.
Step 3: If there are remaining elements in array1 or array2, copy them into the output array
one by one.

ALGORITHM: SymmetricDifference(A[ ], m, B[ ], n)
Input: Array A[ ] of size m, Array B[ ] of size n
Output: Array after set difference (AꚚB)
BEGIN:
C[m+n] Output array of size m+n
i=1, j=1, k=1
WHILE i<=m AND j<=n DO Comparison of current elements of both arrays. If
IF A[i]<B[j] THEN element in array A is smaller than array B, element
C[k]=A[i] from array A is stored in the output array.
i=i+1
k=k+1
ELSE
IF A[i]==B[j] THEN If the current element of both arrays are equal, the
i=i+1 elements are skipped.
j=j+1
ELSE
C[k]=B[j] If element in array B is smaller than array A, element
j=j+1 from array B is stored in the output array.
k=k+1
WHILE i<=m DO
C[k]=A[i] Copy remaining elements of array A
i=i+1 one by one in output array C
k=k+1
WHILE j<=n DO
C[k]=B[j] Copy remaining elements of array B
J=j+1 one by one in output array C
k=k+1

RETURN C Returning the output array.


END;

Example: Symmetric difference of two sorted given Array A and Array B


Time Complexity: This process requires comparison of each element of Array A with that of
Array B. An element is added to the output array after the comparison. Total m+n
comparisons are required. Hence Time Complexity is ϴ(m+n).
Space Complexity: An array of size m+n is required for storage of the output. Alongside, space
is required for variables i, j and k. Thus the total space required is m+n+3 which can be
represented as ϴ (m+n).

4.6 Applications of 2-D Arrays

4.6.1 Matrix Operations through Array


Matrices are used for performing a variety of tasks related to Computer Science, e.g.,
mathematical computations, plotting various kinds of graphs using software, representation
of population information etc., various other applications of matrices are listed as under:
a) Graph: Representation of Graph data structure using adjacency matrix.
b) Computer Graphics: Representation of pixel information. Various operations like
translation, rotation, scaling etc. can be performed with direct computations on pixel
matrix.
c) Geology: Matrices are used for the representation of dynamics of Earth e.g., seismic
surveys. Matrices can also be used to draw graphs, statistics, perform scientific
calculations.
d) Economics: Use of Decision matrix can help to select the best course plan for business
processes. Decision matrix provides a way to compare different solutions to a given
problem and select the best one.
e) In Auto CAD Civil Construction: here structure of buildings can be represented as
matrices by storing their coordinates and angles.
f) Manage Databases: Managing Tables
g) Robotics and Automation: Here, matrices are used to store the direction coordinates
and angles related to the robot’s movement.
h) Data Security by providing encryption and Decryption: In cryptography, encryption
and decryption is done by performing the basic matrix operations like matrix
multiplication, transpose etc.

Here we will discuss the following operations which can be performed on the matrix:
1) Matrix Addition
2) Matrix Subtraction
3) Matrix Multiplication
4) Transpose
5) Determinant
It is assumed that the students have already studied the matrix operations in the earlier
classes.
For performing the above operation, matrices are required to be represented using 2-D
arrays. Before going through any matrix operation, let us first see how matrices are
traversed.

4.6.1.1 Matrix Traversal


This operation is used to explore the matrix (2-D array) elements one by one. We are
considering the row-major order arrangement here.

In the given Algorithm, P[ ][ ] is the array and M x N is the size of the array.

ALGORITHM Traverse (A[ ], M, N)


Input: Array P[ ][ ] of size M x N
Output: Array elements in sequence
BEGIN:
FOR i = 1 TO M DO Exploring the array elements in row-major order. For this, first
FOR j = 1 TO N fix the row number i.e. i and traverse through all the columns.
WRITE(P[i][j]) Then, repeat this for the next value of i until all rows are
covered.
END;

Time Complexity: ϴ(N)


The above algorithm requires execution of loop M x N times. Hence, the number of
statements to be executed are ϴ(Mx N).
Space Complexity: ϴ(1)
The only extra variables taken here is I and j. Hence, the space complexity is constant.
4.6.1.2 Matrix Addition
Let P and Q are the two matrices of the same order (same number of rows and columns).
Their addition (P+Q) can be performed by adding the same row and same column elements
from P and Q.

ALGORITHM: MatrixAddition(P[ ][ ], Q[ ] [ ], R1, C1, R2, C2)


Input: Array P[ ][ ] of size R1 x C1 and Array Q[ ][ ] of size R2 x C2
Output: Array of size R1 x C1 or R2 x C2
BEGIN: Checking the order(same number of rows
S[R1] [C1] and columns). If the order is the same
IF R1 = = R2 AND C1 == C2 THEN addition can be performed.
FOR i = 1 TO R1 DO
FOR j = 1 TO C1 Performing the addition and saving
S[i][j] = P[i][j] + Q[i][j] the result in output matrix S.

RETURN S Returning the output array


ELSE
WRITE(“ADDITION is not possible”) If the order is not same.

END;

Time Complexity: In matrix addition, corresponding elements of both the matrix are added.
Since addition is performed element by element and there are R1xC1 elements, the time
complexity will be ϴ(R1*C1), where R1 is the number of rows and C1 is the number of columns.
Space complexity: An additional matrix of size R1xC1 is used and two variables i and j. Hence,
the space complexity is ϴ(R1*C1).

Figure: Explaining the addition operation on two 3x3 Matrices


4.6.1.3 Matrix Subtraction
Let P and Q are the two matrices of the same order (same number of rows and columns).
Then, their subtraction (P-Q) can be performed by subtracting the same row and same column
elements from P and Q.

ALGORITHM: MatrixSubtraction(P[ ][ ], Q[ ] [ ], R1, C1, R2, C2)


Input: Array P[ ][ ] of size R1 x C1 and Array Q[ ][ ] of size R2 x C2
Output: Array of size R1 x C1
BEGIN:
Checking the order(same number of rows
S[R1] [C1] and columns). If the order is the same
IF R1 == R2 AND C1 == C2 THEN subtraction can be performed.
FOR i = 1 TO R1 DO
FOR j = 1 TO C1 Performing the subtraction and
S[i][j] = P[i][j] – Q[i][j] saving the result in output matrix S.
RETURN S Returning the output array
ELSE
WRITE(“SUBTRACTION is not possible”) If the order not same.

END;

Time Complexity: In matrix subtraction, corresponding elements of both the matrix are
subtracted. Since subtraction is performed element by element and there are R1xC1 elements,
the time complexity will be ϴ(R1*C1), where R1 is the number of rows and C1 is the number
of columns.
Space complexity: An additional matrix of size R1xC1 is used and two variables i and j. Hence,
the space complexity is ϴ(R1*C1).

Figure: Explaining the subtraction operation on two 3x3 Matrices


4.6.1.4 Matrix Multiplication
Let P and Q are the two matrices to be multiplied(P.Q), number of columns in P must be equal
to the number of rows in Q. Let P be a R1xC1 matrix and Q be a R2xC2 matrix. Then the product
of the matrices P and Q will be of the order of mxp.

ALGORITHM: MatrixMultiply(P[ ][ ], Q[ ] [ ], R1, C1, R2, C2)


BEGIN:
Checking the order whether multiplication
M[R1] [C2]
can be performed.
IF C1 == R2 THEN
FOR i = 1 to R1 DO
FOR j = 1 to C2 DO Performing the multiplication and
M[i][j] = 0 saving the result in output matrix M.
FOR k = 1 to C1 DO
M[i][j] = M[i][j]+ P[i][k] + Q[k][j]
RETURN M Returning the output array
ELSE
If C1 is not equal to R2, matrices
WRITE(“Matrix multiplication is not possible”) are not multipliable.
END;

Time Complexity: Matrix Multiplication is performed by multiplying corresponding row


elements of the first matrix with corresponding column elements of the second matrix. The
order of the first matrix is R1xC1, the order of the second matrix is R2xC2. Total multiplications
performed to obtain the output matrix will be of the order of R1xC2 will be R1.C1.C2. Hence,
the time complexity is ϴ(R1.C1.C2).
Space complexity: An additional matrix of size R1xC2 is used and three variables i, j and k.
Hence, the space complexity is ϴ(R1C2).

Figure: Explaining the Multiplication operation


4.6.1.5 Transpose of a matrix
Let P be a matrix whose transpose has to be found. This can be done by interchanging the
rows elements with the corresponding columns elements. If a matrix P is of order rxc then
transposed matrix will be of order cxr.

ALGORITHM: MatrixTranspose(P[ ][ ], R, C)
BEGIN:
T[C][R]
FOR i = 1 to R DO
FOR j = 1 to C DO
Performing the transpose and saving
T[i][j] = P[j][i]
the result in output matrix P.
RETURN T
Returning the output array
END;

Figure: Explaining the Transpose operation on a 3x3 Matrix

Complexity of operation:
Let P be an RxC matrix. Transpose will require RxC times placement of data from original
matrix to transposed matrix. Thus, complexity of transpose operation will be ϴ(C.R).
Space complexity: An additional matrix of size CxR is used and two variables i, j. Hence, the
space complexity is ϴ(C.R).

4.6.1.6 Determinant of a Matrix


Determinant of a matrix is calculated by the element of a square matrix. The determinant of
a matrix is denoted by the |A|, det(A), det[A].
a b
c d
Determinant of a 2X2 matrix is |A| =a*d – b*c

a b c
d e f
g h i
Determinant of a 3x3 matrix is |A| = a(e*i – f*h) – b(d*i – f*g) + c(d*h – e*g)

ALGORITHM: MatrixDeterminant(P[ ][ ], R1, C1)


BEGIN:
Det = Det+ P[1,1]*(P[2,2]*P[3,3] – P[2,3]*P[3,2]) – P[1,2]*(P[2,1]*P[3,3] –
P[3,1] * P[2,3]) + P[1,3]*(P[2,1]*P[3,2] – P[2,2]*P[3,1])
END;

Figure: Explaining the Determinant operation on a 3x3 Matrix

Time Complexity: As N2 multiplications are required for finding determinants, Time


complexity will be ϴ (N2).
Space Complexity: There are no additional space required; hence the space complexity will
be ϴ(1)
4.7 Types of Problem in Array

4.7.1 Type 1: Rotation Type Problem


Problem1– Given an Array and a number d, how will you rotate an Array by d positions.
e.g. Arr[ ]={1,2,3,4,5,6,7,8} , d=2
Output = {3,4,5,6,7,8,1,2}

Method1:
In the Algorithm given below, the Arr[ ] is the input Array
ALGORITHM Rotate(Arr[ ], d, n)
BEGIN:
FOR i=1 TO d DO
Temp=Arr[0]
FOR j=1 TO n–1 DO
Arr[j–1]=Arr[j]
Arr[n–1] = Temp
END;

Explanation and Complexity: In this method, outer loop executes d+1 times i.e., number of
elements rotated and the inner loop executes n times and shifts elements one position left
every time. Hence Time complexity of this process will be O(n*d).

Method2:
ALGORITHM Rotate(Arr[ ], d, n)
BEGIN:
FOR i=0 TO d–1 DO
Temp[i]=Arr[i]
FOR i=0 TO n–d–1 DO
Arr[i]=Arr[i+d]
FOR i=n–d TO n–1 DO
Arr[i]=temp[i–n+d]
END;

Explanation and Complexity: In this method, first take a Temporary Array of size d and copy
first d elements from the original Array to temporary Array (loop execution d+1 times). In the
second loop, shift elements by d position into the left (loop execution n–d+1 times). Finally,
in the last loop, copy the elements from temporary Array to original Array in last d positions
(loop execution time d+1 times).
Total time =d+1+n–d+1+d+1 =n+d+2= O(n+d). Time complexity O(n+d).

Method3–Reversal Algorithm
To perform the rotation, the process can be broken in three parts.
1. Reverse the first d elements
2. Reverse the last n–d elements
3. Reverse the entire Array
The resulting Array would be rotated by d positions.

Function calls
Reverse (Arr, 0, d–1)
Reverse (Arr, d, n–1)
Reverse (Arr, 0, n–1)
Problem 2:
Write an algorithm to rotate an array of n elements by d positions that rotate Arr[ ] of size
n by d elements using block swap algorithm.
Hint: Block swap means swapping the Array elements by making a group of elements (Block).

Problem 3:
Write an algorithm to search an element into sorted and rotated array.

4.7.2 Type 2: Arrangement and de–arrangement problem

Reversal of an Array.

Method1:
In this method, we simply take two variables Low and High and set Low at the smallest index
and High at the largest index (Low=0, High=n–1). Performing the pairwise swap of High and
Low Array elements and then incrementing Low and decrementing High until High and Low
meets each other or cross will rotate the Array.

ALGORITHM Reverse(Arr[ ], n)
BEGIN:
Low=0
High=n–1
WHILE Low < High DO
Swap(Arr[Low], Arr[High])
Low++
High––
END;

ALGORITHM Swap(a, b)
BEGIN:
temp=a
a=b
b=temp
END;

Time complexity: The Algorithm performs swaps n/2 times. The loop executes for n/2 times
and a total of 5 statements run in each loop execution. Total statement execution required
for the operation is 5*n/2 + 2 i.e. O(n).

Method 2:
The same operation of pair wise swap can be performed by making use of 1 variable instead
of 2.
ALGORITHM reverse(Arr[ ], n)
BEGIN:
FOR i=0 TO n/2 – 1 DO
swap(Arr[i], Arr[n–i–1])
END;

Time complexity: The Algorithm performs swaps n/2 times. The loop executes for n/2 times
and a total of 5 statements run in each loop execution. Total statement execution required
for the operation is 5*n/2 + 2 i.e. O(n).

Method 3:
Using recursion. The algorithm written using recursion takes more memory than iterative one
but recursion is a powerful problem–solving tool that reduces effort of writing the Algorithm.
In the Algorithm given below, the Low and High represents smallest and largest Array index
respectively.

ALGORITHM Reverse(Arr[ ], Low, High)


BEGIN:
IF Low>=High THEN
RETURN
Swap(Arr[Low], Arr[High]);
Reverse(Arr, Low+1, High–1);
END;

Time complexity: The Algorithm performs swaps n/2 times conditionally. Hence the Time
complexity of the operations would be O(n).

Problem 1:
Write an algorithm to ReArrange positive and negative numbers in O(n) time and O(1) extra
space.

Problem 2:
Write an algorithm to Shuffle a given Array using Fisher-Yates shuffle Algorithm.

4.7.3 Type 3: Order Statistics Problem


Given an array and a number k where k is smaller than the size of the Array, we need to find
the kth smallest element in the given Array. Therefore, it is given that all Array elements are
distinct.

Examples
Input: Arr[ ] = {7, 10, 4, 3, 20, 15}
k=3
Output: 7

Input: Arr[ ] = {7, 10, 4, 3, 20, 15}


k=4
Output: 10

Method (Brute Force)


• Step 1: Sort the given Array by using any sorting algorithm. It is suggested to use the
sorting algorithms that take minimum time. We can either pick the Quick sort, Heap
sort or Merge sort that takes O(nlogn) time.
• Step 2: Return the element at (k–1)st index.

ALGORITHM kthSmallest(Arr[ ], n, k)
BEGIN:
Sort(Arr, n)
RETURN Arr[k–1]
END;

Time Complexity: Since sorting takes O(nlogn) time and 1 return statement is used in the
given algorithm, total time can be represented as O(nlogn)

Problem 1:
Write an algorithm for finding Mean and Median of an unsorted Array.

Mean of an Array = (sum of all elements) / (number of elements)


Median of a sorted Array of size n is defined as the middle element when n is odd and the
average of Middle two elements when n is even.

Since the Array is not sorted here, we sort the Array first, then apply the above formula.

Examples:
Input : A[ ] = {1, 3, 4, 2, 6, 5, 8, 7}
Output: Mean = 4.5
Median = 4.5
Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36
Mean = 36/8 = 4.5
Since number of elements is even, Median is average of 4th and 5th largest
elements, which means (4 + 5)/2 = 4.5

Input : a[ ] = {4, 4, 4, 4, 4}
Output: Mean = 4
Median = 4

4.7.4 Type 4: Range query problem

To find the GCDs of Array elements in the given index range. Given an Array A[ ] of size n.
We should be able to efficiently find the GCD from index qstart (query start) to qend (query
end) where 0 <= qstart <= qend <= n–1.

Example :
Input : a[ ] = {2, 3, 60, 90, 50}
Index Ranges : {1, 3}
Output: GCD of given range is 3

Input : a[ ] = {2, 3, 60, 90, 50}


Index Ranges : {2, 4}
Output: GCD of given range is 10

Input : a[ ] = {2, 3, 60, 90, 50}


Index Ranges : {0, 2}
Output: GCD of given range is 1

ALGORITHM RangeGcd(qstart, qend)


BEGIN:
FOR i = qstart TO qend DO
x=GCD(A[qstart], A[qend])
RETURN x
END;

ALGORITHM GCD(a, b)
BEGIN:
IF a<b THEN
Swap(a,b)
IF b==0 THEN
RETURN a
RETURN GCD(b, a%b)
END;

4.7.5 Type 5: Optimization problem

Subset sum Problem


Given a set of non–negative integers and a value sum, determine if a subset of the given set
with Total equals the given sum.
Example:
Input: set[ ] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True
There is a subset (4, 5) with sum 9.

Input: set[ ] = {3, 34, 4, 12, 5, 2}, sum = 30


Output: False
There is no subset that add up to 30.
Recursive Solution

ALGORITHM IsSubset(Arr[ ], n, x)
BEGIN:
IF x==0 THEN
RETURN TRUE

IF n==0THEN
RETURN FALSE

IF Arr[0]>x THEN
RETURN IsSubset(Arr+1, n–1, x)
ELSE
RETURN IsSubset(Arr+1, n–1, x) || IsSubset(Arr+1, n–1, x–Arr[0])
END;

Explanation–
let us suppose that Arr[4]={3,2,7,1},x=6,n=4 x is sum and n is number of elements.

In recursive calls, if the current item is greater than the sum, then simply ignore that item.
If the current item is not greater than the sum, either include the item or exclude that item.
If the item is included, then sum = sum –item; otherwise, there will be no change in the
sum.

Permutation Problem
Write an algorithm to find the permutation of given Array elements.

Explanation–
Let us suppose we have an Array a[3]={1,2,3}
ALGORITHM ArrayPermutation(A[ ], Beg, End)
BEGIN:
IF Beg==End THEN
WRITE(A[Beg])
ELSE
FOR i=Beg TO End DO
Swap((A[Beg], A[i]))
ArrayPermutation(A, Beg+1, End)
swap((A[Beg], A[i]))
END;

4.7.6 Type 6: Sorting problem

Alternative Sorting
Given an Array of integers, print the Array in such a way that the first element is first
maximum and second element is first minimum, third element is second maximum and
fourth element is second minimum and so on so forth.

Examples:
Input : Arr[ ] = {7, 1, 2, 3, 4, 5, 6}
Output: 7 1 6 2 5 3 4

Input : Arr[ ] = {1, 6, 9, 4, 3, 7, 8, 2}


Output: 9 1 8 2 7 3 6 4

Method
• Step 1: First, sort the Array by using any sorting algorithms which take a minimum
of O(nlogn) time.
• Step 2: Set Beg=0 and End=n–1. Print elements alternatively A[Beg] followed by
A[End]. Increase Beg by 1 and decrease End by 1. Again, print A[Beg] and A[End].
The process repeats until Beg and End meet each other or cross.

ALGORITHM AlternateSort(Arr[ ], n)
BEGIN:
WHILE Beg < End DO
WRITE(Arr[Beg])
WRITE(Arr[End])
Beg=Beg+1
End=End–1
IF n%2 !=0 THEN
WRITE(Arr[Beg])
END;

Problem 1:
Sort an Array in wave form.
Given an unsorted Array of integers, sort the Array into a wave like Array. An Array ‘Arr[n]’
is sorted in wave form if Arr[0] >= Arr[1] <= Arr[2] >= Arr[3] <= Arr[4] >= …

Examples:
Input : Arr[ ] = {10, 5, 6, 3, 2, 20, 100, 80}
Output: Arr[ ] = {10, 5, 6, 2, 20, 3, 100, 80} OR {20, 5, 10, 2, 80, 6, 100, 3} OR any other
Array that is in wave form

Input : Arr[ ] = {20, 10, 8, 6, 4, 2}


Output: Arr[ ] = {20, 8, 10, 4, 6, 2} OR {10, 8, 20, 2, 6, 4} OR any other Array that is in wave
form

Input : Arr[ ] = {2, 4, 6, 8, 10, 20}


Output: Arr[ ] = {4, 2, 8, 6, 20, 10} OR any other Array that is in wave form
Input : Arr[ ] = {3, 6, 5, 10, 7, 20}
Output: Arr[ ] = {6, 3, 10, 5, 20, 7} OR any other Array that is in wave form

Problem 2:
Merge two sorted Arrays with O(1) extra space
We are given two sorted Arrays. We need to merge these two Arrays such that the initial
numbers (after complete sorting) are in the first Array and the remaining numbers are in
the second Array. Extra space allowed in O(1).

Example:
Input : ar1[ ] = {10}
ar2[ ] = {2, 3}
Output: ar1[ ] = {2}
ar2[ ] = {3, 10}

Input : ar1[ ] = {1, 5, 9, 10, 15, 20}


ar2[ ] = {2, 3, 8, 13}
Output: ar1[ ] = {1, 2, 3, 5, 8, 9}
ar2[ ] = {10, 13, 15, 20}

4.7.7 Type 7: Searching Problem


Leaders in an Array
Write an Algorithm to print all the LEADERS in the Array. An element is a leader if it is
greater than all the elements to its right side and the rightmost element is always a leader.
For example, int the Array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.

ALGORITHM Leader(Arr[ ], n)
BEGIN:
FOR i=0 TO n–1 DO
FOR j=i+1 TO n–1 DO
IF Arr[i]<=Arr[j] THEN
BREAK
IF j==n THEN
WRITE(Arr[i])
END;

Method
• Step 1: Outer loop runs from 0 to n – 1 and one by one select all elements from left
to right.
• Step 2: The inner loop compares the selected element to all the elements to its
right side.
• Step 3: If the selected element is greater than all the elements to its right side,
then the selected element is the leader.

Problem 1: Majority Element


Write a function that takes an Array and prints the majority element (if it exists); otherwise,
print "No Majority Element." A majority element in an Array A[ ] of size n is an element that
appears more than n/2 times (and hence there is at most one such element).

Examples :
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output: 4
Explanation: The frequency of 4 is 5, which is greater
then the half of the size of the Array size.

Input : {3, 3, 4, 2, 4, 4, 2, 4}
Output : No Majority Element
Explanation: There is no element whose frequency is
greater than half of the size of the Array size.

Problem 2: Peak Element


Given an Array of integers. Find a peak element in it. An Array element is a peak if it is not
smaller than its neighbors. For corner elements, we need to consider only one neighbor.

Example:
Input: Array[ ]= {5, 10, 20, 15}
Output: 20
The element 20 has neighbours 10 and 15,
both of them are less than 20.

Input: Array[ ] = {10, 20, 15, 2, 23, 90, 67}


Output: 20 or 90
The element 20 has neighbors 10 and 15,
both of them are less than 20, similarly 90 has neighbors 23 and 67.

4.8 Generic Array

In C language Array can be declared as–


int a[10];
From the above declaration, we can calculate how much memory is allocated to an Array.
However, if we declare an Array of void type, it is impossible to calculate how much memory
will be allocated to an Array.
void a[10]; This is an invalid declaration

Array of void pointers used as generic Array


void*a[4] //valid declaration
Now let us convert the Array elements in such a way that each element of an Array points to
different types of memory
a[0] = malloc(sizeof(bool));
a[1] = malloc(sizeof(int));
a[2] = malloc(sizeof(float));
a[3] = malloc(sizeof(char));
Now let us store different data type values into this Array
*((bool*)&(a[0]))=1
*((int*)&(a[1]))=3
*((float*)&(a[2]))=3.666666
*((char*)&(a[0]))=’s’
In the generic Array, it is very important to know which type of data element Array element
points to.
In C language, there is no generic programming framework like templates in C++. In C
programming language, Macros trying to provide generic programming in the true sense but
macros have their limitations.
In Java Array of object data type is generic because the object is parent class of all.

4.9 Competitive Coding Questions

Problem 1: Given an array, Arr of length N. Determine if there exists an element in the array
such that the sum of the elements on its left is equal to the sum of the elements on its right.
If there are no elements to the left/right, then the sum is considered to be zero.
Formally, find an i, such that, Arr1 + Arr2 ... Arri–1 = Arri+1 + Arri+2 ... ArrN

Input:
N=4
Arr[ ] = {1, 2, 3, 3}
Output: YES
Explanation: Consider i = 3, for [1, 2]
sum is 3 and for [3] sum is also 3.

Expected Time Complexity: O(N)


Expected Auxiliary Space: O(1)

Solution:
The solution to this problem may be by iterative increasing one half's size simultaneously
decreasing the size of the other part. The solution given below takes right and left sum. Entire
array is summed then one element at a time is taken in left part (from right part) increasing
the size of left part by 1 element in each iteration. Wherever the equilibrium is found, the
algorithm prints Yes and terminates. In case no such equilibrium is found, the Algorithm prints
No. Since this Algorithm traverses the Array twice, the complexity of the Algorithm would be
O(N).

ALGORITHM Equilibrium(Arr[ ], n)
BEGIN:
right_sum = 0
FOR i= 0 TO N–1 DO
right_sum = right_sum + Arr[i]
left_sum = 0
FOR i= 0 TO N–1 DO
right_sum = right_sum – Arr[i]
IF left_sum == right_sum THEN
WRITE ("YES")
RETURN
left_sum = left_sum + Arr[i];

WRITE( "NO")
RETURN

Problem 2: Given an array, you have to find the max sum of i*A[i] where A[i] is the element
at index i in the array. The only operation allowed is to rotate (clockwise or counter clockwise)
the array any number of times.

Input:
N=4
A[ ] = {8,3,1,2}
Output: 29
Explanation: Above the configuration
possible by rotating elements are

3 1 2 8 here sum is 3*0+1*1+2*2+8*3 = 29


1 2 8 3 here sum is 1*0+2*1+8*2+3*3 = 27
2 8 3 1 here sum is 2*0+8*1+3*2+1*3 = 17
8 3 1 2 here sum is 8*0+3*1+1*2+2*3 = 11

Here the max sum is 29

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).
Solution:– The possible solution to this problem could be finding the Sum of all the elements
and Sum of i*A[i] as MaxSum initially. Then with the rotation, update this value. Comparison
of previous max sum is done with the new sum found. Return the Answer with the maximum
sum. Since this solution will traverse the Array twice, and rotation requires is performed only
virtually with O(1) time, The total time complexity remains as O(N). Since No auxiliary array is
taken in the solution, the Algorithm will take O(1) space.

ALGORITHM MaximumSum(A[ ], n)
BEGIN:
Sum = 0
MaxSum = 0
FOR i = 0 TO N – 1 DO
Sum =Sum + A[i];
MaxSum = MaxSum + i*A[i];

Ans = MaxSum;
FOR i = N–2 TO 0 STEP – 1
MaxSum = MaxSum + Sum – N*A[i+1]
Ans = Max(Ans, MaxSum)
RETURN Ans
END;

Problem 3: An array contains both positive and negative numbers in random order. Rearrange
the array elements so that all negative numbers appear before all positive numbers in
constant space. Order of Element does not matter here.

Input: –12, 11, –13, –5, 6, –7, 5, –3, –6


Output: –12 –13 –5 –7 –3 –6 11 6 5

Expected Time Complexity: O(n)


Expected Space Complexity: O(1)

Solution: The solution takes advantage of moving two pointers, one from front of the array
(i) and other one from back of the array (j). The two pointers move in opposite directions
(When the two meet or cross each other, the Algorithm will terminate. Before their
movements, the array elements are compared. Depending on the requirement they are
swapped.

ALGORITHM NegativePositive(A[ ], N)
BEGIN:
i=0
j=N–1
WHILE i < j DO
WHILE i<j && A[i] < 0 DO
i++
WHILE j > i && A[j] >= 0 DO
j––
IF i < j THEN
Swap(A[i], A[j])
END;

Problem 4: Three–way partitioning of array around a given value


Given an array of size n and a range [a, b]. The task is to partition the array around the range
such that the array is divided into three parts.
1) All elements smaller than a come first.
2) All elements in range a to b come next.
3) All elements greater than b appear in the end.
The individual elements of three sets can appear in any order. You are required to return the
modified array.

Example 1:
Input:
n=5
A[ ] = {1, 2, 3, 3, 4}
[a, b] = [1, 2]
Output: 1
Explanation: One possible arrangement is:
{1, 2, 3, 3, 4}. If you return a valid
arrangement, output will be 1.

Example 2:
Input:
n=3
A[ ] = {1, 2, 3}
[a, b] = [1, 3]
Output: 1
Explanation: One possible arrangement
is: {1, 2, 3}. If you return a valid
arrangement, output will be 1.

Expected Time Complexity: O(n)


Expected Space Complexity: O(1)
Multiple Choice Questions
1. Let G be a graph with n vertices and m edges. What is the tightest upper bound on
the running time of Depth First Search on G, when G is represented as an adjacency
matrix? GAYE CS 2014
A O(n)
B O(m+n)
C O(n2)
D O(mn)
AN C

2. Let G be a simple undirected graph. Let TD be a depth-first search tree of G. Let TB be


a breadth-first search tree of G. Consider the following statements.
(I) No edge of G is a cross edge with respect to TD. (A cross edge in G is between two
nodes, neither of which is an ancestor of the other in TD).
(II) For every edge (u, v) of G, if u is at depth i and v is at depth j in TB, then ∣i − j∣ = 1.
Which of the statements above must necessarily be true?
A I only
B II only
C Both I and II
D Neither I nor II
AN C

3. Let A[1...n] be an array of n distinct numbers. If i< j and A[i] > A[j], then the pair (i, j) is
called an inversion of A. What is the expected number of inversions in any
permutation on n elements? UGC NET CS 2016 July – III
A n(n–1)/2
B n(n–1)/4
C n(n+1)/4
D 2n[logn]
AN B

4. Which of the following correctly declares an array? ISRO CS 2008


A int geeks[20];
B int geeks
C geeks{20}
D array geeks[20]
AN A

5. Which of the following is true about arrays in C.


A For every type T, there can be an array of T
B For every type T except void and function type, there can be an array of T.
C For every type T except void and function type, there can be an array of T.
D 2D arrays are stored in column-major form
AN B

1 Consider the following declaration of a ‘two–dimensional array in C:


char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored
starting from memory address 0, the address of a[30][50] is:
A 2950
B 3049
C 3050
D 2949
AN C
DL E

2 Consider the following declaration of a ‘two–dimensional array in C:


char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored
starting from memory address 0, how many elements will be before the element
present at a[20][10] is:
A 1909
B 1910
C 2010
D 2009
AN D
DL M

3 A program P reads in 300 integers in the range [0…100], representing the scores of
300 students. It then prints the frequency of each score above 55. What would be
the best way for P to store the frequencies? :
A An array of 100 integers
B An array of 300 integers
C An array of 45 integers
D An array of 345 integers
AN C
DL M
Scenario A program X reads the marks of 120 students in the range [ 0…100]. It then
prints the frequency of each score above 65. Based upon this answer following
questions

4 What would be the most appropriate data type to store Marks?


A integer
B char
C double
D float
AN A
DL E

5 What would be the size of the array used?


A 65
B 100
C 165
D 35
AN D
DL M

6 What would be the address of the 10th element assuming the base address to be –
100?
A –136
B –60
C 140
D 36
AN B
DL M

7 What would be the address of the 20th element assuming the base address to be 0?
A 20
B 76
C 80
D 19
AN B
DL M

8 The memory address of the fifth element of an array can be calculated by the
formula?
A None of these
B LOC( Array[5] ) = Base( Array[4] ) + (5 – Upper bound)
C LOC( Array[5] ) = Base( Array[5] ) + (5–lower bound)
D LOC(Array[5] = Base(Array ) + (5–lower bound)
AN A
DL M

Scenario Suppose we are developing a program to multiply two matrices M1 of order 3


X 5 and matrix M2 of order 5 X 4. Answer the following questions based upon
this?

9 What would be the best-suited data structure in this case?


A Array 1D
B Array 2D
C Array 3D
D Array 4D
AN B
DL E

10 How many rows will be in each matrix M1 and M2?


A 3,5
B 3,4
C 3,3
D None of these
AN C
DL M

11 How many rows will be there in the resultant Matrix?


A 3
B 4
C 5
D 6
AN A
DL M

1. Perform the following operations on the matrix. GATE CSE 2015


⎡3 4 45⎤
⎢7 8 105⎥
⎣13 2 195⎦
Add the third row to the second row.
Subtract the third column from the first column
The determinant of the resultant matrix is _____________.
A 0
B 1
C 50
D 100
AN A

2. An n*n array V is defined as follows


V[i,j]=i–j for all i,j, 1<=i<=n;1<=j<=n;
The sum of the elements of the array V is GATE 2000
A 0
B n–1
C n2–3n+1
D n2(n+1)/2
AN A

3. Let A be a two–dimensional array declared as follows: A: array [1 … 10] [1 … 15] of


integer; Assuming that each integer takes one memory location, the array is stored
in row–major order and the first element of the array is stored at location 100, what
is the address of the element A[i][j]?
A 15i + j + 84
B 15j + i + 84
C 10i + j + 89
D 10j + i + 89
AN A

4. Two matrices M1 and M2 are to be stored in arrays A and B, respectively. Each array
can be stored either in row-major or column-major order in contiguous memory
locations. The time complexity of an algorithm to compute M1×M2 will be
GATE 2004
A best if A is in row-major, and B is in column-major order
B best if both are in row-major order
C best if both are in column-major order
D independent of the storage scheme
AN A

5. In a compact single dimensional array representation for lower triangular matrices


(i.e, all the elements above the diagonal are zero) of size n x n, non–zero elements
(i.e, elements of the lower triangle) of each row are stored one after another, starting
from the first row, the index of the (i,j)th element of the lower triangular matrix in this
new representation is: GATE 1994
A i+j
B i + j –1
C j + [i(i–1)/2]
D i + [j(j–1)/2]
AN C

6. Consider the matrices P, Q and R which are 10 x 20, 20 x 30 and 30 x 40 matrices,


respectively. What is the minimum number of multiplications required to multiply the
three matrices?
A 18000
B 12000
C 24000
D 32000
AN A

7. Consider the matrices P, Q, R and S which are 20 x 15, 15 x 30, 30 x 5 and 5 x 40


matrices respectively. What is the minimum number of multiplications required to
multiply the four matrices?
A 6050
B 7500
C 7750
D 12000
AN C

8. Consider the brute force implementation in which we find all the possible ways of
multiplying the given set of n matrices. What is the time complexity of this
implementation?
A O(n!)
B O(n3)
C O(n2)
D Exponential
AN D

9. Let A be a square matrix of size n x n. Consider the following program. What is the
expected output?
C = 100
for i = 1 to n do
for j = 1 to n do
{
Temp = A[i][j] + C
A[i][j] = A[j][i]
A[j][i] = Temp – C
}
for i = 1 to n do
for j = 1 to n do
Output(A[i][j]);
The matrix A itself
Transpose of matrix A
Adding 100 to the upper diagonal elements and subtracting 100 from diagonal
elements of A
None of the above
AN A

You might also like