Day 29 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Reverse a String We were given a string. Task was simple. Reverse the characters. Example: "hello" → "olleh" Looks easy. But there are multiple ways to do it. 💻 Brute Force Approach 🔹️Create a new empty string. 🔹️Traverse the original string from the end. 🔹️Append each character to the new string. 🔹️Return the new reversed string. Time Complexity: O(n) Space Complexity: O(n) Because a new string is created. 💻 Optimal Approach (Two Pointers) 🔹️Convert the string into a character array. 🔹️Place one pointer at the start. 🔹️Place another pointer at the end. 🔹️Swap both characters. 🔹️Move pointers toward the center. Continue until they meet. Time Complexity: O(n) Space Complexity: O(1) No extra string needed. 📚 What I learned today: ▫️Two-pointer technique works well for reversal problems. ▫️In-place operations help reduce space complexity. ▫️String problems often become easier when treated as arrays. ▫️Pointer movement patterns appear in many algorithms. Day 29 completed. Small problem, but useful pattern 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
Reversing Strings with Two Pointers
More Relevant Posts
-
Day 37 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Second Most Repeated String in a Sequence We were given a list of strings. Task was to find the second most frequent string. Not the most frequent. The one just below it. 💻 Approach 🔹️Create a hash map to store frequency of each string. 🔹️Traverse the sequence and count occurrences. 🔹️Track the highest and second highest frequency. 🔹️Find the string with second highest count. 🔹️Return that string. Simple counting + comparison. 📊 Complexity Analysis Time Complexity: O(N * max(|Si|)) Space Complexity: O(N * max(|Si|)) 📚 What I learned today: ▫️Hash maps are very useful for frequency-based problems. ▫️Tracking second maximum needs careful comparison. ▫️One-pass counting + second pass evaluation works well. ▫️String problems often reduce to counting patterns. Day 37 completed. Getting more comfortable with hash maps 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Day 36 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Uncommon Characters in Two Strings We were given two strings s1 and s2. Task was to find characters that are present in only one string. Not in both. Final result should be sorted 💻 Approach 🔹️Create two frequency arrays (or sets). 🔹️Traverse s1 and mark its characters. 🔹️Traverse s2 and mark its characters. 🔹️Now check each character from 'a' to 'z': ▪️If present in only one string → include it ▪️If present in both → skip it 🔹️Add valid characters to result string. 🔹️Sort the result. Simple comparison logic. --- 📊 Complexity Analysis Time Complexity: **O(n + m)** Space Complexity: **O(n + m)** --- 📚 What I learned today: ▫️Set/frequency based comparison is useful for string problems. ▫️Checking presence instead of count simplifies logic. ▫️Iterating over fixed character range helps in sorting automatically. ▫️Problem is more about filtering than processing. Day 36 completed. Understanding string comparison better 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 68 of #100DaysOfCode 🔥 Solved Median of Two Sorted Arrays (LeetCode Q4) today! 💡 Problem Insight: Find the median of two sorted arrays in an efficient way without merging them. 🧠 Approach: - Use Binary Search on the smaller array - Partition both arrays such that left side has smaller elements and right side has larger ones - Ensure correct balance of elements on both sides ⚙️ Algorithm: - Apply binary search to find correct partition - Check conditions for valid split - If valid → calculate median based on total length - Else → adjust search space ⏱️ Complexity: - Time: O(log(min(n, m))) - Space: O(1) 📌 Key Learning: Brute force is not always the answer — smart partitioning can optimize everything. 💬 Think smart, not hard. #DSA #LeetCode #BinarySearch #100DaysOfCode #CodingJourney #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 46 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Geometric Sum using Recursion We were given an integer n. Task was to find the sum: 1 + 1/3 + 1/3² + ... + 1/3ⁿ Using recursion. 💻 Approach 🔹️Define a recursive function sum(n). 🔹️Base case: ▪️If n == 0 → return 1 🔹️Recursive case: ▪️Return sum(n-1) + 1/(3ⁿ) Each call adds one term. And moves toward smaller n. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) Due to recursion stack. 📚 What I learned today: ▫️Recursion can be used for summation of series. ▫️Each recursive call adds one term to the result. ▫️Understanding base case is important to stop recursion. ▫️Power calculations are common in series problems. Day 46 completed. Getting more comfortable with recursive formulas 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Day 83 of #100DaysOfCode Today I solved "Binary Tree Maximum Path Sum" on LeetCode using DFS + Recursion. Key Idea: At every node, we calculate the maximum path sum passing through it. But here’s the twist We ignore negative paths because they reduce the total sum. Approach: • Recursively get the max path sum from left and right subtrees • Ignore negative values using max(0, …) • Update the global answer as: root->val + left + right • Return to parent: root->val + max(left, right) This ensures we consider both: Path passing through the node Path extending upwards Concepts Used: • Binary Trees • Depth First Search (DFS) • Recursion • Greedy choice (ignore negative paths) Time Complexity: O(n) Space Complexity: O(h) This problem really sharpened my understanding of handling multiple path possibilities in trees From simple traversals to advanced patterns — growth is visible #Day83 #100DaysOfCode #LeetCode #BinaryTree #DFS #Cpp #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 11 of My LeetCode Journey Today’s problem: Container With Most Water This problem looked tricky at first, but the solution turned out to be a clean application of the Two Pointer technique. 💡 Key Idea: Start with two pointers at both ends Calculate area using width × minimum height Move the pointer with smaller height to maximize area 🔍 Instead of brute force O(n²), optimized it to O(n) 🚀 ⚡ Result: Accepted ⏱️ Runtime: 60 ms 🧠 What I Learned: Two Pointers can drastically reduce complexity Always think about optimizing from both ends Logic > brute force #LeetCode #DSA #CodingJourney #100DaysOfCode #TwoPointers #Algorithms #ProblemSolving
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 17 Problem: 1727. Largest Submatrix With Rearrangements Topic: Array, Greedy, Sorting, Matrix 📌 Quick Problem Sense: You have a binary matrix (0s and 1s). You can rearrange columns in any order. Find the largest submatrix where every element is 1 after optimal column reordering. The trick? You don't need to try every permutation → Sort column heights per row and greedily pick the best rectangle! 🧠 Approach (Simple Thinking): 🔹 For each cell, compute the height = number of consecutive 1s stacked upward (including itself) 🔹 If a cell is 0, its height resets to 0 🔹 For each row, clone the heights array and sort it in ascending order 🔹 Iterate from the tallest height to the shortest, at each step, width = columns selected, height = current column's value 🔹 Area = height × width → track the maximum 🔹 Since columns can be freely reordered, sorting gives the globally optimal arrangement 🔹 Return the maximum area found ⏱️ Time Complexity: Building heights → O(m × n) Sorting per row → O(m × n log n) Overall → O(m × n log n) 📦 Space Complexity: One extra array per row → O(n) In-place height updates → O(1) extra for the matrix I wrote a full breakdown with dry run, real-life analogy, and step-by-step code walkthrough here 👇 https://lnkd.in/gpbQdPkj If you solved it differently , maybe using a monotonic stack on the histogram, drop it in the comments, always love seeing different angles on the same problem 💬 See you in the next problem 👋 #LeetCode #CodingChallenge #DSA #DataStructures #Algorithms #Greedy
To view or add a comment, sign in
-
-
🚀 Cracked one of the toughest 🔥 problems on LeetCode — Median of Two Sorted Arrays." 💡 Problem: Find the median of two sorted arrays in O(log (m+n)) time. 🧠 Key Insight: Instead of merging arrays (O(n)), I used Binary Search + Partitioning to split both arrays such that: ✔ Left half contains equal elements ✔ All left elements ≤ right elements ⚙️ Approach Highlights: ✅ Binary search on smaller array ✅ Handle edge cases using ±∞ ✅ Partition validation logic ✅ Works for both even & odd lengths 🔥 Journey: After 3 attempts, finally nailed this problem 💪 Each attempt taught something new — edge cases, partition logic, and precision. ⚡ Result: ✔ Accepted ✅ ⚡ Runtime: 0 ms (Beats 100%) 💻 Clean & optimal solution 🎯 What I learned: Thinking beyond brute force is key Binary search isn’t just for searching Edge cases define correctness 💬 Challenge for you: Can you solve this without merging arrays? 😉 #LeetCode #DataStructures #Algorithms #BinarySearch #CodingInterview #SoftwareEngineer #ProblemSolving #TechInterview #100DaysOfCode
To view or add a comment, sign in
-
-
Day 97/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 456 – 132 Pattern(Medium) 🧠 Approach: Traverse the array from right to left while maintaining a stack. Use a variable to track the “middle” element (the ‘2’ in 132 pattern) and check if a valid pattern exists. 💻 Solution: class Solution: def find132pattern(self, nums: List[int]) -> bool: stack = [] third = float('-inf') for i in range(len(nums) - 1, -1, -1): if nums[i] < third: return True while stack and nums[i] > stack[-1]: third = stack.pop() stack.append(nums[i]) return False ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Using a monotonic stack while iterating backwards helps efficiently detect complex patterns in linear time. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: Largest Submatrix With Rearrangements You are given a binary matrix (containing only 0s and 1s). You are allowed to rearrange the columns of each row independently. 🎯 Goal Find the area of the largest submatrix consisting only of 1s that can be formed after rearranging the columns optimally. 🧠 Key Intuition Instead of directly rearranging columns, think in terms of heights of consecutive 1s: For each column, compute how many continuous 1s are stacked vertically up to that row. This transforms each row into a histogram. Now the trick is: ➡️ If we sort each row in descending order, we simulate the best possible column rearrangement. Why does this work? Taller columns grouped together → larger rectangle area Sorting ensures we always try the widest possible rectangle with maximum height 🛠 Approach 1️⃣ Build a height matrix (grid): If matrix[i][j] == 1 grid[i][j] = grid[i-1][j] + 1 Else → 0 2️⃣ For each row: Sort the row (heights) in non-decreasing order 3️⃣ For each position j: Treat grid[i][j] as height Width = (n - j) (since sorted) 4️⃣ Compute area: area = height × width 5️⃣ Keep track of the maximum area 📈 Complexity Analysis Time Complexity: O(m × n log n) Space Complexity: O(m × n) 🔗 Problem https://lnkd.in/dZ775m6j 💻 Solution https://lnkd.in/dhqZGZSc #LeetCode #Cpp #DSA #Algorithms #MatrixProblems #Greedy #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney 🚀
To view or add a comment, sign in
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