Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
The Problem:
Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.
Return the shortest such subarray and output its length.
Example 1:
Example 2:
Example 3:
Let me walk you through how I approached this problem and refined my solution!
Step 1: Initial Observations
First, I noticed that:
But how? 🤔
Step 2: First Attempt - Find Where Order Breaks
I thought:
Example:
Step 3: The Hidden Problem
Initial boundaries: [5, 4, 2] (indices 2 to 4)
But sorting just this gives [1,3,2,4,5,6,7] → still unsorted!
Why?
Step 4: Fixing the Approach
Example:
Step 5: Final Algorithm
The actual code:
Key Takeaways
This problem teaches us to look beyond the obvious when dealing with subarrays!