CEI Coding Questions
CEI Coding Questions
A test case consists of an input to the code and an expected output to verify a program’s
actual output against its expected output. It helps in validating your code by evaluating it
automatically.
In programming questions, input data is read from the standard input stream (STDIN) and the
results are printed to the standard output stream (STDOUT).
For example, in an online coding test in C, the following code is used to read an integer from
STDIN and print the result to STDOUT.
The online judge compares your output to the expected output, therefore, if you print an
output that is different from the expected output, then an error will be displayed on the
screen.
Your code is run against 2 types of test cases: Sample and internal
Note: Your code should be able to convert the sample input into the sample output. However,
this is not enough to pass the challenge, because the code will be run against multiple,
internal test cases too. Therefore, it is important that your code solves the problem statement.
Example
Your code is run against these test cases when you click Submit
Note: You cannot edit or change your code after you have submitted it.
By default, when you compile your code, it is run against the sample test cases. However, if
you want to test your code with more test cases, you can manually define these by using the
custom input section.
When you click Run code, the hidden test cases get executed, where your output and debug output are
displayed. You may use the print statement to debug why the hidden test cases are failing.
Typically, each hidden test case in a coding question may include specific scores for producing the exact
expected output.
// Driver code
int main()
{
int money = 15 ; // total money
int price = 1; // cost of each candy
int wrap = 3 ; // no of wrappers needs to be
// exchanged for one chocolate.
import java.io.*;
class GFG {
// Driver code
public static void main (String[] args)
{
int money = 15 ; // total money
int price = 1; // cost of each candy
// no of wrappers needs to be
// exchanged for one chocolate.
int wrap = 3 ;
System.out.println(
countMaxChoco(money, price, wrap));
}
}
Python:
# Recursive Python3 program to find
# maximum number of chocolates
import math
# Driver code
# total money
money = 15;
# no of wrappers needs to be
wrap = 3 ;
// Driver code
int main()
{
int money = 15 ; // total money
int price = 1; // cost of each candy
int wrap = 3 ; // no of wrappers needs to be
// exchanged for one chocolate.
class GFG {
// Corner case
if (money < price)
return 0;
// Driver code
public static void main (String[] args)
{
// total money
int money = 15;
// no of wrappers needs to be
int wrap = 3 ;
# Corner case
if (money < price) :
return 0
# Driver code
money = 15 # total money
price = 1 # cost of each candy
wrap = 3 # no of wrappers needs to be
# exchanged for one chocolate.
/*
#include <bits/stdc++.h>
using namespace std;
int main(){
int money, price, wrap;
int t;
cin >> t;
while(t--){
cin >> money >> price >> wrap;
cout << totalChocolates(money, price, wrap) << endl;
}
return 0;
}
Sample Input
STDIN Function
----- --------
3 t = 3 (test cases)
10 2 5 n = 10, c = 2, m = 5 (first test case)
12 4 4 n = 12, c = 4, m = 4 (second test case)
6 2 2 n = 6, c = 2, m = 2 (third test case)
Sample Output
6
3
5
Explanation
Bobby makes the following 3 trips to the store:
He spends 10 on 5 chocolates at 2 apiece. He then eats them and exchanges all 5 wrappers to get 1
more. He eats 6 chocolates.
He spends his 12 on 3 chocolates at 4 apiece. He has 3 wrappers, but needs 4 to trade for his next
chocolate. He eats 3 chocolates.
He spends 6 on 3 chocolates at 2 apiece. He then exchanges 2 of the 3 wrappers for 1 additional
piece. Next, he uses his third leftover chocolate wrapper from his initial purchase with the wrapper
from his trade-in to do a second trade-in for 1 more piece. At this point he has 1 wrapper left, which
is not enough to perform another trade-in. He eats 5 chocolates.
Python Code:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'chocolateFeast' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER c
# 3. INTEGER m
#
total_chocolar_bar = n//c
wrappers = total_chocolar_bar
while wrappers >= m :
bar_can_exchange = wrappers // m
total_chocolar_bar += bar_can_exchange
wrappers = bar_can_exchange + wrappers%m
return(total_chocolar_bar)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input().strip())
n = int(first_multiple_input[0])
c = int(first_multiple_input[1])
m = int(first_multiple_input[2])
result = chocolateFeast(n, c, m)
fptr.write(str(result) + '\n')
fptr.close()
Test Case 0:
Compiler Message
Success
Input (stdin)
Download
3
10 2 5
12 4 4
622
Expected Output
Download
6
3
Test Case 1:
Input:
200
16809 123 11668
20373 18211 10188
92512 413 33040
2339 4 1337
96741 945 77194
53270 182 30238
47733 230 4840
60751 346 20578
19150 99 2945
94566 514 47583
17274 5234 12885
39478 364 23991
46052 388 43028
21816 14645 1827
98573 74120 44437
47151 78 28526
18991 78 10010
28583 113 5299
34587 86 33334
59272 24946 44416
41894 36 640
65164 522 23728
40916 399 30670
7045 25 6484
45567 63 7564
63041 302 50870
14440 3 275
33773 13179 6929
71656 325 52375
1575 1 262
2216 8 35
16974 1248 6090
74892 314 48340
45312 848 44198
96428 81144 43066
61264 96 14300
52734 489 40749
42751 125 8850
51803 25 38253
15012 6806 2360
41447 94 8946
35849 343 28910
32715 123 21578
43344 425 7949
41986 104 18269
4893 37 921
13243 108 10845
45996 24153 38080
48630 366 48388
66474 560 50488
90041 613 9878
5975 32 4059
24892 157 3783
85276 579 4163
51005 503 44415
56364 40668 53449
78089 566 70805
44843 29 44838
31777 12538 1103
56037 545 24743
34612 116 21569
78806 591 64185
76790 661 44704
77417 52 35659
59861 219 38856
10645 94 10622
4338 39 2556
78479 513 59943
12574 11303 6650
23333 15178 16444
46143 19994 24879
7747 59 3587
72286 334 69906
99770 758 69806
85486 331 47153
85006 78153 30358
6614 3887 5753
98046 331 68600
27454 24335 17798
90430 14 37004
92285 9 56341
26628 209 4335
87158 54024 8721
7319 5432 6940
83253 31055 76601
59908 556 23522
52587 277 50630
51942 234 27353
38224 9603 22293
39749 326 38757
94372 326 44544
31149 292 4735
60695 347 28355
29297 91 15445
60608 543 17689
22268 28 7954
7628 56 5078
17404 9882 3646
26377 11981 13848
60217 144 24
41835 89 34999
77879 179 31082
6776 51 5473
64418 127 54187
88748 825 25437
69332 29 21687
38654 37809 27752
84880 757 76541
28441 7705 4276
78037 667 61963
34387 325 2593
24774 53 23837
58803 431 8270
74284 609 6760
11884 51 6499
24769 7 13138
7723 72 917
36919 262 36431
55480 496 18054
83218 572 270
11896 106 8061
92868 119 61630
67029 42406 65482
16151 5659 13619
54305 395 17271
74054 72920 65545
45753 196 28551
4145 3019 2607
80026 8 43540
42342 176 13286
8281 23 5518
94516 341 48463
36675 89 10736
88109 31038 13905
45222 23238 5933
78900 66292 45302
6970 67 2422
75850 72918 69563
8833 88 8220
89054 50341 12699
26996 142 7001
21774 73 13594
95131 235 94956
17489 154 13015
83036 625 41851
92256 33304 78345
68740 68 34109
56741 44464 44937
76527 406 24956
40312 150 34596
69422 39 38093
68456 46948 50268
99919 959 59041
22424 171 15391
85156 516 5140
4432 30 4053
2497 1604 1925
62708 601 7268
55238 8343 8602
18786 34 16023
48086 83 22018
37739 143 22531
17425 5 9471
8275 30 1023
68263 28 56980
62805 8203 47015
62145 224 8814
58714 416 17333
98043 457 91858
97605 807 28306
18571 154 16864
72333 638 12814
42501 367 15557
13185 3869 11205
57235 40867 11374
62269 30396 37489
40087 386 32766
7543 44 4454
80973 711 45988
26849 257 19705
57397 165 16054
52662 172 22539
36141 152 25515
96333 163 91785
5327 34 5080
1528 131 1308
22118 11 8112
30285 52 18617
22094 4104 4118
98446 76 73069
67107 18429 56091
19325 175 14156
51090 343 13666
54259 39030 44860
53328 39959 48103
33533 245 16064
50204 261 36997
4586 14 98
63548 277 26922
78711 514 63338
Output:
136
1
224
584
102
292
207
175
193
183
3
108
118
1
1
604
243
252
402
2
1164
124
102
281
723
208
4830
2
220
1581
285
13
238
53
1
638
107
342
2072
2
440
104
265
101
403
132
122
1
132
118
146
186
158
147
101
1
137
1546
2
102
298
133
116
1488
273
113
111
152
1
1
2
131
216
131
258
1
1
296
1
6459
10253
127
1
1
2
107
189
221
3
121
289
106
174
321
111
795
136
1
2
436
470
435
132
507
107
2390
1
112
3
116
105
467
136
121
233
3538
107
140
111
145
112
780
1
2
137
1
233
1
10003
240
360
277
412
2
1
1
104
1
100
1
190
298
404
113
132
2
1010
1
188
268
1780
1
104
131
165
147
1
104
6
552
579
263
3485
275
2437
7
277
141
214
120
120
113
115
3
1
2
103
171
113
104
347
306
237
591
156
11
2010
582
5
1295
3
110
148
1
1
136
192
330
229
153
Just given two sample test cases to understand
The above images show the difference between the column index and row index at each cell. The
cells having the same difference from top-left to bottom-down cell forms a diagonal.
Below are the steps to sort diagonal in decreasing order:
Store the diagonal element with a positive difference in one Array of Vectors(say Pos[]) such that
elements at the cell having difference(say a) is stored at index an of Pos[] array.
Store the diagonal element with the negative difference in another Array of Vectors(say Neg[]) such
that elements at the cell having difference(say -b) is stored at index abs(-b) = b of Neg[] array.
Sort both the Array of Vectors increasing order.
Traverse the given 2D vector and updated the value at the current cell with the value stored in Pos[]
and Neg[] array.
If the difference between column and row index(say d) is positive, then updated the value from Pos[d]
array and remove the last element as:
d=i-j
arr[i][j] = Pos[d][Pos.size()-1]
Pos[d].pop_back()
If the difference between column and row index(say d) is negative, then updated the value from
Neg[d] array and remove the last element as:
d=j-i
arr[i][j] = Neg[d][Neg.size()-1]
Neg[d].pop_back()
Java:
// Java program to sort the 2D matrix
// diagonally in decreasing order
import java.io.*;
import java.util.*;
class GFG {
public static void
diagonalSort(ArrayList<ArrayList<Integer> > mat)
{
int i, j;
// If diff is 0
else {
int l = Pos.get(0).size();
mat.get(i).set(j,
Pos.get(0).get(l - 1));
Pos.get(0).remove(l - 1);
}
}
}
// Driver Code
public static void main(String[] args)
{
ArrayList<ArrayList<Integer> > arr
= new ArrayList<ArrayList<Integer> >();
ArrayList<Integer> row1 = new ArrayList<Integer>();
row1.add(10);
row1.add(2);
row1.add(3);
arr.add(row1);
}
}
Python:
# Python program for the above approach
from collections import defaultdict
return matrix
# Driver Code
if __name__ == "__main__":
matrix = [[10, 2, 3],
[4, 5, 6],
[7, 8, 9]]
n = len(matrix)
m = len(matrix[0])
matrix = diagonalSort(matrix, n, m)
class GFG
{
// Driver Code
public static void main(String[] args)
{
ArrayList<ArrayList<Integer> > arr
= new ArrayList<ArrayList<Integer> >();
ArrayList<Integer> row1 = new ArrayList<Integer>();
row1.add(10);
row1.add(2);
row1.add(3);
arr.add(row1);
diagonalSort(arr);
}
}
Python:
# Python program to sort the 2D vector diagonally in decreasing order
# Driver Code
arr = [[10, 2, 3], [4, 5, 6], [7, 8, 9]]
DiagonalSort(arr)
printElement(arr)
Print a given matrix in spiral form
Given a 2D array, print it in spiral form.
Examples:
Input: {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16 }}
Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Explanation: The output is matrix in spiral format.
if (matrix.length == 0)
return ans;
// Iterate from 0 to R * C - 1
for (int i = 0; i < m * n; i++) {
ans.add(matrix[x][y]);
seen[x][y] = true;
int cr = x + dr[di];
int cc = y + dc[di];
// Driver Code
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function call
System.out.println(spiralOrder(a));
}
}
Python:
# python3 program for the above approach
def spiralOrder(matrix):
ans = []
if (len(matrix) == 0):
return ans
m = len(matrix)
n = len(matrix[0])
seen = [[0 for i in range(n)] for j in range(m)]
dr = [0, 1, 0, -1]
dc = [1, 0, -1, 0]
x=0
y=0
di = 0
# Iterate from 0 to R * C - 1
for i in range(m * n):
ans.append(matrix[x][y])
seen[x][y] = True
cr = x + dr[di]
cc = y + dc[di]
# Driver code
if __name__ == "__main__":
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
# Function call
for x in spiralOrder(a):
print(x, end=" ")
print()
Print a given matrix in spiral form by dividing the matrix into cycles:
To solve the problem follow the below idea:
The problem can be solved by dividing the matrix into loops or squares or
boundaries. It can be seen that the elements of the outer loop are printed first in a
clockwise manner then the elements of the inner loop are printed. So printing the
elements of a loop can be solved using four loops that print all the elements. Every
‘for’ loop defines a single-direction movement along with the matrix. The first for
loop represents the movement from left to right, whereas the second crawl
represents the movement from top to bottom, the third represents the movement from
the right to left, and the fourth represents the movement from bottom to up
Follow the given steps to solve the problem:
Create and initialize variables k – starting row index, m – ending row index, l –
starting column index, n – ending column index
Run a loop until all the squares of loops are printed.
In each outer loop traversal print the elements of a square in a clockwise manner.
Print the top row, i.e. Print the elements of the kth row from column index l to n,
and increase the count of k.
Print the right column, i.e. Print the last column or n-1th column from row index
k to m and decrease the count of n.
Print the bottom row, i.e. if k < m, then print the elements of the m-1th row from
column n-1 to l and decrease the count of m
Print the left column, i.e. if l < n, then print the elements of lth column from m-
1th row to k and increase the count of l.
Java:
// Java program to print a given matrix in spiral form
import java.io.*;
class GFG {
// Driver Code
public static void main(String[] args)
{
int R = 4;
int C = 4;
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function Call
spiralPrint(R, C, a);
}
}
Python:
# Python3 program to print
# given matrix in spiral form
k += 1
n -= 1
m -= 1
l += 1
# Driver Code
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
R=4
C=4
# Function Call
spiralPrint(R, C, a)
Print a given matrix in a spiral using recursion:
To solve the problem follow the below idea:
The above problem can be solved by printing the boundary of the Matrix
recursively. In each recursive call, we decrease the dimensions of the matrix. The
idea of printing the boundary or loops is the same
Follow the given steps to solve the problem:
create a recursive function that takes a matrix and some variables (k – starting
row index, m – ending row index, l – starting column index, n – ending column
index) as parameters
Check the base cases (starting index is less than or equal to the ending index) and
print the boundary elements in a clockwise manner
Print the top row, i.e. Print the elements of the kth row from column index l to n,
and increase the count of k
Print the right column, i.e. Print the last column or n-1th column from row index
k to m and decrease the count of n
Print the bottom row, i.e. if k > m, then print the elements of m-1th row from
column n-1 to l and decrease the count of m
Print the left column, i.e. if l < n, then print the elements of the lth column from
m-1th row to k and increase the count of l
Call the function recursively with the values of starting and ending indices of
rows and columns
Java:
// Java program for the above approach
import java.util.*;
class GFG {
static int R = 4;
static int C = 4;
// Driver Code
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function Call
print(a, 0, 0, R, C);
}
}
Python:
# Python3 program for the above approach
printdata(arr, i + 1, j + 1, m - 1, n - 1)
# Driver code
if __name__ == "__main__":
R=4
C=4
arr = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
# Function Call
printdata(arr, 0, 0, R, C)
Print a given matrix in spiral using DFS:
To solve the problem follow the below idea:
Another recursive approach is to consider DFS movement within the matrix (right-
>down->left->up->right->..->end). We do this by modifying the matrix itself such
that when DFS algorithm visits each matrix cell it’s changed to a value which
cannot be contained within the matrix. The DFS algorithm is terminated when it
visits a cell such that all of its surrounding cells are already visited. The direction of
the DFS search is controlled by a variable.
Follow the given steps to solve the problem:
create a DFS function that takes matrix, cell indices, and direction
checks are cell indices pointing to a valid cell (that is, not visited and in bounds)?
if not, skip this cell
print cell value
mark matrix cell pointed by indicates as visited by changing it to a value not
supported in the matrix
check are surrounding cells valid? if not stop the algorithm, else continue
if the direction is given right then check, if the cell to the right is valid. if so, DFS
to the right cell given the steps above, else, change the direction to down and
DFS downwards given the steps above
else, if the direction given is down then check, if the cell to the down is valid. if
so, DFS to the cell below given the steps above, else, change the direction to left
and DFS leftwards given the steps above
else, if the direction given is left then check, if the cell to the left is valid. if so,
DFS to the left cell given the steps above, else, change the direction to up and
DFS upwards given the steps above
else, if the direction given is up then check, if the cell to the up is valid. if so,
DFS to the upper cell given the steps above, else, change the direction to right
and DFS rightwards given the steps above
Java:
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
public static int R = 4, C = 4;
public static boolean isInBounds(int i, int j)
{
if (i < 0 || i >= R || j < 0 || j >= C)
return false;
return true;
}
// to traverse spirally
public static ArrayList<Integer>
spirallyTraverse(int[][] matrix)
{
ArrayList<Integer> res = new ArrayList<Integer>();
spirallyDFSTravserse(matrix, 0, 0, 0, res);
return res;
}
// Driver code
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
// Function Call
ArrayList<Integer> res = spirallyTraverse(a);
int size = res.size();
for (int i = 0; i < size; ++i)
System.out.print(res.get(i) + " ");
System.out.println();
}
}
Python:
# Python3 program for the above approach
R=4
C=4
return False
allBlocked = True
for k in range(-1, 2, 2):
allBlocked = allBlocked and isBlocked(
matrix, k + i, j) and isBlocked(matrix, i, j + k)
res.append(matrix[i][j])
matrix[i][j] = -1
if (allBlocked):
return
elif(Dir == 1):
if (not isBlocked(matrix, i + 1, j)):
nxt_i += 1
else:
nxt_dir = 2
nxt_j -= 1
elif(Dir == 2):
if (not isBlocked(matrix, i, j - 1)):
nxt_j -= 1
else:
nxt_dir = 3
nxt_i -= 1
elif(Dir == 3):
if (not isBlocked(matrix, i - 1, j)):
nxt_i -= 1
else:
nxt_dir = 0
nxt_j += 1
# To traverse spirally
def spirallyTraverse(matrix):
res = []
spirallyDFSTravserse(matrix, 0, 0, 0, res)
return res
# Driver code
if __name__ == "__main__":
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
# Function Call
res = spirallyTraverse(a)
print(*res)
class Main {
ind = i + 1
while ind < rows:
if matrix[ind][j] != 1:
matrix[ind][j] = -1
ind += 1
ind = j + 1
while ind < cols:
if matrix[i][ind] != 1:
matrix[i][ind] = -1
ind += 1
class GFG {
public static void modifyMatrix(int mat[][], int R,
int C)
{
int row[] = new int[R];
int col[] = new int[C];
int i, j;
System.out.println("Matrix Initially");
printMatrix(mat, 3, 4);
modifyMatrix(mat, 3, 4);
System.out.println("Matrix after modification");
printMatrix(mat, 3, 4);
}
}
Python:
# Python3 Code For A Boolean Matrix Question
R=3
C=4
def modifyMatrix(mat):
row = [0] * R
col = [0] * C
def printMatrix(mat):
for i in range(0, R):
print("Input Matrix")
printMatrix(mat)
modifyMatrix(mat)
if (j == 0 && mat[i][j] == 1)
col_flag = true;
if (mat[i][j] == 1) {
mat[0][j] = 1;
mat[i][0] = 1;
}
}
}
if (mat[i][j] == 1):
mat[0][j] = 1
mat[i][0] = 1
def printMatrix(mat):
print()
# Driver Code
mat = [[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]]
modifyMatrix(mat)
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Rotated the input matrix by
90 degrees in anti-clockwise direction.
An approach that requires extra space is already discussed in a different article:
Inplace rotate square matrix by 90 degrees | Set 1
This post discusses the same problem with a different approach which is space-
optimized.
Approach: The idea is to find the transpose of the matrix and then reverse the
columns of the transposed matrix.
Here is an example to show how this works.
Algorithm:
1. To solve the given problem there are two tasks. 1st is finding the transpose and
the second is reversing the columns without using extra space
2. A transpose of a matrix is when the matrix is flipped over its diagonal, i.e the
row index of an element becomes the column index and vice versa. So to find the
transpose interchange of the elements at position (i, j) with (j, i). Run two loops,
the outer loop from 0 to row count and the inner loop from 0 to the index of the
outer loop.
3. To reverse the column of the transposed matrix, run two nested loops, the outer
loop from 0 to column count and the inner loop from 0 to row count/2,
interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices
of inner and outer loop respectively.
Java:
// JAVA Code for left Rotation of a
// matrix by 90 degree without using
// any extra space
import java.util.*;
class GFG {
rotate90(arr);
printMatrix(arr);
}
}
Python:
# Python 3 program for left rotation of matrix by 90
# degree without using extra space
R=4
C=4
def reverseColumns(arr):
for i in range(C):
j=0
k = C-1
while j < k:
t = arr[j][i]
arr[j][i] = arr[k][i]
arr[k][i] = t
j += 1
k -= 1
def printMatrix(arr):
for i in range(R):
for j in range(C):
print(str(arr[i][j]), end=" ")
print()
def rotate90(arr):
transpose(arr)
reverseColumns(arr)
# Driven code
arr = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
rotate90(arr)
printMatrix(arr)
Another Approach using a single traversal of the matrix :
The idea is to traverse along the boundaries of the matrix and shift the positions of
the elements in 900 anticlockwise directions in each boundary. There are such (n/2-1)
boundaries in the matrix.
Algorithm:
1. Iterate over all the boundaries in the matrix. There are total (n/2-1) boundaries
2. For each boundary take the 4 corner elements and swap them such that the 4
corner elements get rotated in anticlockwise directions. Then take the next 4
elements along the edges(left, right, top, bottom) and swap them in an
anticlockwise direction. Continue as long as all the elements in that particular
boundary get rotated in 900 anticlockwise directions.
3. Then move on to the next inner boundary and continue the process as long the
whole matrix is rotated in 90 0 anticlockwise direction.
Java:
// JAVA Code for left Rotation of a matrix
// by 90 degree without using any extra space
import java.util.*;
class GFG {
arr[i + j][i] = d;
arr[n - 1 - i][i + j] = a;
arr[n - 1 - i - j][n - 1 - i] = b;
arr[i][n - 1 - i - j] = c;
}
}
}
// Function for print matrix
static void printMatrix(int arr[][])
{
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println("");
}
}
rotateby90(arr);
printMatrix(arr);
}
}
Python:
# Function to rotate matrix anticlockwise by 90 degrees.
def rotateby90(arr):
n = len(arr)
a,b,c,d = 0,0,0,0
arr[i + j][i] = d
arr[n - 1 - i][i + j] = a
arr[n - 1 - i - j][n - 1 - i] = b
arr[i][n - 1 - i - j] = c
for i in range(len(arr)):
for j in range(len(arr[0])):
print(arr[i][j] ,end = " ")
print()
# Driven code
arr = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
print("\nnumpy implementation\n")
print(flipmat)
Note: The above steps/programs do left (or anticlockwise) rotation. Let’s see how to
do the right rotation or clockwise rotation. The approach would be similar. Find the
transpose of the matrix and then reverse the rows of the transposed matrix.
This is how it is done.
Sea
rch in a row wise and column wise sorted
matrix
Given an n x n matrix and an integer x, find the position of x in the matrix if it is
present. Otherwise, print “Element not found”. Every row and column of the matrix
is sorted in increasing order. The designed algorithm should have linear time
complexity
Examples:
Input: mat[4][4] = { {10, 20, 30, 40}, x = 29
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}}
class GFG {
static int search(int[][] mat, int n, int x)
{
if (n == 0)
return -1;
// Driver code
public static void main(String[] args)
{
int mat[][] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
// Function call
search(mat, 4, 29);
}
}
Python:
# Python program to search an element in row-wise
# and column-wise sorted matrix
# Function call
search(mat, 4, 29)
Search in a row-wise and column-wise sorted matrix in linear time complexity:
The simple idea is to remove a row or column in each comparison until an element
is found. Start searching from the top-right corner of the matrix. There are three
possible cases:-
1. The given number is greater than the current number: This will ensure that all
the elements in the current row are smaller than the given number as the pointer
is already at the right-most elements and the row is sorted. Thus, the entire row
gets eliminated and continues the search for the next row. Here, elimination
means that a row needs not to be searched.
2. The given number is smaller than the current number: This will ensure that all
the elements in the current column are greater than the given number. Thus, the
entire column gets eliminated and continues the search for the previous column,
i.e. the column on the immediate left.
3. The given number is equal to the current number: This will end the search.
Follow the given steps to solve the problem:
Let the given element be x, create two variable i = 0, j = n-1 as index of row and
column.
Run a loop until i < n.
Check if the current element is greater than x then decrease the count
of j. Exclude the current column.
Check if the current element is less than x then increase the count of i.
Exclude the current row.
If the element is equal, then print the position and end.
Print the Element is not found
Java:
// JAVA Code for Search in a row wise and
// column wise sorted matrix
class GFG {
i=0
if (mat[i][j] == x):
# if mat[i][j] < x
else:
i += 1
# Driver Code
if __name__ == "__main__":
mat = [[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]]
# Function call
search(mat, 4, 29)
Using Linear Search:
Approach:
In this approach, we traverse the matrix row by row and check each element until we
find the target element.
Define a function search_element that takes a matrix mat and a target element x as
input.
Traverse the matrix mat row by row using a nested loop.
For each element in the matrix, check if it is equal to the target element x.
If the target element is found, return its position as a string in the format “Found at
(i, j)”, where i and j are the row and column indices of the element, respectively.
If the target element is not found, return the string “Element not found”.
Java:
// Java Code for the above approach
import java.util.ArrayList;
import java.util.List;
class GFG {
public static String search_element(List<List<Integer>> mat, int x) {
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat.get(0).size(); j++) {
if (mat.get(i).get(j) == x) {
return "Found at (" + i + ", " + j + ")";
}
}
}
return "Element not found";
}
int x = 29;
System.out.println(search_element(mat, x)); // Output: Found at (2, 1)
x = 100;
System.out.println(search_element(mat, x)); // Output: Element not found
}
}
Python:
def search_element(mat, x):
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == x:
return f"Found at ({i}, {j})"
return "Element not found"
mat = [
[10, 20, 30, 40],
[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]
]
x = 29
print(search_element(mat, x)) # Output: Found at (2, 1)
x = 100
print(search_element(mat, x)) # Output: Element not found
class GFG {
static int R = 4 ;
static int C = 4 ;
return max_row_index;
}
// Driver Code
public static void main(String[] args) {
}
}
Python:
// Java program for the above approach
import java.util.*;
class GFG {
static int R = 4 ;
static int C = 4 ;
// Function to find the index of first index
// of 1 in a boolean array arr[]
static int first(int arr[], int low, int high)
{
if(high >= low)
{
// Get the middle index
int mid = low + (high - low)/2;
return max_row_index;
}
// Driver Code
public static void main(String[] args) {
}
}
Python:
# Python implementation of the approach
R,C = 4,4
# Function to find the index of first index
# of 1 in a boolean array arr
def first(arr , low , high):
return -1
return max_row_index
# Driver Code
mat = [[0, 0, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]]
print("Index of row with maximum 1s is " + str(rowWithMax1s(mat)))
We can do better. Since each row is sorted, we can use Binary Search to count 1s in
each row. We find the index of the first instance of 1 in each row. The count of 1s
will be equal to the total number of columns minus the index of the first 1.
Java:
// Java program to find the row
// with maximum number of 1s
import java.io.*;
class GFG {
static int R = 4, C = 4;
// Function to find the index of first index
// of 1 in a boolean array arr[]
static int first(int arr[], int low, int high)
{
if (high >= low) {
// Get the middle index
int mid = low + (high - low) / 2;
// Check if the element at middle index is first 1
if ((mid == 0 || (arr[mid - 1] == 0)) && arr[mid] == 1)
return mid;
return max_row_index;
}
// Driver Code
public static void main(String[] args)
{
int mat[][] = { { 0, 0, 0, 1 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 } };
System.out.println("Index of row with maximum 1s is "
+
rowWithMax1s(mat));
}
}
Python:
# Python3 program to find the row
# with maximum number of 1s
# If the element is 0,
# recur for right side
elif arr[mid] == 0:
return first(arr, (mid + 1), high)
def rowWithMax1s(mat):
return max_row_index
# Driver Code
mat = [[0, 0, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]]
print("Index of row with maximum 1s is",
rowWithMax1s(mat))
the above solution can be optimized further. Instead of doing a binary search in
every row, we first check whether the row has more 1s than max so far. If the row
has more 1s, then only count 1s in the row. Also, to count 1s in a row, we don’t do a
binary search in a complete row, we do a search before the index of the last max.
Java:
public class gfg
{
// The main function that returns index
// of row with maximum number of 1s.
static int rowWithMax1s(boolean mat[][])
{
int i, index;
return max_row_index
The worst case of the above solution occurs for a matrix like following.
000…01
0 0 0 ..0 1 1
0…0111
….0 1 1 1 1
Following method works in O(m+n) time complexity in worst case.
Step1: Get the index of first (or leftmost) 1 in the first row.
Step2: Do following for every row after the first row
…IF the element on left of previous leftmost 1 is 0, ignore this row.
…ELSE Move left until a 0 is found. Update the leftmost index to this
index and max_row_index to be the current row.
The time complexity is O(m+n) because we can possibly go as far left
as we came ahead in the first step.
Java: // Java program to find the row
// with maximum number of 1s
import java.io.*;
class GFG {
static int R = 4, C = 4;
// Function that returns index of row
// with maximum number of 1s.
static int rowWithMax1s(int mat[][])
{
// Initialize first row as row with max 1s
int j,max_row_index = 0;
j = C - 1;
class GFG {
static int R = 4, C = 4;
// Function that returns index of row
// with maximum number of 1s.
static int rowWithMax1s(int mat[][])
{
// Initialize first row as row with max 1s
int j,max_row_index = 0;
j = C - 1;
def rowWithMax1s(mat):
# Driver Code
mat = [[0, 0, 0, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]]
print("Index of row with maximum 1s is",
rowWithMax1s(mat))
Input: a = 10
Output: 57
Input: a = 19
Output: 205.77
Approach: Area of the shaded region will be:
The area of a semicircle is (3.14 * r2) / 2 where r is the radius of the semicircle
which is equal to a / 2.
Hence, Area of the shaded region = 4 * (3.14 * (a * a) / 8 ) – a * a
return ShadedArea;
}
// Driver code
public static void main(String[] args)
{
float a = 10;
System.out.println(findAreaShaded(a));
}
}
Python:
# Python3 implementation of the approach
return ShadedArea;
# Driver code
if __name__ == '__main__':
a = 10
print(findAreaShaded(a))
Example 1
Calculate the area of the shaded region in the right triangle below.
Solution
Area of shaded region = area of outer shape – area of the unshaded inner shape
= 75 cm2.
= 30 cm2.
= 45 cm2.
Example 2
Solution
AB/EC = BD/CD
6/3 = 8/CD
Cross multiply.
6 CD = 3 x 8 = 24
= 24 m2
Area of triangle = (½ x 3 x 4) m2
= 6 m2
= 18 m2
Let’s see a few examples below to understand how to find the area of the shaded region in a
rectangle.
Example 3
Solution
Area of shaded region = area of outer shape – area of unshaded inner shape
= 56 m2
Example 4
Given, AB = 120 cm, AF = CD = 40 cm and ED = 20 cm. Calculate the area of the shaded
region of the diagram below.
Solution
Area of the shaded region = area of the rectangle ACDF – area of triangle BFE.
= 4,800 cm2.
= 100 cm
= 400 cm2.
= 4,400 cm2
Example 5
Calculate the area of the shaded diagram below.
Solution
This is a composite shape; therefore, we subdivide the diagram into shapes with area
formulas.
= 54 cm2 + 96 cm2
= 150 cm2.
Let’s see a few examples below to understand how to find the area of a shaded region in a
square.
Example 6
Area of the shaded region = area of the square – area of the four unshaded small squares.
= 12 cm.
= 80 cm2
Example 7
Calculate the shaded area of the square below if the side length of the hexagon is 6 cm.
Solution
Area of the shaded region = area of the square – area of the hexagon
= 225 cm2
A = (L2n)/[4tan(180/n)]
= 216/ 2.3094
A = 93.53 cm2
= 131.47 cm2