🔥 Day-9 — Rotate Array (Array Manipulation + Reversal Trick) 🧩 Problem: Rotate Array 💻 Platform: LeetCode (#189) Given an array, rotate it to the right by k steps. At first, this looks like a simple shifting problem. Brute force idea: Shift elements one by one, k times. Time Complexity → O(n × k). Not scalable. Better idea: Use an extra array and place elements at correct rotated positions. Time → O(n) Space → O(n) But the optimal solution? 🚀 Reverse Technique (In-Place) Steps: 1️⃣ Reverse the entire array 2️⃣ Reverse first k elements 3️⃣ Reverse remaining n − k elements That’s it. Time Complexity: O(n) Space Complexity: O(1) 💡 Why this works: Reversal repositions elements into their final rotated order without needing extra memory. It’s not obvious at first — but once you visualize it, it becomes clean and elegant. Key Takeaways: ✔ Not all array problems require extra space ✔ In-place manipulation is a powerful skill ✔ Sometimes the trick is not shifting — but reordering cleverly Each day I’m realizing: Patterns repeat. Tricks repeat. Only the surface changes. Day-9 complete. Onward 🚀 #30DaysOfCode #LeetCode #DSA #Java #Arrays #Algorithms #ProblemSolving #SoftwareEngineering #Developers
Rotate Array in Place with Reversal Trick
More Relevant Posts
-
Sometimes a brute force approach is more than enough before jumping to complex optimizations. 🚀 While solving LeetCode 3713 – Longest Balanced Substring, I followed a straightforward brute-force strategy that worked effectively within constraints. 🔍 Approach: The idea is to check every possible substring and verify whether it is balanced. A substring is considered balanced if all characters present in it appear the same number of times. 1. Iterate through every possible starting index i. 2. For each start, extend the substring with index j. 3. Maintain a frequency array of size 26 to track occurrences of characters. 4. After each extension, check whether all non-zero frequencies are equal. 5. If the substring is balanced, update the maximum length. (The helper function verifies the balance condition by ensuring all characters that appear in the substring have the same frequency.) ⏱ Time Complexity: >Outer loop for start index → O(n) >Inner loop for end index → O(n) >Balance check over 26 characters → O(26) ≈ O(1) >Overall Time Complexity: O(n²) 💾 Space Complexity: >Frequency array of size 26 → O(1) (constant space) ✨ Sometimes the simplest idea—checking all possibilities carefully—can solve the problem efficiently without overcomplicating the solution. #LeetCode #ProblemSolving #DataStructures #Algorithms #Java #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day-11 — Longest Substring Without Repeating Characters 🧩 Problem: Longest Substring Without Repeating Characters 💻 Platform: LeetCode (#3) This problem forced me to truly understand the Sliding Window pattern. Brute force checks every substring. That’s inefficient. Optimal approach: ✔ Use two pointers (left & right) ✔ Expand the window ✔ Shrink when duplicate appears ✔ Track max window size Time Complexity: O(n) Space Complexity: O(n) Big takeaway: If a problem mentions “longest substring” + “no repetition” → Sliding Window should be your first thought. Strings aren’t new logic. They’re just arrays of characters. Day-11 complete. Moving deeper into string patterns 🚀 #30DaysOfCode #LeetCode #DSA #Java #SlidingWindow #Algorithms #ProblemSolving #Developers
To view or add a comment, sign in
-
-
🚀 Day 46 of #100DaysOfCode Solved 719. Find K-th Smallest Pair Distance on LeetCode 📏 🧠 Key Insight: We need to find the k-th smallest absolute difference among all possible pairs in the array. Brute force (generating all pairs) would be O(n²) → not efficient. Instead, we use Binary Search on Answer + Two Pointers. ⚙️ Approach: 1️⃣ Sort the array 2️⃣ Define search space: 🔹left = 0 (minimum distance) 🔹right = max(nums) - min(nums) 3️⃣ Apply Binary Search: 🔹For a given mid, count how many pairs have distance ≤ mid 4️⃣ Counting pairs efficiently: 🔹Use two pointers 🔹For each i, move j while nums[j] - nums[i] ≤ mid 🔹Add (j - i - 1) to count 5️⃣ If count ≥ k → try smaller distance 6️⃣ Else → increase distance 🎯 Final answer = smallest distance satisfying the condition ⏱️ Time Complexity: O(n log n + n log D) 🔹Sorting + Binary Search with linear check 📦 Space Complexity: O(1) #100DaysOfCode #LeetCode #DSA #BinarySearch #TwoPointers #Algorithms #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟲/𝟭𝟬𝟬 — 𝗘𝘃𝗮𝗹𝘂𝗮𝘁𝗲 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗣𝗼𝗹𝗶𝘀𝗵 𝗡𝗼𝘁𝗮𝘁𝗶𝗼𝗻 Day 66. Two-thirds done. Today's problem? The reason calculators exist. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟭𝟱𝟬: Evaluate Reverse Polish Notation (Medium) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Evaluate expressions in Reverse Polish Notation (RPN). Numbers come first, operators after. Example: ["2","1","+","3","*"] → ((2+1)*3) = 9 No parentheses needed. No order of operations confusion. Just read left to right. 𝗧𝗵𝗲 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Stack. When you see a number, push it. When you see an operator, pop two numbers, apply the operation, push the result. The last number standing? That's your answer. Used ArrayList as a stack for cleaner syntax with removeLast(). Same LIFO behavior. 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: This is how calculators and compilers evaluate expressions internally. RPN eliminates ambiguity. "3 + 4 * 5" needs rules. "3 4 5 * +" doesn't. Understanding this makes you understand how expression parsing works. 𝗖𝗼𝗱𝗲: https://lnkd.in/gXwcqVdP 𝗗𝗮𝘆 𝟲𝟲/𝟭𝟬𝟬 ✅ 𝟲𝟲 𝗱𝗼𝘄𝗻. 𝟯𝟰 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #Stack #RPN #Algorithms #ExpressionEvaluation #CodingInterview #Programming #Java #MediumLevel #CompilerDesign
To view or add a comment, sign in
-
Day 72: Binary Search Squared 🏔️ Problem 3296: Minimum Number of Seconds to Make Mountain Height Zero Today’s problem was a masterclass in optimization. The goal: reduce a mountain's height to zero using workers who take progressively more time for each unit of height they remove. The Strategy: • Binary Search on Answer: Since the time needed is monotonic, I used binary search to find the minimum seconds required to finish the job. • Nested Binary Search: Inside that loop, I ran a second binary search for each worker to calculate the maximum height they could handle within that time limit. • Efficiency: This "Double Binary Search" approach kept the runtime lean even with a massive search space up to 10^16. Solving a "Binary Search inside a Binary Search" problem is a great way to test your grip on time complexity. It’s all about finding that optimal boundary. 🚀 #LeetCode #Java #BinarySearch #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
#100DaysOfCode 🚀 👉Solved: LeetCode 75 – Sort Colors The goal was to sort an array containing only three values: 0 (Red), 1 (White), and 2 (Blue) At first glance this looks like a simple sorting problem. But the twist: ❌ No built-in sort ✔ One pass ✔ Constant space The solution uses the famous **Dutch National Flag Algorithm**. Instead of sorting normally, we maintain three pointers: • low → for 0s • mid → current element • high → for 2s Rules: • If nums[mid] == 0 → swap with low • If nums[mid] == 1 → move mid forward • If nums[mid] == 2 → swap with high This allows sorting the array in a single pass. 📌 Key Points: ✔ In-place sorting ✔ One pass algorithm ✔ Constant space usage ✔ Classic three-pointer technique ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this show how powerful pointer techniques can be. Day 15✅ #DSA #Java #LeetCode #Algorithms #ProblemSolving #100DaysOfCode #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
🚀 A quick tip from the “Rotate String” problem! A popular trick to check if one string is a rotation of another is this: return s.length() == goal.length() && (s + s).contains(goal); The idea is pretty straightforward: if goal is a rotation of s, it’ll show up somewhere inside s + s. For example: s = "abcde" goal = "cdeab" s + s = "abcdeabcde" and you can see "cdeab" right there. But here’s the catch: the .contains() method does a substring search that can be slow in the worst case (up to O(n²)). So while this trick usually works fine, it’s not the most efficient for all cases. But to reduce the time complexity, we can use KMP (Knuth–Morris–Pratt) algorithm instead: Build the LPS (Longest Prefix Suffix) array for goal Use KMP to search for goal inside s + s This guarantees the search will run in O(n) time. 💡 It’s a good reminder that a simple trick can solve a problem quickly, but knowing classic algorithms like KMP helps to build solutions that perform well even in tricky situations. #Algorithms #Coding #TechTips #Java #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 74/365 – Remove Duplicate Letters Problem: Given a string s, remove duplicate letters so that each letter appears once and the result is the smallest lexicographical order possible. Example: "bcabc" → "abc" "cbacdcbc" → "acdb" 💡 Key Idea Use a Monotonic Stack to maintain characters in lexicographically smallest order. We also track: • Last occurrence of each character • Whether a character is already used in the result 🧠 Approach 1️⃣ Record the last index of each character. 2️⃣ Traverse the string. 3️⃣ Skip characters already included. 4️⃣ While stack top is bigger than current character and it appears later again, remove it to get a smaller result. 5️⃣ Push current character into the stack. 📦 Key Logic while(!stack.isEmpty() && stack.peek() > c && lastIndex[stack.peek() - 'a'] > i) { visited[stack.pop() - 'a'] = false; } This ensures: Lexicographically smallest result Each character appears only once 📊 Complexity ⏱ Time: O(n) 📦 Space: O(1) (since only 26 letters) ✨ Key Learning This is a classic Monotonic Stack + Greedy problem. Pattern to remember: 👉 Remove previous larger elements if they appear again later. This pattern appears in problems like: Smallest Subsequence Remove K Digits Monotonic stack optimization problems #Day74 #365DaysOfCode #LeetCode #MonotonicStack #GreedyAlgorithm #DataStructures #Algorithms #Java #DSA #CodingInterview
To view or add a comment, sign in
-
-
Today I solved the classic Rotate Array problem — a simple-looking question that teaches a powerful concept: in-place transformation. 💡 Problem: Rotate an array to the right by k steps without using extra space. 🧠 Approach (Optimal): Instead of shifting elements one by one (O(n·k)), I used a smarter trick: ✔️ Reverse the entire array ✔️ Reverse first k elements ✔️ Reverse remaining elements ⚡ This reduces complexity to: ⏱️ Time → O(n) 📦 Space → O(1) 🔥 Key Learning: Sometimes, reversing parts of a data structure can simplify what looks like a complex movement problem. 📌 Problems like this strengthen understanding of: • Two-pointer technique • In-place algorithms • Array manipulation Consistency is key — one problem at a time! 💪 #DataStructures #Algorithms #Java #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
✳️Day 23 of #100DaysOfCode✳️ 🚀Solved Remove Duplicate Letters ✅The goal is to remove duplicate letters so that every letter appears once, ensuring the result is the smallest in lexicographical order among all possible results. 🧠 My Approach & Implementation Steps: To solve this efficiently in O(n) time, I used a Greedy approach supported by a Monotonic Stack: 1️⃣Frequency Map: First, I built a frequency array freq[26] to keep track of the remaining count of each character in the string. This tells the algorithm if a character can be safely removed and re-added later. 2️⃣Visited Tracking: I used a boolean array visited[26] to ensure each character is added to our result only once, maintaining the "unique" constraint. 3️⃣Monotonic Stack Logic: As I iterated through the string: I decremented the character's frequency. If the character was already in the stack, I skipped it. 4️⃣The Crucial Part: While the current character was smaller than the top of the stack AND that top character appeared again later in the string (checked via the frequency map), I popped the stack and marked that character as "not visited." 💯Result Construction: Finally, I pushed the current character onto the stack and built the final string using a StringBuilder. 📊 Results: Runtime: 2 ms (Beats 89.98%) Memory: 43.64 MB (Beats 78.91%) ⚡This problem is a great reminder of how powerful stacks can be when you need to maintain a specific order while processing linear data. Onward to the next challenge! 💻🔥 #LeetCode #Java #DataStructures #Algorithms #CodingLife #ProblemSolving #SoftwareEngineering Anchal Sharma Ikshit ..
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development