š Day 2 - Striverās SDE Sheet | Arrays Part 1 | Q3 & Q4: Next Permutation & Kadane's Algorithm

Table of contents
- Namaste Developers! š
- š What is a Permutation?
- š What is "Next" Permutation?
- š Real-Life Example for Intuition
- šExample:
- š Problem Statement
- š Brute Force Approach (Not Recommended)
- š Optimal Approach (In-place and Efficient)
- šHighlights & Tips :
- š What is Kadaneās Algorithm?
- š Kadaneās Ka Sochne Ka Tareeka:
- š¢Kadane's Algorithm : Maximum Subarray Sum in an Array
- š Real-Life Example
- š Brute Force Approach
- š Time Complexity: O(n²)
- š Space Complexity: O(1)
- š Optimal Approach
- š Time Complexity: O(n)
- š Space Complexity: O(1)
- šConcept behind Kadane's Algorithm
- āļø Final Notes:

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 2 of my 27-day DSA journey using Striverās SDE Sheet!
š What is a Permutation?
In simple words,
A permutation of an array is an arrangement or reordering of its elements.
Real-Life Example: Socho ek box mein 3 different color ke balls hain: Red , Blue , Green .
Agar tum inka har possible sequence banana chahte ho toh:
[Red, Blue, Green]
[Red, Green, Blue]
[Green, Red, Blue]
... and so on!
Ye sab hi permutations hain.
š What is "Next" Permutation?
Ab maan lo tumhare paas ek permutation already hai ā for example: [1, 2, 3]
Toh iska next permutation hoga lexicographically (dictionary-like order) next arrangement i.e. [1, 3, 2]
Lexicographical means: jaisa tum words ko dictionary mein arrange karte ho ā waise hi numbers bhi arrange hote hain.
š Real-Life Example for Intuition
Imagine tum password try kar rahe ho on a locker: 1ļøā£2ļøā£3ļøā£
You want to try the next possible guess ā tum chahte ho ki pehle se thoda aage wala pattern mile automatically.
Thatās what "Next Permutation" helps with!
šExample:
Input: [1,2,3]
Next Permutation: [1,3,2]
Input: [3,2,1]
Next Permutation: [1,2,3]
(Because this is the last permutation, we rotate it to the smallest one)
Input: [1,1,5]
Next Permutation: [1,5,1]
š Problem Statement
š¢Next Permutation : A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
- For example, for
arr = [1,2,3]
, the following are all the permutations ofarr
:[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]
.
The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
For example, the next permutation of
arr = [1,2,3]
is[1,3,2]
.Similarly, the next permutation of
arr = [2,3,1]
is[3,1,2]
.While the next permutation of
arr = [3,2,1]
is[1,2,3]
because[3,2,1]
does not have a lexicographical larger rearrangement.
Given an array of integers nums
, find the next permutation of nums
.
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
š Brute Force Approach (Not Recommended)
Generate all permutations of the array.
Sort them.
Find the next one after the current.
Problem: Time complexity is too high (O(N!)) and not efficient at all.
š Optimal Approach (In-place and Efficient)
We follow 3ļøā£ steps:
Step 1: Find the Break Point
Traverse from right to left.
Find the first number that is smaller than its next number.
Call it index
i
.
Why? Ye index batata hai jahan se hum permutation ko modify karna start karenge.
Example: In [1, 3, 5, 4, 2], break point is at index 1 (value = 3)
Step 2: Find the Just Greater Element
Again, move from right to left and find the first number that is bigger than
nums[i]
Letās call its index
j
Swap
nums[i]
andnums[j]
So now we get a slightly bigger number.
Step 3: Reverse the Right Part
Reverse the part of array from index
i+1
to end.This gives the next lexicographically smallest arrangement.
class Solution {
public void nextPermutation(int[] nums) {
int n = nums.length;
int i = n - 2;
// Step 1: Find first decreasing element from end
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
// Step 2: If found, find next greater element and swap
if (i >= 0) {
int j = n - 1;
while (nums[j] <= nums[i]) {
j--;
}
// swap
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
// Step 3: Reverse the remaining array
reverse(nums, i + 1, n - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start++] = nums[end];
nums[end--] = temp;
}
}
}
Time & Space Complexity
Complexity | Value |
Time | O(N) |
Space | O(1) (In-place) |
šHighlights & Tips :
Ye pattern DSA interviews mein kaafi baar poocha ja chuka hai (Top companies like Google, Amazon, etc.)
Focus karo "breakpoint" dhoondhne par ā wahi sabse important step hai!
Don't forget to reverse the right half after swap.
Jab array already in decreasing order ho, next permutation hoti hai sorted (ascending) form.
š What is Kadaneās Algorithm?
Kadaneās algorithm continuously tracks the best possible sum of a subarray ending at each index, and resets it when the running sum becomes negative.
Kadaneās Algorithm ek efficient way hai maximum subarray sum nikalne ka ā matlab continuous elements ka woh group jinka sum sabse zyada ho.
Kadaneās says:
"Agar tumhare paas ek achha sum chal raha hai, toh usme naye element ko jodte jao. Agar woh sum negative ho jaye, toh usko chhodo aur naya start karo."
šReal Life Analogy:
Socho tum ek marathon bhaag rahe ho (continuous subarray), aur kabhi kabhi thak jaate ho (negative sum).
Kadane's kehta hai:
"Jab tak energy positive hai, bhaag te raho. Jaise hi energy negative ho gayi, reset karo aur fresh start lo!"
š Kadaneās Ka Sochne Ka Tareeka:
currentSum
rakho ā jo tum abhi tak ka sum calculate kar rahe ho.maxSum
rakho ā ab tak mila sabse bada sum.
Every step pe decide karo:
"Kya mujhe naye number se fresh start karna chahiye? Ya previous subarray ko continue karna chahiye?"
š¢Kadane's Algorithm : Maximum Subarray Sum in an Array
Given an integer array nums
, find the subarray with the largest sum, and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Constraints:
1 <= nums.length <= 10<sup>5</sup>
-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>
Follow up: If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
š Real-Life Example
Socho tumhare paas ek graph ho jo daily profit/damage dikhata hai ā kabhi profit ho raha hai kabhi nuksan. Tumhe dekhna hai ki kaunsa period (subarray) sabse zyada profitable tha. Bas wahi hai yeh Maximum Subarray problem!
š Brute Force Approach
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
int currentSum = 0;
for (int j = i; j < n; j++) {
currentSum += nums[j];
maxSum = Math.max(maxSum, currentSum);
}
}
return maxSum;
}
}
āYeh code TLE dega jab input bada hoga (10āµ elements), kyunki:
Har index se har possible subarray check karta hai.
Time Complexity: O(n²)
š Time Complexity: O(n²)
Outer loop runs n times.
Inner loop runs n-i times.
Total iterations ā n + (n-1) + (n-2) + ... + 1 = n(n+1)/2 ā O(n²)
Example: Agar array size 10āµ hai, toh 10āµ Ć 10āµ = 10¹Ⱐoperations ā ā TLE in interview/code test
š Space Complexity: O(1)
- No extra space used except some variables (maxSum, currentSum)
š Real-life analogy:
Imagine checking happiness of every day-to-every-day combo in a year ā 365 Ć 365 = 1,33,225 combinations! Thak jaoge!
š Optimal Approach
Kadane's Algorithm is based on a simple idea:
Either continue the previous subarray or start a new one.
class Solution {
public int maxSubArray(int[] nums) {
int currentSum = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
š Time Complexity: O(n)
Ek hi baar array traverse kar rahe ho
No nested loop
š Space Complexity: O(1)
- Sirf 2 variables: currentSum and maxSum
šReal-life analogy:
Jaise tum har din ka mood dekh ke turant decide karo ā continue karna ya new streak start karna. Simple & fast!
šConcept behind Kadane's Algorithm
Har element pe do choice hoti hai:
Khud se start karu? (nums[i])
Pichle wale ke sath jod lu? (currentSum + nums[i])
Jo bhi zyada hoga, wahi current subarray banega.
Soch lo daily ka mood tracker hai, jahan kuch din kharab ja rahe the, aur achanak ek achha din aaya. Tab tum decide karte ho ki naye tareeke se shuru karte hain ya pichle dino ke effort ko continue karte hain. šŖ
āļø 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 š©āš»
Officially ready to start my 27-Day DSA Journey with Striverās Sheet! #dsawithpayal
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.