2 Arrays
2 Arrays
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.
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”.
• 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.
Example:
In C language, we declare array as shown below:
<data_type> <name_of_array>[<size_of_array>];
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.
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.)
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.
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
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)
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)
Example: Declaration of two-dimensional array “A” having “int” datatype and row size 6 and
column size 5. int A[6][5]
Similarly, languages that support column-major order representation are: Fortran, MATLAB,
GNU Octave, S-Plus, R, Julia, and Scilab.
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.
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]
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.
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:
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 α.
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
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
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].
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
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
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
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
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.
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
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
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.
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
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
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
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.
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)
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.
BEGIN:
x = A[i] Saving the element to be deleted
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).
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: 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
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]
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).
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).
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).
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)
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.
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;
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).
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
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.
In the given Algorithm, P[ ][ ] is the array and M x N is the size of the array.
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).
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).
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;
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).
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)
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.
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.
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.
Examples
Input: Arr[ ] = {7, 10, 4, 3, 20, 15}
k=3
Output: 7
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.
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
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
ALGORITHM GCD(a, b)
BEGIN:
IF a<b THEN
Swap(a,b)
IF b==0 THEN
RETURN a
RETURN GCD(b, a%b)
END;
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;
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
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
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}
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.
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.
Example:
Input: Array[ ]= {5, 10, 20, 15}
Output: 20
The element 20 has neighbours 10 and 15,
both of them are less than 20.
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.
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
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.
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;
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.
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
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
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
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
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