š Day-7 Striverās SDE Sheet | Arrays Part 3 | Search in a 2 D matrix , Pow(x, n)

Table of contents

Note : Started my 27-day DSA journey with Striverās SDE Sheet!
I will be journaling every day ā recording what I learn, reflecting on it, and sharing it with my network to help fellow learners and aspiring developers.. Learning through videos, resources, and the internet ā simplifying logic in my own way with real-world connections. Sharing 2 questions daily: brute-force to optimal, clean Java code, time & space complexity, and key patterns.
This blog series is for anyone preparing for coding interviews ā whether youāre a beginner or a revision warrior. Letās grow together! š
Namaste Developers! š
Welcome to Day 7 of my 27-day DSA journey using Striverās SDE Sheet!
1ļøā£Search in a sorted 2D matrix
šø Problem Statement:
You are given an m x n
integer matrix matrix
with the following two properties:
Each row is sorted in non-decreasing order.
The first integer of each row is greater than the last integer of the previous row.
Given an integer target
, return true
if target
is in matrix
or false
otherwise.
You must write a solution in O(log(m * n))
time complexity.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-10<sup>4</sup> <= matrix[i][j], target <= 10<sup>4</sup>
š Real-World Example
Imagine a library with shelves (rows).
Each shelf has books sorted in increasing order (like a row).
Also, the first book on the second shelf is thicker than the last book on the first shelf š
So the entire library, though in 2D shelves, behaves like a 1D sorted list of books.
We need to find a specific book thickness ā can we do it without checking each one?
Yes! We can use Binary Search.
(Hinglish : Another Example - Socho tumhare paas ek register hai jisme roll numbers likhe hain.
Har page pe numbers sorted hain.
Naye page ka pehla number pichle page ke last number se bada hai.
Ab agar kisi ka roll number dhundhna hai, toh:
Tum ek-ek page aur number dekh ke dhoond sakte ho ( Brute Force)
Ya phir ek smart strategy laga sakte ho ( Binary Search), jaise ek librarian fast search karta hai using index. )
1. Brute Force Approach (Simple & Straightforward)
šApproach:
We check each element one by one ā like manually flipping every page of a dictionary to find a word. Tedious, right?
(Hinglish :
Har element ko line by line check karo.
Jaise roll number register mein manually dhoondhna.)
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[0].length; j++) {
if(matrix[i][j] == target) {
return true;
}
}
}
return false;
}
}
š Time Complexity:
O(m * n)
ā m = number of rows
ā n = number of columns
š Space Complexity:
O(1)
(No extra space)
2. Optimal Approach (Binary Search in 2D as 1D)
šKey Insight:
Matrix actually behaves like a sorted 1D array.
We can perform binary search by mapping:
mid index ā (row = mid / n, col = mid % n)
šSmart Trick:
Treat the matrix as if itās flattened into a sorted array.
Use classic binary search strategy.
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length; // total rows
int n = matrix[0].length; //tpta; columns
int left = 0;
int right = m * n - 1; //treat matrix as 1D array
while (left <= right) {
int mid = (left + right) / 2;
int row = mid / n; //find actua row in matrix
int col = mid % n; //find actual column in matrix
int midValue = matrix[row][col];
if(midValue == target) {
return true; //target mil gaya
} else if(midValue < target) {
left = mid + 1; //search right half
} else {
right = mid - 1; //serach left half
}
}
return false; //target nahi mila
}
}
š Time Complexity:
O(log(m * n))
ā
ā because weāre performing binary search on totalm * n
elements
š Space Complexity:
O(1)
(No extra space)
šKey Takeaways:
ā
Understand the matrix property ā rows are sorted, and each row starts bigger than previous ends.
ā
Map 1D index to 2D to apply binary search smartly.
ā
Practicing this builds strong foundation in search algorithms & matrix manipulation.
2ļøā£Implement Pow(x,n) | X raised to the power N
šø Problem Statement:
Implement pow(x, n), which calculates x
raised to the power n
(i.e., x<sup>n</sup>
).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0
-2<sup>31</sup> <= n <= 2<sup>31</sup>-1
n
is an integer.Either
x
is not zero orn > 0
.-10<sup>4</sup> <= x<sup>n</sup> <= 10<sup>4</sup>
š Real-World Example
Imagine youāre doubling your savings every year (compound interest style ).
Year 1: ā¹100
Year 2: ā¹200
Year 3: ā¹400
...
By Year 10: ā¹1024
Thatās 2 raised to power 10 ā or pow(2, 10)
.
But what if we have to calculate it for large powers or for negative exponents like interest deduction?
This is where efficiency comes into play!
(Hinglish : Socho tumne saving kari hai per year
Har din wo double hota hai:
Year 1 ā ā¹100
Year 2 ā ā¹200
Year 3 ā ā¹400
...
Year 10 ā ā¹1024
Yeh exactly pow(2, 10)
hai.
Agar same rupees har year aadha ho jaaye due to drought, then it becomes pow(2, -2) = 0.25
.
Toh ab samajh aaya, power positive bhi ho sakta hai aur negative bhi. We need to handle both efficiently!
Brute Force Approach
šLogic : Multiply
x
with itselfn
times.(Hinglish :
Bas ek loop chalao
n
times, har baarresult *= x
karo.Negative power ho toh finally
1 / result
return karo.)
class Solution {
public double myPow(double x, int n) {
double result = 1.0;
long power = n;
if (power < 0) {
power = -power;
}
for (int i = 0; i < power; i++) {
result *= x;
}
return (n < 0) ? 1.0 / result : result;
}
}
š Time Complexity:
O(n)
šProblem:
Too slow when n
is large (like 2³¹). May cause Time Limit Exceeded (TLE).
(Hinglish : TLE (Time Limit Exceeded) ho sakta hai ā especially when n
is huge.)
Optimal Approach-Fast Power Using Binary Exponentiation
š Concept:
Instead of multiplying
x
n
times, letās do it smartly!- It uses:
āx^n = (x^2)^{n/2}
(when n is even)
āx^n = x * (x^2)^{n/2}
(when n is odd)
- It uses:
This actually reflects the optimized recursive/iterative logic.
This reduces steps from
n
ālog n
class Solution {
public double myPow(double x, int n) {
long power = n;
if (power < 0) {
x = 1 / x; //negative power ka handle
power = -power;
}
double result = 1.0;
while(power > 0) {
if(power % 2 == 1) {
result *= x; //odd power
}
x *= x; //square the base
power /= 2; //divide power by 2
}
return result;
}
}
š Time Complexity: : O(log n)
ā
Why?
Each time we divide the power
n
by 2 ā this is a classic Binary Exponentiation or Exponentiation by Squaring technique.This reduces the number of steps drastically (just like in binary search).
So, the loop runs approximately logā(n) times.
Example:
Forn = 16
, number of operations ālogā(16)
= 4 steps only.
š Space Complexity:: O(1)
ā
Why?
No recursion stack.
We use only a fixed number of variables (
result
,x
,power
) regardless of input size.So, the space used is constant.
Input: x = 2.0, n = 10
Initial:
result = 1.0, power = 10, x = 2.0
Step 1: power even ā x = x*x = 4, power = 5
Step 2: power odd ā result = result * 4 = 4, x = 16, power = 2
Step 3: power even ā x = 256, power = 1
Step 4: power odd ā result = result * 256 = 1024, power = 0
Final Result: 1024.0 ā
(Hinglish : "Maan lo tumhare paas ek number hai
x = 2
aur tumhe uska 10th power chahiye. Ab 2 ko 10 baar multiply karne ki jagah, hum shortcut lete hain!"
Just like how we donāt count steps one by one when climbing stairs ā instead, we take double steps ā similarly, here we square the base and reduce the power. Thatās exponentiation by squaring! )
šImportant Points :-
ā
If n
is negative ā convert x
to 1/x
and n
to -n
ā
Binary Exponentiation = super fast, time O(log n)
ā
Overflow se bachne ke liye use long
instead of int
ā
pow(x, n)
ek basic yet super frequently asked DSA concept hai ā must know for interviews.
āļø Final Notes:
If you're just starting your DSA journey like me, don't worry if you donāt get it perfect the first time.
Visualize ā Dry Run ā Optimize.
Stay consistent, and letās crack every problem from brute to optimal! šŖ
š Special Thanks
A heartfelt thank you to Rajvikraaditya Sir for creating and sharing such an incredible DSA resource with the community (takeuforward). Your structured approach has made DSA more accessible and less intimidating for thousands of learners like me.
If this helped you, do share it with your fellow DSA learners.
Comment with your doubts ā Iād love to answer and grow together š±
āļø Payal Kumari š©āš»
My 27-Day DSA Journey with Striverās Sheet! #dsawithpayal
%[INVALID_URL]
Subscribe to my newsletter
Read articles from Payal Kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Kumari
Payal Kumari
I'm a passionate full-stack developer with a strong foundation in the MERN stackābuilding and maintaining scalable web applications using React.js, Node.js, and Next.js. My journey in open source began with Hacktoberfest 2023, where I made four impactful pull requests that sparked a love for collaborative coding, global learning, and open knowledge sharing. Since then, Iāve contributed to and mentored projects in top open source programs like GSSoCā24, SSOCā24, and C4GTā24. As a Google Gen AI Exchange Hackathon ā24 Finalist and Googleās Women Techmakers (WTM) Ambassador, Iāve been privileged to support diverse communities in building meaningful tech solutions. My work as a Top 50 Mentor for GSSoC ā24 reflects my commitment to nurturing new talent in tech. Beyond development, I serve as a Student Career Guide, Profile Building Expert & Evangelist at Topmate.io, where I conduct workshops, guide students through resume building and career strategy, and help mentees navigate open source and tech careers. Recognized among the Top 5% of mentors and featured on āTopmate Discover,ā I take pride in making mentorship accessible and impactful. My technical voice has also been acknowledged by LinkedIn, where Iāve earned the Top Voice badge seven times in domains like web development, programming, and software engineering. In addition, I hold LinkedIn Golden Badges for Research Skills, Interpersonal Skills, Critical Thinking, and Teamworkāsignaling a well-rounded approach to both individual contribution and team collaboration. Graduating with an MCA from Chandigarh University in 2023, Iāve continued to fuel my curiosity by writing technical articles and sharing practical MERN stack insights across platforms. Whether itās building polished UIs, optimizing backend performance, or guiding a mentee through their first pull request, Iām driven by the power of community and continuous learning. Letās connect! I'm open to collaborations, mentorship, or building something impactful together. Reach out to me at kumaripayal7488@gmail.com or visit my profile on Topmate.io.