0% found this document useful (0 votes)
13 views108 pages

CEI Coding Questions

The document explains the concept of test cases in programming, detailing their role in validating code by comparing actual outputs against expected outputs. It describes two types of test cases: sample test cases, which are visible and used for immediate validation, and internal test cases, which are hidden and cover various scenarios for comprehensive testing. Additionally, it provides a programming challenge involving calculating the maximum number of chocolates one can eat based on money, price, and wrappers, along with implementations in C++, Java, and Python.

Uploaded by

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

CEI Coding Questions

The document explains the concept of test cases in programming, detailing their role in validating code by comparing actual outputs against expected outputs. It describes two types of test cases: sample test cases, which are visible and used for immediate validation, and internal test cases, which are hidden and cover various scenarios for comprehensive testing. Additionally, it provides a programming challenge involving calculating the maximum number of chocolates one can eat based on money, price, and wrappers, along with implementations in C++, Java, and Python.

Uploaded by

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

Test cases

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.

Types of test cases

Your code is run against 2 types of test cases: Sample and internal

Sample test cases

 Usually available after the Constraints section


 Known as Sample input and Sample output
 Used to check the logic and validate your code instantly because you can see both the input
and expected output values when your code is run against these test cases
 Your code is run against these test cases when you click Compile & Test

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.

Internal test cases

 Not visible on the platform


o Contains multiple test cases that cover a number of scenarios in order to test
your code in a holistic manner

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.

Hidden Test Cases


Hidden test cases include your test setter's corner cases or different scenarios defined to validate your
coding solution. These test cases check whether your solution addresses the problem, including its various
constraints. They do not display the expected output of the test case.
For instance, the hidden test cases may be defined to validate your coding logic against boundary values,
error handling scenarios, and so on. Depending on the complexity of the coding question or for specific
skills assessment, your test setter may include one or more hidden test cases for your question.

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.

Program for Chocolate and Wrapper


Puzzle
Given the following three values, the task is to find the total number of maximum
chocolates you can eat.
1. money: Money you have to buy chocolates
2. price: Price of a chocolate
3. wrap: Number of wrappers to be returned for getting one extra chocolate.
It may be assumed that all given values are positive integers and greater than 1.
Examples:
Input: money = 16, price = 2, wrap = 2
Output: 15
Price of a chocolate is 2. You can buy 8 chocolates from
amount 16. You can return 8 wrappers back and get 4 more
chocolates. Then you can return 4 wrappers and get 2 more
chocolates. Finally you can return 2 wrappers to get 1
more chocolate.

Input: money = 15, price = 1, wrap = 3


Output: 22
We buy and eat 15 chocolates
We return 15 wrappers and get 5 more chocolates.
We return 3 wrappers, get 1 chocolate and eat it
(keep 2 wrappers). Now we have 3 wrappers. Return
3 and get 1 more chocolate.
So total chocolates = 15 + 5 + 1 + 1

Input: money = 20, price = 3, wrap = 5


Output: 7
C++ Implementation:
// Recursive C++ program to find maximum
// number of chocolates
#include <iostream>
using namespace std;

// Returns number of chocolates we can


// have from given number of chocolates
// and number of wrappers required to
// get a chocolate.
int countRec(int choc, int wrap)
{
// If number of chocolates is less than
// number of wrappers required.
if (choc < wrap)
return 0;

// We can immediately get newChoc using


// wrappers of choc.
int newChoc = choc/wrap;

// Now we have "newChoc + choc%wrap" wrappers.


return newChoc + countRec(newChoc + choc%wrap,
wrap);
}

// Returns maximum number of chocolates we can eat


// with given money, price of chocolate and number
// of wrappers required to get a chocolate.
int countMaxChoco(int money, int price, int wrap)
{
// We can directly buy below number of chocolates
int choc = money/price;

// countRec returns number of chocolates we can


// have from given number of chocolates
return choc + countRec(choc, wrap);
}

// 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.

cout << countMaxChoco(money, price, wrap);


return 0;
}
Java:
// Recursive java program to find maximum
// number of chocolates

import java.io.*;

class GFG {

// Returns number of chocolates we can


// have from given number of chocolates
// and number of wrappers required to
// get a chocolate.
static int countRec(int choc, int wrap)
{

// If number of chocolates is less than


// number of wrappers required.
if (choc < wrap)
return 0;

// We can immediately get newChoc using


// wrappers of choc.
int newChoc = choc / wrap;

// Now we have "newChoc + choc%wrap"


// wrappers.
return newChoc + countRec(newChoc +
choc % wrap, wrap);
}

// Returns maximum number of chocolates


// we can eat with given money, price of
// chocolate and number of wrappers
// required to get a chocolate.
static int countMaxChoco(int money,
int price, int wrap)
{

// We can directly buy below number of


// chocolates
int choc = money/price;

// countRec returns number of chocolates


// we can have from given number of
// chocolates
return choc + countRec(choc, wrap);
}

// 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

# Returns number of chocolates we can


# have from given number of chocolates
# and number of wrappers required to
# get a chocolate.
def countRec(choc, wrap):

# If number of chocolates is less


# than number of wrappers required.
if (choc < wrap):
return 0;

# We can immediately get newChoc


# using wrappers of choc.
newChoc = choc / wrap;

# Now we have "newChoc + choc%wrap" wrappers.


return newChoc + countRec(newChoc + choc %
wrap, wrap);

# Returns maximum number of chocolates


# we can eat with given money, price
# of chocolate and number of wrappers
# required to get a chocolate.
def countMaxChoco(money, price, wrap):
# We can directly buy below
# number of chocolates
choc = money / price;

# countRec returns number


# of chocolates we can
# have from given number
# of chocolates
return math.floor(choc + countRec(choc, wrap));

# Driver code

# total money
money = 15;

# cost of each candy


price = 1;

# no of wrappers needs to be
wrap = 3 ;

# exchanged for one chocolate.


print(countMaxChoco(money, price, wrap));
An efficient solution is to use a direct formula to find the number of chocolates.
Find initial number of chocolates by
dividing the amount with per piece cost.
i.e. choc = money / price

then apply below formula


choc += (choc - 1)/(wrap - 1)
In the above naive implementation, we noticed that after finding the initial number of chocolates, we
recursively divide the number of chocolates by the number of wrappers required. until we left with 1
chocolate or wrapper.
We are recomputing the values i.e. ((choc/wrap + choc%wrap)/wrap until we get 1.
It is observed that we can get the result by just reducing the values of chocolates and wrappers by 1
and then divide them to get the result (choc-1)/(wrap-1)
C++ Implementation:
// Efficient C++ program to find maximum
// number of chocolates
#include <iostream>
using namespace std;

// Returns maximum number of chocolates we can eat


// with given money, price of chocolate and number
// of wrapprices required to get a chocolate.
int countMaxChoco(int money, int price, int wrap)
{
// Corner case
if (money < price)
return 0;

// First find number of chocolates that


// can be purchased with the given amount
int choc = money / price;

// Now just add number of chocolates with the


// chocolates gained by wrapprices
choc = choc + (choc - 1) / (wrap - 1);
return choc;
}

// 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.

cout << countMaxChoco(money, price, wrap);


return 0;
}
Java:
// Efficient Java program to find maximum
// number of chocolates
import java.io.*;

class GFG {

// Returns maximum number of chocolates


// we can eat with given money, price
// of chocolate and number of wrapprices
// required to get a chocolate.
static int countMaxChoco(int money,
int price, int wrap)
{

// Corner case
if (money < price)
return 0;

// First find number of chocolates


// that can be purchased with the
// given amount
int choc = money / price;

// Now just add number of chocolates


// with the chocolates gained by
// wrapprices
choc = choc + (choc - 1) / (wrap - 1);
return choc;
}

// Driver code
public static void main (String[] args)
{

// total money
int money = 15;

// cost of each candy


int price = 1;

// no of wrappers needs to be
int wrap = 3 ;

// exchanged for one chocolate.


System.out.println(
countMaxChoco(money, price, wrap));
}
}
Python:
# Efficient Python3 program to find
# maximum number of chocolates

# Returns maximum number of


# chocolates we can eat with
# given money, price of chocolate
# and number of wrapprices
# required to get a chocolate.
def countMaxChoco(money, price, wrap) :

# Corner case
if (money < price) :
return 0

# First find number of chocolates


# that can be purchased with the
# given amount
choc = int(money / price)

# Now just add number of


# chocolates with the chocolates
# gained by wrapprices
choc = choc + (choc - 1) / (wrap - 1)
return int(choc )

# Driver code
money = 15 # total money
price = 1 # cost of each candy
wrap = 3 # no of wrappers needs to be
# exchanged for one chocolate.

print(countMaxChoco(money, price, wrap))

Chocolate and Wrapper Puzzle


Given the following three values, the task is to find the total number of maximum chocolates you can
eat.
Money: Money you have to buy chocolates.
Price: Price of a chocolate.
Wrap: Number of wrappers to be returned for getting one extra chocolate.
Note: It may be assumed that all given values are positive integers and greater than 1.
Example: #1
Input : money = 16, price = 2, wrap = 2
Output : 15
Price of a chocolate is 2. You can buy 8 chocolates from
amount 16. You can return 8 wrappers back and get 4 more
chocolates. Then you can return 4 wrappers and get 2 more
chocolates. Finally you can return 2 wrappers to get 1
more chocolate.
Example: #2
Input : money = 15, price = 1, wrap = 3
Output : 22
We buy and eat 15 chocolates
We return 15 wrappers and get 5 more chocolates.
We return 3 wrappers, get 1 chocolate and eat it
(keep 2 wrappers). Now we have 3 wrappers. Return
3 and get 1 more chocolate.
So total chocolates = 15 + 5 + 1 + 1

/*

Program for Chocolate and Wrapper Puzzle


Given following three values, the task is to find the total number of maximum chocolates you can
eat.
money : Money you have to buy chocolates
price : Price of a chocolate
wrap : Number of wrappers to be returned for getting one extra chocolate.
It may be assumed that all given values are positive integers and greater than 1.
Examples:
Input : money = 16, price = 2, wrap = 2
Output : 15
Price of a chocolate is 2. You can buy 8 chocolates from
amount 16. You can return 8 wrappers back and get 4 more
chocolates. Then you can return 4 wrappers and get 2 more
chocolates. Finally you can return 2 wrappers to get 1
more chocolate.
Input : money = 15, price = 1, wrap = 3
Output : 22
We buy and eat 15 chocolates
We return 15 wrappers and get 5 more chocolates.
We return 3 wrappers, get 1 chocolate and eat it
(keep 2 wrappers). Now we have 3 wrappers. Return
3 and get 1 more chocolate.
So total chocolates = 15 + 5 + 1 + 1
Input : money = 20, price = 3, wrap = 5
Output : 7
*/

#include <bits/stdc++.h>
using namespace std;

int util(int money, int price, int wrap, int curr_wrap){


if(money==0 || money < price){
if(curr_wrap==0 || curr_wrap < wrap) return 0;
return (curr_wrap/wrap) + util(money, price, wrap, (curr_wrap%wrap)+(curr_wrap/wrap));
}

int choco = (money/price);


choco += util((money%price), price, wrap, curr_wrap + choco);
return choco;
}

int totalChocolates(int money, int price, int wrap){


return util(money, price, wrap, 0);
}

int main(){
int money, price, wrap;
int t;
cin >> t;
while(t--){
cin >> money >> price >> wrap;
cout << totalChocolates(money, price, wrap) << endl;
}
return 0;
}

Chocolate Feast from Hackerrank


Little Bobby loves chocolate. He frequently goes to his favorite store, Penny Auntie, to buy them.
They are having a promotion at Penny Auntie. If Bobby saves enough wrappers, he can turn them in
for a free chocolate.
Example
He has to spend, bars cost , and he can turn in wrappers to receive another bar. Initially, he
buys bars and has wrappers after eating them. He turns in of them, leaving him with , for more bars.
After eating those two, he has wrappers, turns in leaving him with wrapper and his new bar. Once
he eats that one, he has wrappers and turns them in for another bar. After eating that one, he only
has wrapper, and his feast ends. Overall, he has eaten bars.
Function Description
Complete the chocolateFeast function in the editor below.
chocolateFeast has the following parameter(s):
int n: Bobby's initial amount of money
int c: the cost of a chocolate bar
int m: the number of wrappers he can turn in for a free bar
Returns
int: the number of chocolates Bobby can eat after taking full advantage of the promotion
Note: Little Bobby will always turn in his wrappers if he has enough to get a free chocolate.
Input Format
The first line contains an integer, , the number of test cases to analyze.
Each of the next lines contains three space-separated integers: , , and . They represent money to
spend, cost of a chocolate, and the number of wrappers he can turn in for a free chocolate.
Constraints

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
#

def chocolateFeast(n, c, m):


# Write your code here

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())

for t_itr in range(t):


first_multiple_input = input().rstrip().split()

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

Sample Matrix Problem Solving

S. No Question Page No.


1 Sort a 2D vector diagonally
2 Spiral Matrix
3 Boolean matrix
4 Rotate matrix by 90 degrees
5 Search in a row-column sorted Matrix
6 Row with maximum 1s

Sort a 2D vector diagonally


Given a 2D vector of NxM integers. The task is to sort the elements of the vectors diagonally from
top-left to bottom-right in decreasing order.
Examples:
Input: arr[][] = { { 10, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }
Output:
10 6 3
892
745
Input: arr[][] = { { 10, 2, 43 }, { 40, 5, 16 }, { 71, 8, 29 }, {1, 100, 5} }
Output:
29 16 43
40 10 2
100 8 5
1 71 5

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)
{

// Calculate the rows and column


int row = mat.size();
int col = mat.get(0).size();

// Arraylist of Arraylist to store the


// diagonal elements
ArrayList<ArrayList<Integer> > Neg
= new ArrayList<ArrayList<Integer> >();
ArrayList<ArrayList<Integer> > Pos
= new ArrayList<ArrayList<Integer> >();

int i, j;

for (i = 0; i < row; i++) {


ArrayList<Integer> temp
= new ArrayList<Integer>();
Neg.add(temp);
}

for (j = 0; j < col; j++) {


ArrayList<Integer> temp
= new ArrayList<Integer>();
Pos.add(temp);
}

// Traverse the 2D matrix and put


// element in Arraylist of Arraylist at
// index difference between indexes
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {

// If diff is negative, then


// push element to Neg[]
if (j < i) {
Neg.get(i - j).add(mat.get(i).get(j));
}

// If diff is positive, then


// push element to Pos[]
else if (i < j) {
Pos.get(j - i).add(mat.get(i).get(j));
}

// If diff is 0, then push


// element to Pos[0]
else {
Pos.get(0).add(mat.get(i).get(j));
}
}
}

// Sort the Array of vectors


for (i = 0; i < row; i++) {
Collections.sort(Neg.get(i));
;
}
for (i = 0; i < col; i++) {
Collections.sort(Pos.get(i));
;
}

// Update the value to mat


// from the sorted Arraylist of Arraylist
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
// If diff is positive
if (j < i) {
int d = i - j;
int l = Neg.get(d).size();
mat.get(i).set(j,
Neg.get(d).get(l - 1));
Neg.get(d).remove(l - 1);
}
// If diff is negative
else if (i < j) {
int d = j - i;
int l = Pos.get(d).size();
mat.get(i).set(j,
Pos.get(d).get(l - 1));
Pos.get(d).remove(l - 1);
}

// 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);
}
}
}

// Print diagonally sorted matrix


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.print(mat.get(i).get(j) + " ");
}
System.out.println();
}
}

// 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);

ArrayList<Integer> row2 = new ArrayList<Integer>();


row2.add(4);
row2.add(5);
row2.add(6);
arr.add(row2);

ArrayList<Integer> row3 = new ArrayList<Integer>();


row3.add(7);
row3.add(8);
row3.add(9);
arr.add(row3);
diagonalSort(arr);

}
}
Python:
# Python program for the above approach
from collections import defaultdict

def diagonalSort(matrix, n, m):

# make a dict of list, where we


# will store the diagonal elements
to = defaultdict(list)

# store the diagonal elements with


# respect to their row-col value
# remember every row-col value for
# each diagonal will be different
for row in range(n):
for col in range(m):
to[row-col].append(matrix[row][col])

# sort the elements of each


# diagonal as required
for i in to:
to[i].sort(reverse=True)

# store the new diagonal elements to


# their respective position in the matrix
for row in range(n):
for col in range(m):
matrix[row][col] = to[row-col].pop(0)

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)

for row in range(n):


for col in range(m):
print(matrix[row][col], end=' ')
print()
Time Complexity: O(N*M*log(min(N,M)))
Space Complexity: O(N*M)
Method 2 :
here in this method, we will do space optimization in the above method. here we traverse matrix
diagonal and store their values in the extra 1D array so for every diagonal we will need to store the
maximum min(n,m) element in our 1D array so this is space optimization in the above solution
Java:
// Java program to sort the 2D matrix
// diagonally in decreasing order
import java.io.*;
import java.util.*;

class GFG
{

// Function that sort 2D matrix Diagonally In Descending


// order
public static void
diagonalSort(ArrayList<ArrayList<Integer> > mat)
{

// Calculate the rows and column


int n = mat.size();
int m = mat.get(0).size();
// 1D array for extra space
ArrayList<Integer> v = new ArrayList<Integer>();

// start traversing from first row to nth row


// where first row to nth row is first member of
// diagonal
for (int row = 0; row < n; row++)
{

// take all diagonal element where first element


// is mat[row][0] means left column of matrix
for (int j = 0, i = row; j < m && i < n;
i++, j++) {
v.add(mat.get(i).get(j));
}

// sort element in reverse order because we need


// decreasing order in diagonal
Collections.sort(v, Collections.reverseOrder());
int t = 0;
for (int j = 0, i = row; j < m && i < n;
i++, j++) {
mat.get(i).set(j, v.get(t++));
}
v.clear();
}
// start traversing from second column to mth column
// where second column to mth column is first member
// of diagonal note that here we can't start from
// first column because it is already sorted by
// first row processing
for (int col = 1; col < m; col++)
{

// take all diagonal element where first element


// is mat[0][col] means first row of matrix
for (int j = col, i = 0; i < n && j < m;
i++, j++) {
v.add(mat.get(i).get(j));
}

// sort element in reverse order because we need


// decreasing order in diagonal
Collections.sort(v, Collections.reverseOrder());
int t = 0;

// putting this all values to matrix in


// descending sorted order
for (int j = col, i = 0; i < n && j < m;
i++, j++) {
mat.get(i).set(j, v.get(t++));
}
v.clear();
}

// Print diagonally sorted matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(mat.get(i).get(j) + " ");
}
System.out.println();
}
}

// 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);

ArrayList<Integer> row2 = new ArrayList<Integer>();


row2.add(4);
row2.add(5);
row2.add(6);
arr.add(row2);

ArrayList<Integer> row3 = new ArrayList<Integer>();


row3.add(7);
row3.add(8);
row3.add(9);
arr.add(row3);

diagonalSort(arr);
}
}
Python:
# Python program to sort the 2D vector diagonally in decreasing order

# Function that sort 2D matrix Diagonally In Descending order


def DiagonalSort(mat):
# Calculate the rows and column
n = len(mat)
m = len(mat[0])
# 1D array for extra space
v = []

# start traversing from first row to nth row


# where first row to nth row is first member of diagonal
for row in range(0, n):
j=0
i = row
# take all diagonal element where first element is
# mat[row][0] means left column of matrix
while(i < n and j < m):
v.append(mat[i][j])
i += 1
j += 1
# sort element in reverse order because we need
# decreasing order in diagonal
v.sort(reverse=True)
v[::-1]
t=0
j=0
i = row
# putting this all values to matrix in descending sorted order
while(i < n and j < m):
mat[i][j] = v[t]
t += 1
i += 1
j += 1
v = []
# start traversing from second column to mth column
# where second column to mth column is first member of diagonal
# note that here we can't start from first column
# because it is already sorted by first row processing
for col in range(0, m):
j = col
i=0
# take all diagonal element where first element is
# mat[0][col] means first row of matrix
while(i < n and j < m):
v.append(mat[i][j])
i += 1
j += 1
# sort element in reverse order because we need
# decreasing order in diagonal
v.sort(reverse=True)
v[::-1]
t=0
j = col
i=0
# putting this all values to matrix in descending sorted order
while(i < n and j < m):
mat[i][j] = v[t]
t += 1
i += 1
j += 1
v = []
return mat

# Function to print element


def printElement(arr):
n = len(arr)
m = len(arr[0])
# Traverse the 2D array
for i in range(0, n):
for j in range(0, m):
print(arr[i][j], end=" ")
print()

# 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.

Input: { {1, 2, 3, 4, 5, 6},


{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}}
Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
Explanation: The output is matrix in spiral format.
Print a given matrix in spiral form using the simulation approach:
To solve the problem follow the below idea:
Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would
go out of bounds or into a cell that was previously visited
Follow the given steps to solve the problem:
Let the array have R rows and C columns
seen[r] denotes that the cell on the r-th row and c-th column was previously visited. Our current
position is (r, c), facing direction di, and we want to visit R x C total cells.
As we move through the matrix, our candidate’s next position is (cr, cc).
If the candidate is in the bounds of the matrix and unseen, then it becomes our next position;
otherwise, our next position is the one after performing a clockwise turn
Java:
// Java program for the above approach
import java.util.*;
class Solution {

// Function to print in spiral order


public static List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> ans = new ArrayList<Integer>();

if (matrix.length == 0)
return ans;

int m = matrix.length, n = matrix[0].length;


boolean[][] seen = new boolean[m][n];
int[] dr = { 0, 1, 0, -1 };
int[] dc = { 1, 0, -1, 0 };
int x = 0, y = 0, di = 0;

// 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];

if (0 <= cr && cr < m && 0 <= cc && cc < n


&& !seen[cr][cc]) {
x = cr;
y = cc;
}
else {
di = (di + 1) % 4;
x += dr[di];
y += dc[di];
}
}
return ans;
}

// 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]

if (0 <= cr and cr < m and 0 <= cc and cc < n and not(seen[cr][cc])):


x = cr
y = cc
else:
di = (di + 1) % 4
x += dr[di]
y += dc[di]
return ans

# 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 {

// Function print matrix in spiral form


static void spiralPrint(int m, int n, int a[][])
{
int i, k = 0, l = 0;

/* k - starting row index


m - ending row index
l - starting column index
n - ending column index
i - iterator
*/

while (k < m && l < n) {


// Print the first row from the remaining rows
for (i = l; i < n; ++i) {
System.out.print(a[k][i] + " ");
}
k++;

// Print the last column from the remaining


// columns
for (i = k; i < m; ++i) {
System.out.print(a[i][n - 1] + " ");
}
n--;

// Print the last row from the remaining rows */


if (k < m) {
for (i = n - 1; i >= l; --i) {
System.out.print(a[m - 1][i] + " ");
}
m--;
}

// Print the first column from the remaining


// columns */
if (l < n) {
for (i = m - 1; i >= k; --i) {
System.out.print(a[i][l] + " ");
}
l++;
}
}
}

// 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

def spiralPrint(m, n, a):


k=0
l=0

''' k - starting row index


m - ending row index
l - starting column index
n - ending column index
i - iterator '''

while (k < m and l < n):

# Print the first row from


# the remaining rows
for i in range(l, n):
print(a[k][i], end=" ")

k += 1

# Print the last column from


# the remaining columns
for i in range(k, m):
print(a[i][n - 1], end=" ")

n -= 1

# Print the last row from


# the remaining rows
if (k < m):

for i in range(n - 1, (l - 1), -1):


print(a[m - 1][i], end=" ")

m -= 1

# Print the first column from


# the remaining columns
if (l < n):
for i in range(m - 1, k - 1, -1):
print(a[i][l], end=" ")

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;

// Function for printing matrix in spiral


// form i, j: Start index of matrix, row
// and column respectively m, n: End index
// of matrix row and column respectively
static void print(int arr[][], int i, int j, int m,
int n)
{
// If i or j lies outside the matrix
if (i >= m || j >= n) {
return;
}

// Print First Row


for (int p = i; p < n; p++) {
System.out.print(arr[i][p] + " ");
}

// Print Last Column


for (int p = i + 1; p < m; p++) {
System.out.print(arr[p][n - 1] + " ");
}

// Print Last Row, if Last and


// First Row are not same
if ((m - 1) != i) {
for (int p = n - 2; p >= j; p--) {
System.out.print(arr[m - 1][p] + " ");
}
}

// Print First Column, if Last and


// First Column are not same
if ((n - 1) != j) {
for (int p = m - 2; p > i; p--) {
System.out.print(arr[p][j] + " ");
}
}
print(arr, i + 1, j + 1, m - 1, n - 1);
}

// 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

# Function for printing matrix in spiral


# form i, j: Start index of matrix, row
# and column respectively m, n: End index
# of matrix row and column respectively

def printdata(arr, i, j, m, n):

# If i or j lies outside the matrix


if (i >= m or j >= n):
return

# Print First Row


for p in range(i, n):
print(arr[i][p], end=" ")
# Print Last Column
for p in range(i + 1, m):
print(arr[p][n - 1], end=" ")

# Print Last Row, if Last and


# First Row are not same
if ((m - 1) != i):
for p in range(n - 2, j - 1, -1):
print(arr[m - 1][p], end=" ")

# Print First Column, if Last and


# First Column are not same
if ((n - 1) != j):
for p in range(m - 2, i, -1):
print(arr[p][j], end=" ")

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;
}

// check if the position is blocked


public static boolean isBlocked(int[][] matrix, int i,
int j)
{
if (!isInBounds(i, j))
return true;
if (matrix[i][j] == -1)
return true;
return false;
}

// DFS code to traverse spirally


public static void
spirallyDFSTraverse(int[][] matrix, int i, int j,
int dir, ArrayList<Integer> res)
{
if (isBlocked(matrix, i, j))
return;
boolean allBlocked = true;
for (int k = -1; k <= 1; k += 2) {
allBlocked = allBlocked
&& isBlocked(matrix, k + i, j)
&& isBlocked(matrix, i, j + k);
}
res.add(matrix[i][j]);
matrix[i][j] = -1;
if (allBlocked) {
return;
}
// dir: 0 - right, 1 - down, 2 - left, 3 - up
int nxt_i = i;
int nxt_j = j;
int nxt_dir = dir;
if (dir == 0) {
if (!isBlocked(matrix, i, j + 1)) {
nxt_j++;
}
else {
nxt_dir = 1;
nxt_i++;
}
}
else if (dir == 1) {
if (!isBlocked(matrix, i + 1, j)) {
nxt_i++;
}
else {
nxt_dir = 2;
nxt_j--;
}
}
else if (dir == 2) {
if (!isBlocked(matrix, i, j - 1)) {
nxt_j--;
}
else {
nxt_dir = 3;
nxt_i--;
}
}
else if (dir == 3) {
if (!isBlocked(matrix, i - 1, j)) {
nxt_i--;
}
else {
nxt_dir = 0;
nxt_j++;
}
}
spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir,
res);
}

// 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

def isInBounds(i, j):


global R
global C
if (i < 0 or i >= R or j < 0 or j >= C):
return False
return True

# Check if the position is blocked

def isBlocked(matrix, i, j):


if (not isInBounds(i, j)):
return True
if (matrix[i][j] == -1):
return True

return False

# DFS code to traverse spirally


def spirallyDFSTraverse(matrix, i, j, Dir, res):
if (isBlocked(matrix, i, j)):
return

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

# dir: 0 - right, 1 - down, 2 - left, 3 - up


nxt_i = i
nxt_j = j
nxt_dir = Dir
if (Dir == 0):
if (not isBlocked(matrix, i, j + 1)):
nxt_j += 1
else:
nxt_dir = 1
nxt_i += 1

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

spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res)

# 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)

A Boolean Matrix Question


Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix
cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1.
Examples:
Input: {{1, 0},
{0, 0}}
Output: {{1, 1}
{1, 0}}
Input: {{0, 0, 0},
{0, 0, 1}}
Output: {{0, 0, 1},
{1, 1, 1}}

Input: {{1, 0, 0, 1},


{0, 0, 1, 0},
{0, 0, 0, 0}}
Output: {{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 0, 1, 1}}
A Boolean Matrix Question using Brute Force:
Approach: Using brute force
Assuming all the elements in the matrix are non-negative. Traverse through the
matrix and if you find an element with value 1, then change all the elements in its
row and column to -1, except when an element is 1. The reason for not changing
other elements to 1, but -1, is because that might affect other columns and rows.
Now traverse through the matrix again and if an element is -1 change it to 1, which
will be the answer.
Java:
import java.util.*;

class Main {

// Given an m x n matrix, if an element is 0, set its


// entire row and column to 0.
static void setZeroes(int[][] matrix)
{
int rows = matrix.length;
int cols = matrix[0].length;

// Iterate through each element of the matrix


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {

// If the element is 1, mark its


// corresponding row and column using -1
if (matrix[i][j] == 1) {

// Mark all elements in the same column


// as -1, except for other 1's
int ind = i - 1;
while (ind >= 0) {
if (matrix[ind][j] != 1) {
matrix[ind][j] = -1;
}
ind--;
}
ind = i + 1;
while (ind < rows) {
if (matrix[ind][j] != 1) {
matrix[ind][j] = -1;
}
ind++;
}

// Mark all elements in the same row as


// -1, except for other 1's
ind = j - 1;
while (ind >= 0) {
if (matrix[i][ind] != 1) {
matrix[i][ind] = -1;
}
ind--;
}
ind = j + 1;
while (ind < cols) {
if (matrix[i][ind] != 1) {
matrix[i][ind] = -1;
}
ind++;
}
}
}
}

// Iterate through the matrix again, setting all


// -1's to 0
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] < 0) {
matrix[i][j] = 1;
}
}
}
}

// Test the setZeroes function with a sample input


public static void main(String[] args)
{
int[][] arr = { { 1, 0, 2, 1 },
{ 3, 4, 5, 2 },
{ 0, 3, 0, 5 } };
setZeroes(arr);
System.out.println("The Final Matrix is:");
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();
}
}
}
Python:
# Python equivalent of above code

# define a function to set the zeroes in the matrix


def setZeroes(matrix):
# get the length of the matrix
rows = len(matrix)
cols = len(matrix[0])

# Iterate through each element of the matrix


for i in range(0, rows):
for j in range(0, cols):

# If the element is 1, mark its


# corresponding row and column using -1
if matrix[i][j] == 1:

# Mark all elements in the same column


# as -1, except for other 1's
ind = i - 1
while ind >= 0:
if matrix[ind][j] != 1:
matrix[ind][j] = -1
ind -= 1

ind = i + 1
while ind < rows:
if matrix[ind][j] != 1:
matrix[ind][j] = -1
ind += 1

# Mark all elements in the same row as


# -1, except for other 1's
ind = j - 1
while ind >= 0:
if matrix[i][ind] != 1:
matrix[i][ind] = -1
ind -= 1

ind = j + 1
while ind < cols:
if matrix[i][ind] != 1:
matrix[i][ind] = -1
ind += 1

# Iterate through the matrix again, setting all


# -1's to 0
for i in range(0, rows):
for j in range(0, cols):
if matrix[i][j] < 0:
matrix[i][j] = 1

# Test the setZeroes function with a sample input


if __name__ == "__main__":
arr = [[1, 0, 2, 1],
[3, 4, 5, 2],
[0, 3, 0, 5]]
setZeroes(arr)
print("The Final Matrix is:")
for i in range(len(arr)):
for j in range(len(arr[0])):
print(arr[i][j], end=" ")
print()
Another Approach:
Follow the steps below to solve the problem
 Create two temporary arrays row[M] and col[N]. Initialize all values of row[] and
col[] as 0.
 Traverse the input matrix mat[M][N]. If you see an entry mat[i][j] as true, then
mark row[i] and col[j] as true.
 Traverse the input matrix mat[M][N] again. For each entry mat[i][j], check the
values of row[i] and col[j]. If any of the two values (row[i] or col[j]) is true, then
mark mat[i][j] as true.
Java:
// Java Code For A Boolean Matrix Question
import java.io.*;

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;

/* Initialize all values of row[] as 0 */


for (i = 0; i < R; i++)
row[i] = 0;
/* Initialize all values of col[] as 0 */
for (i = 0; i < C; i++)
col[i] = 0;

/* Store the rows and columns to be marked as


1 in row[] and col[] arrays respectively */
for (i = 0; i < R; i++) {
for (j = 0; j < C; j++) {
if (mat[i][j] == 1) {
row[i] = 1;
col[j] = 1;
}
}
}

/* Modify the input matrix mat[] using the


above constructed row[] and col[] arrays */
for (i = 0; i < R; i++)
for (j = 0; j < C; j++)
if (row[i] == 1 || col[j] == 1)
mat[i][j] = 1;
}

/* A utility function to print a 2D matrix */


public static void printMatrix(int mat[][], int R,
int C)
{
int i, j;
for (i = 0; i < R; i++) {
for (j = 0; j < C; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
}

/* Driver program to test above functions */


public static void main(String[] args)
{
int mat[][] = {
{ 1, 0, 0, 1 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
};

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

# Initialize all values of row[] as 0


for i in range(0, R):
row[i] = 0
# Initialize all values of col[] as 0
for i in range(0, C):
col[i] = 0

# Store the rows and columns to be marked


# as 1 in row[] and col[] arrays respectively
for i in range(0, R):

for j in range(0, C):


if (mat[i][j] == 1):
row[i] = 1
col[j] = 1

# Modify the input matrix mat[] using the


# above constructed row[] and col[] arrays
for i in range(0, R):

for j in range(0, C):


if (row[i] == 1 or col[j] == 1):
mat[i][j] = 1

# A utility function to print a 2D matrix

def printMatrix(mat):
for i in range(0, R):

for j in range(0, C):


print(mat[i][j], end=" ")
print()
# Driver Code
mat = [[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]]

print("Input Matrix")
printMatrix(mat)

modifyMatrix(mat)

print("Matrix after modification")


printMatrix(mat)
A Boolean Matrix Question using O(1) Space:
Intuition: Instead of taking two dummy arrays we can use the first row and column
of the matrix for the same work. This will help to reduce the space complexity of the
problem. While traversing for the second time the first row and column will be
computed first, which will affect the values of further elements that’s why we
traversing in the reverse direction.
Approach: Instead of taking two separate dummy arrays, take the first row and
column of the matrix as the array for checking whether the particular column or row
has the value 1 or not.Since matrix[0][0] are overlapping.Therefore take separate
variable col0(say) to check if the 0th column has 1 or not and use matrix[0][0] to
check if the 0th row has 1 or not. Now traverse from the last element to the first
element and check if matrix[i][0]==1 || matrix[0][j]==1 and if true set matrix[i][j]=1,
else continue.
Java:
import java.io.*;
class GFG {
public static void modifyMatrix(int mat[][])
{
// variables to check if there are any 1
// in first row and column
boolean row_flag = false;
boolean col_flag = false;
// updating the first row and col if 1
// is encountered
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
if (i == 0 && mat[i][j] == 1)
row_flag = true;

if (j == 0 && mat[i][j] == 1)
col_flag = true;

if (mat[i][j] == 1) {

mat[0][j] = 1;
mat[i][0] = 1;
}
}
}

// Modify the input matrix mat[] using the


// first row and first column of Matrix mat
for (int i = 1; i < mat.length; i++)
for (int j = 1; j < mat[0].length; j++)
if (mat[0][j] == 1 || mat[i][0] == 1)
mat[i][j] = 1;

// modify first row if there was any 1


if (row_flag == true)
for (int i = 0; i < mat[0].length; i++)
mat[0][i] = 1;

// modify first col if there was any 1


if (col_flag == true)
for (int i = 0; i < mat.length; i++)
mat[i][0] = 1;
}

/* A utility function to print a 2D matrix */


public static void printMatrix(int mat[][])
{
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++)
System.out.print(mat[i][j] + " ");
System.out.println("");
}
}

// Driver function to test the above function


public static void main(String args[])
{
int mat[][] = { { 1, 0, 0, 1 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 } };

System.out.println("Input Matrix :");


printMatrix(mat);
modifyMatrix(mat);
System.out.println("Matrix After Modification :");
printMatrix(mat);
}
}
Python:
# Python3 Code For A Boolean Matrix Question
def modifyMatrix(mat):
# variables to check if there are any 1
# in first row and column
row_flag = False
col_flag = False

# updating the first row and col


# if 1 is encountered
for i in range(0, len(mat)):

for j in range(0, len(mat)):


if (i == 0 and mat[i][j] == 1):
row_flag = True

if (j == 0 and mat[i][j] == 1):


col_flag = True

if (mat[i][j] == 1):
mat[0][j] = 1
mat[i][0] = 1

# Modify the input matrix mat[] using the


# first row and first column of Matrix mat
for i in range(1, len(mat)):

for j in range(1, len(mat) + 1):


if (mat[0][j] == 1 or mat[i][0] == 1):
mat[i][j] = 1

# modify first row if there was any 1


if (row_flag == True):
for i in range(0, len(mat)):
mat[0][i] = 1
# modify first col if there was any 1
if (col_flag == True):
for i in range(0, len(mat)):
mat[i][0] = 1

# A utility function to print a 2D matrix

def printMatrix(mat):

for i in range(0, len(mat)):


for j in range(0, len(mat) + 1):
print(mat[i][j], end="")

print()

# Driver Code
mat = [[1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]]

print("Input Matrix :")


printMatrix(mat)

modifyMatrix(mat)

print("Matrix After Modification :")


printMatrix(mat)
Rotate a matrix by 90 degree without using
any extra space |
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without
using any extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Rotated the input matrix by
90 degrees in anti-clockwise direction.

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 {

// After transpose we swap elements of


// column one by one for finding left
// rotation of matrix by 90 degree
static void reverseColumns(int arr[][])
{
for (int i = 0; i < arr[0].length; i++)
for (int j = 0, k = arr[0].length - 1; j < k;
j++, k--) {
int temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}

// Function for do transpose of matrix


static void transpose(int arr[][])
{
for (int i = 0; i < arr.length; i++)
for (int j = i; j < arr[0].length; j++) {
int temp = arr[j][i];
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}

// 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("");
}
}

// Function to anticlockwise rotate


// matrix by 90 degree
static void rotate90(int arr[][])
{
transpose(arr);
reverseColumns(arr);
}

/* Driver program to test above function */


public static void main(String[] args)
{
int arr[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };

rotate90(arr);
printMatrix(arr);
}
}
Python:
# Python 3 program for left rotation of matrix by 90
# degree without using extra space

R=4
C=4

# After transpose we swap elements of column


# one by one for finding left rotation of matrix
# by 90 degree

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

# Function for do transpose of matrix


def transpose(arr):
for i in range(R):
for j in range(i, C):
t = arr[i][j]
arr[i][j] = arr[j][i]
arr[j][i] = t

# Function for print matrix

def printMatrix(arr):
for i in range(R):
for j in range(C):
print(str(arr[i][j]), end=" ")
print()

# Function to anticlockwise rotate matrix


# by 90 degree

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 {

// Function to rotate matrix anticlockwise by 90


// degrees.
static void rotateby90(int arr[][])
{
int n = arr.length;
int a = 0, b = 0, c = 0, d = 0;

// iterate over all the boundaries of the matrix


for (int i = 0; i <= n / 2 - 1; i++) {

// for each boundary, keep on taking 4 elements


// (one each along the 4 edges) and swap them in
// anticlockwise manner
for (int j = 0; j <= n - 2 * i - 2; j++) {
a = arr[i + j][i];
b = arr[n - 1 - i][i + j];
c = arr[n - 1 - i - j][n - 1 - i];
d = arr[i][n - 1 - i - j];

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("");
}
}

/* Driver program to test above function */


public static void main(String[] args)
{
int arr[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };

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

# iterate over all the boundaries of the matrix


for i in range(n // 2):

# for each boundary, keep on taking 4 elements


# (one each along the 4 edges) and swap them in
# anticlockwise manner
for j in range(n - 2 * i - 1):
a = arr[i + j][i]
b = arr[n - 1 - i][i + j]
c = arr[n - 1 - i - j][n - 1 - i]
d = arr[i][n - 1 - i - j]

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


def printMatrix(arr):

for i in range(len(arr)):
for j in range(len(arr[0])):
print(arr[i][j] ,end = " ")
print()

# Driver program to test above function


arr=[[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ]]
rotateby90(arr)
printMatrix(arr)
Let’s see a method of Python numpy that can be used to arrive at the particular
solution.
Python:
# Alternative implementation using numpy
import numpy

# Driven code
arr = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]

# Define flip algorithm (Note numpy.flip is a builtin f


# function for versions > v.1.12.0)

def flip(m, axis):


if not hasattr(m, 'ndim'):
m = asarray(m)
indexer = [slice(None)] * m.ndim
try:
indexer[axis] = slice(None, None, -1)
except IndexError:
raise ValueError("axis =% i is invalid for the % i-dimensional input array"
% (axis, m.ndim))
return m[tuple(indexer)]

# Transpose the matrix


trans = numpy.transpose(arr)

# Flip the matrix anti-clockwise (1 for clockwise)


flipmat = flip(trans, 0)

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}}

Output: Found at (2, 1)


Explanation: Element at (2,1) is 29
Input : mat[4][4] = { {10, 20, 30, 40}, x = 100
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};

Output: Element not found


Explanation: Element 100 does not exist in the matrix
Naive approach: To solve the problem follow the below idea:
The simple idea is to traverse the array and search elements one by one
Follow the given steps to solve the problem:
 Run a nested loop, outer loop for the row, and inner loop for the column
 Check every element with x and if the element is found then print “element
found”
 If the element is not found, then print “element not found”
Java:
// Java program to search an element in row-wise
// and column-wise sorted matrix

class GFG {
static int search(int[][] mat, int n, int x)
{
if (n == 0)
return -1;

// traverse through the matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
// if the element is found
if (mat[i][j] == x) {
System.out.print("Element found at ("
+ i + ", " + j
+ ")\n");
return 1;
}
}

System.out.print(" Element not found");


return 0;
}

// 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

# Searches the element x in mat[][]. If the


# element is found, then prints its position
# and returns true, otherwise prints "not found"
# and returns false

def search(mat, n, x):


if(n == 0):
return -1

# Traverse through the matrix


for i in range(n):
for j in range(n):

# If the element is found


if(mat[i][j] == x):
print("Element found at (", i, ",", j, ")")
return 1

print(" Element not found")


return 0
# 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)
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 {

/* Searches the element x in mat[][]. If the


element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
private static void search(int[][] mat, int n, int x)
{

// set indexes for top right


int i = 0, j = n - 1;
// element

while (i < n && j >= 0) {


if (mat[i][j] == x) {
System.out.print("Element found at " + i
+ " " + j);
return;
}
if (mat[i][j] > x)
j--;
else // if mat[i][j] < x
i++;
}

System.out.print("n Element not found");


return; // if ( i==n || j== -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:
# Python3 program to search an element
# in row-wise and column-wise sorted matrix

# Searches the element x in mat[][]. If the


# element is found, then prints its position
# and returns true, otherwise prints "not found"
# and returns false

def search(mat, n, x):

i=0

# set indexes for top right element


j=n-1
while (i < n and j >= 0):

if (mat[i][j] == x):

print("Element found at ", i, ", ", j)


return 1

if (mat[i][j] > x):


j -= 1

# if mat[i][j] < x
else:
i += 1

print("Element not found")


return 0 # if (i == n || j == -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";
}

public static void main(String[] args) {


List<List<Integer>> mat = new ArrayList<>();
mat.add(List.of(10, 20, 30, 40));
mat.add(List.of(15, 25, 35, 45));
mat.add(List.of(27, 29, 37, 48));
mat.add(List.of(32, 33, 39, 50));

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

Find the row with maximum number of 1s


Given a boolean 2D array, where each row is sorted. Find the row with the
maximum number of 1s.
Example:
Input matrix : 0 1 1 1
0011
1 1 1 1 // this row has maximum 1s
0000
Output: 2
A simple method is to do a row-wise traversal of the matrix, count the number of 1s
in each row, and compare the count with the max. Finally, return the index of the
row with a maximum of 1s. The time complexity of this method is O(m*n) where m
is the number of rows and n is the number of columns in the matrix.
Java:
// 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;

// Check if the element at middle index is first 1


if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
return mid;

// If the element is 0, recur for right side


else if (arr[mid] == 0)
return first(arr, (mid + 1), high);

// If element is not first 1, recur for left side


else
return first(arr, low, (mid -1));
}
return -1;
}

// Function that returns index of row


// with maximum number of 1s.
static int rowWithMax1s(int mat[][])
{
// Initialize max values
int max_row_index = 0, max = -1;

// Traverse for each row and count number of 1s


// by finding the index of first 1
int i, index;
for (i = 0; i < R; i++)
{
index = first (mat[i], 0, C-1);
if (index != -1 && C-index > max)
{
max = C - index;
max_row_index = i;
}
}

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.print("Index of row with maximum 1s is " + rowWithMax1s(mat));

}
}
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;

// Check if the element at middle index is first 1


if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
return mid;

// If the element is 0, recur for right side


else if (arr[mid] == 0)
return first(arr, (mid + 1), high);

// If element is not first 1, recur for left side


else
return first(arr, low, (mid -1));
}
return -1;
}

// Function that returns index of row


// with maximum number of 1s.
static int rowWithMax1s(int mat[][])
{
// Initialize max values
int max_row_index = 0, max = -1;
// Traverse for each row and count number of 1s
// by finding the index of first 1
int i, index;
for (i = 0; i < R; i++)
{
index = first (mat[i], 0, C-1);
if (index != -1 && C-index > max)
{
max = C - index;
max_row_index = i;
}
}

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.print("Index of row with maximum 1s is " + rowWithMax1s(mat));

}
}
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):

if(high >= low):

# Get the middle index


mid = low + (high - low)//2

# Check if the element at middle index is first 1


if ( ( mid == 0 or arr[mid-1] == 0) and arr[mid] == 1):
return mid

# If the element is 0, recur for right side


elif (arr[mid] == 0):
return first(arr, (mid + 1), high);

# If element is not first 1, recur for left side


else:
return first(arr, low, (mid -1));

return -1

# Function that returns index of row


# with maximum number of 1s.
def rowWithMax1s(mat):

# Initialize max values


max_row_index,Max = 0,-1

# Traverse for each row and count number of 1s


# by finding the index of first 1
for i in range(R):

index = first (mat[i], 0, C-1)


if (index != -1 and C-index > Max):
Max = C - index;
max_row_index = i

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;

// If the element is 0, recur for right side


else if (arr[mid] == 0)
return first(arr, (mid + 1), high);

// If element is not first 1, recur for left side


else
return first(arr, low, (mid - 1));
}
return -1;
}

// Function that returns index of row


// with maximum number of 1s.
static int rowWithMax1s(int mat[][])
{
// Initialize max values
int max_row_index = 0, max = -1;

// Traverse for each row and count number of


// 1s by finding the index of first 1
int i, index;
for (i = 0; i < R; i++) {
index = first(mat[i], 0, C - 1);
if (index != -1 && C - index > max) {
max = C - index;
max_row_index = i;
}
}

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

# Function to find the index


# of first index of 1 in a
# boolean array arr[]

def first(arr, low, high):


if high >= low:

# Get the middle index


mid = low + (high - low)//2

# Check if the element at


# middle index is first 1
if (mid == 0 or arr[mid - 1] == 0) and arr[mid] == 1:
return mid

# If the element is 0,
# recur for right side
elif arr[mid] == 0:
return first(arr, (mid + 1), high)

# If element is not first 1,


# recur for left side
else:
return first(arr, low, (mid - 1))
return -1

# Function that returns


# index of row with maximum
# number of 1s.

def rowWithMax1s(mat):

# Initialize max values


R = len(mat)
C = len(mat[0])
max_row_index = 0
max = -1

# Traverse for each row and


# count number of 1s by finding
# the index of first 1
for i in range(0, R):
index = first(mat[i], 0, C - 1)
if index != -1 and C - index > max:
max = C - index
max_row_index = i

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;

// Initialize max using values from first row.


int max_row_index = 0;
int max = first(mat[0], 0, C - 1);

// Traverse for each row and count number of 1s


// by finding the index of first 1
for (i = 1; i < R; i++)
{

// Count 1s in this row only if this row


// has more 1s than max so far

// Count 1s in this row only if this row


// has more 1s than max so far
if (max != -1 && mat[i][C - max - 1] == 1)
{
// Note the optimization here also
index = first (mat[i], 0, C - max);

if (index != -1 && C - index > max)


{
max = C - index;
max_row_index = i;
}
}
else
{
max = first(mat[i], 0, C - 1);
}
}
return max_row_index;
}
}
Python:
# The main function that returns index
# of row with maximum number of 1s.
def rowWithMax1s(mat):

# Initialize max using values from first row.


max_row_index = 0
max = first(mat[0], 0, C - 1)

# Traverse for each row and count number of 1s


# by finding the index of first 1
for i in range(1, R):

# Count 1s in this row only if this row


# has more 1s than max so far

# Count 1s in this row only if this row


# has more 1s than max so far
if (max != -1 and mat[i][C - max - 1] == 1):

# Note the optimization here also


index = first(mat[i], 0, C - max)

if (index != -1 and C - index > max):


max = C - index
max_row_index = i
else:
max = first(mat[i], 0, C - 1)

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;

for (int i = 0; i < R; i++) {


// Move left until a 0 is found
while (j >= 0 && mat[i][j] == 1) {
j = j - 1; // Update the index of leftmost 1
// seen so far
max_row_index = i; // Update max_row_index
}
}
if(max_row_index==0&&mat[0][C-1]==0)
return -1;
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:
// 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;

for (int i = 0; i < R; i++) {


// Move left until a 0 is found
while (j >= 0 && mat[i][j] == 1) {
j = j - 1; // Update the index of leftmost 1
// seen so far
max_row_index = i; // Update max_row_index
}
}
if(max_row_index==0&&mat[0][C-1]==0)
return -1;
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

# Function that returns


# index of row with maximum
# number of 1s.

def rowWithMax1s(mat):

# Initialize max values


R = len(mat)
C = len(mat[0])
max_row_index = 0
index = C-1
# Traverse for each row and
# count number of 1s by finding
# the index of first 1
for i in range(0, R):
flag = False # to check whether a row has more 1's than previous
while(index >= 0 and mat[i][index] == 1):
flag = True # present row has more 1's than previous
index -= 1
if(flag): # if the present row has more 1's than previous
max_row_index = i
if max_row_index == 0 and mat[0][C-1] == 0:
return 0
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))

Find the area of the shaded region formed


by the intersection of four semicircles in a
square
Given the length of the side of a square a, the task is to find the area of the shaded
region formed by the intersection of four semicircles in a square as shown in the
image below:
Examples:

Input: a = 10
Output: 57
Input: a = 19
Output: 205.77
Approach: Area of the shaded region will be:

Area(semicircle1) + Area(semicircle2) + Area(semicircle3) + Area(semicircle4) –


Area(square).
Since all semicircles are of same radius, therefore, area of all semicircles will be
equal. So, the above formula can be written as:
4*(Area of Semicircle) – Area(Square)

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

Below is the implementation of the above approach:


Java:
// Java implementation of the approach
class GFG {

// Function to return the area


// of the shaded region
static float findAreaShaded(float a)
{
// Area of the square
float sqArea = a * a;

// Area of the semicircle


float semiCircleArea = (float)(3.14 * (a * a) / 8);

// There are 4 semicircles


// shadedArea = Area of 4 semicircles - Area of square
float ShadedArea = 4 * semiCircleArea - sqArea;

return ShadedArea;
}

// Driver code
public static void main(String[] args)
{
float a = 10;
System.out.println(findAreaShaded(a));
}
}
Python:
# Python3 implementation of the approach

# Function to return the area


# of the shaded region
def findAreaShaded(a):

# Area of the square


sqArea = a * a;

# Area of the semicircle


semiCircleArea = (3.14 * (a * a ) / 8)

# There are 4 semicircles


# shadedArea = Area of 4 semicircles - Area of square
ShadedArea = 4 * semiCircleArea - sqArea ;

return ShadedArea;

# Driver code
if __name__ == '__main__':
a = 10
print(findAreaShaded(a))

Area of the Shaded Region – Explanation &


Examples
Area of shaded region = area of outer shape – area of the unshaded inner shape

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

Area of a triangle = ½ bh.


Area of outer shape = (½ x 15 x 10) cm2.

= 75 cm2.

Area of unshaded inner shape = (½ x 12 x 5) cm2.

= 30 cm2.

Area of shaded region = (75 – 30) cm2.

= 45 cm2.

Therefore, the area of the shaded region is 45 cm2.

Example 2

Given AB = 6 m, BD = 8 m, and EC = 3 m, calculate the area of the shaded region in the


diagram below.

Solution

Considering similar triangles,

AB/EC = BD/CD

6/3 = 8/CD

Cross multiply.

6 CD = 3 x 8 = 24

Divide both sides by 6.


CD = 4 m.

Now calculate the area of triangle ABD and triangle ECD

Area of triangle ABD = (½ x 6 x 8) m2

= 24 m2

Area of triangle = (½ x 3 x 4) m2

= 6 m2

Area of the shaded region = (24 – 6) m2

= 18 m2

How to find the area of a shaded region in a rectangle?

Let’s see a few examples below to understand how to find the area of the shaded region in a
rectangle.

Example 3

Calculate the area of the shaded region of the rectangle below if

Solution

Area of shaded region = area of outer shape – area of unshaded inner shape

= (10 x 20) m2 – (18 x 8) m2


= 200 m2 – 144 m2.

= 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.

Area of rectangle ACDF= (120 x 40) cm2

= 4,800 cm2.

Area of triangle BFE = ½ x CD x FE

But FE = (120 – 20) cm

= 100 cm

Area = (½ x 40 x 20) cm2.

= 400 cm2.

Area of the shaded region = 4,800 cm2 – 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.

Area of the shaded region = area of part A + area of part B

= 6(13 – 4) cm2 – (24 x 4) cm2

= 54 cm2 + 96 cm2

= 150 cm2.

So, the area of the shaded region is 150 cm2

How to find the area of a shaded region in a square?

Let’s see a few examples below to understand how to find the area of a shaded region in a
square.

Example 6

Calculate the area of the shaded region in the diagram below.


Solution

Area of the shaded region = area of the square – area of the four unshaded small squares.

The side length of the square = (4 + 4 + 4) cm

= 12 cm.

The side length of the four unshaded small squares is 4 cm each.

Area of the shaded region = (12 x 12) cm2 – 4(4 x 4) cm2

= 144 cm2 – 64 cm2

= 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

Area of the square = (15 x 15) cm2

= 225 cm2

Area of the hexagon

A = (L2n)/[4tan(180/n)]

A = (62 6)/ [4tan (180/6)]

= (36 * 6)/ [4tan (180/6)]

= 216/ [4tan (180/6)]

= 216/ 2.3094

A = 93.53 cm2

Area of the shaded region = (225 – 93.53) cm2.

= 131.47 cm2

How to Find the Area of a Shaded Region


Under a Curve : Math Problems &
Trigonometry
Please refer this video
https://www.youtube.com/watch?v=BIzAbnG2qOw

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy