🚀 Day 43 of #100DaysOfCode Today’s problem focused on Strings + Arrays with a clean optimization trick — 🧵 Longest Common Prefix 📌 Problem Summary Given an array of strings, the goal is to find the longest prefix shared by all strings. If no common prefix exists, return an empty string. At first glance, it feels like a brute-force string comparison problem — but there’s a smarter way 💡 🧠 My Approach: Sorting + Boundary Comparison Key insight: After sorting the array of strings lexicographically: The first and last strings will be the most different The common prefix of the entire array must be the common prefix of just these two strings Steps: Sort the array Compare characters of the first and last strings Stop when characters mismatch Extract the prefix till that point This avoids unnecessary comparisons across all strings and keeps the solution elegant and efficient ✨ ⚙️ Complexity Analysis ⏱ Time: O(n log n + m) 💾 Space: O(1) (ignoring sort internals) (n = number of strings, m = length of shortest string) 🔥 Key Learning Sorting can simplify problems that seem comparison-heavy Often, extreme cases (first & last) reveal global properties Clean logic > brute force ✅ Solution accepted successfully with fast runtime, keeping the momentum strong 💪 Onward to Day 44 — consistency builds mastery 🚀 #100DaysOfCode #LeetCode #Strings #Arrays #Java #DSA #ProblemSolving #CodingJourney #Consistency
Optimizing Strings + Arrays with Sorting and Boundary Comparison
More Relevant Posts
-
𝗗𝗮𝘆 𝟯𝟲/𝟭𝟬𝟬 | 𝗠𝗲𝗿𝗴𝗲 𝗧𝘄𝗼 𝗦𝗼𝗿𝘁𝗲𝗱 𝗟𝗶𝘀𝘁𝘀 Day 36 ✅ — Recursion over iteration. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 #𝟮𝟭: Merge Two Sorted Lists (Easy) 𝗪𝗵𝗮𝘁 𝗖𝗹𝗶𝗰𝗸𝗲𝗱: Merge two sorted linked lists. Instead of the iterative dummy node approach, I used 𝗿𝗲𝗰𝘂𝗿𝘀𝗶𝗼𝗻. Compare the heads. Attach the smaller one, then recursively merge the rest. Base case: if one list is empty, return the other. Elegant. Three lines of logic. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: 👉 Base cases: if l1 is null, return l2 (and vice versa) 👉 Compare l1.val and l2.val 👉 Attach smaller node and recurse with remaining lists Time: O(n + m), Space: O(n + m) for recursion stack 𝗠𝘆 𝗥𝗲𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻: Seven linked list problems, and recursion just made this one cleaner than iteration. Sometimes the simplest code is the most powerful. 𝗖𝗼𝗱𝗲:🔗 https://lnkd.in/g4f4_B69 𝗗𝗮𝘆 𝟯𝟲/𝟭𝟬𝟬 ✅ | 𝟲𝟰 𝗺𝗼𝗿𝗲 𝘁𝗼 𝗴𝗼! #100DaysOfCode #LeetCode #LinkedList #Recursion #DataStructures #CodingInterview #SoftwareEngineer #Java #Algorithms #Programming
To view or add a comment, sign in
-
#200DaysOfCode – Day 111 Word Search Problem: Given a 2D grid of characters and a word, determine whether the word exists in the grid. The word must be formed using adjacent cells (up, down, left, right), and each cell can be used only once. Example: Input: board = [[A, B, C, E], [S, F, C, S], [A, D, E, E]] word = "ABCCED" Output: true My Approach: Used DFS (Depth First Search) starting from every cell. Matched characters step-by-step with the given word. Marked cells as visited during the path to avoid reuse. Applied backtracking to explore all possible directions safely. Time Complexity: O(m × n × 4^L) Space Complexity: O(L) (recursion stack) Grid problems often look complex, but breaking them down with DFS + backtracking makes the logic clear and manageable. Patience and careful state handling are the real keys here #takeUforward #100DaysOfCode #Java #LeetCode #ProblemSolving #Backtracking #DFS #DataStructures #Algorithms #CodeNewbie #Consistency
To view or add a comment, sign in
-
-
LeetCode 3010: Divide an Array Into Subarrays With Minimum Cost I — a neat “read the definition carefully” problem I enjoyed this one because it looks like a partitioning problem… but the optimal solution is just a simple scan. Key insight: When you split the array into 3 subarrays, the cost = sum of the first element of each subarray. The first subarray must start at index 0, so nums[0] is always included. You’re free to choose where subarray 2 and 3 start (somewhere in nums[1..]). To minimize cost, you simply pick the two smallest values from nums[1..]. So the answer is: nums[0] + smallest(nums[1..]) + secondSmallest(nums[1..]) Leetcode problem link:https://lnkd.in/gUrES9Td #leetcode #java #datastructures #algorithms #problemsolving
To view or add a comment, sign in
-
-
🚀 Day 57 of #100DaysOfCode Solved LeetCode Problem #2943 – Maximize Area of Square Hole in Grid. This problem focused on identifying the largest possible square that can be formed after removing horizontal and vertical bars from a grid. The key was to analyze consecutive gaps efficiently and translate them into the maximum square area. Key Learnings: -> Sorting input arrays to simplify gap analysis -> Tracking longest consecutive segments in both dimensions -> Understanding how grid constraints map directly to square geometry -> Writing clean, optimal logic for interval-based problems Language Used: Java -> Runtime: 4 ms (Beats 100.00%) -> Memory: 45.45 MB (Beats 50.00%) Consistent problem-solving, sharper logic, one day at a time 🚀 #LeetCode #Arrays #Geometry #Java #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 49 of #100DaysOfCode Today’s challenge was a clean and elegant Two Pointer problem — 🔢 LeetCode: Two Sum II – Input Array Is Sorted 📌 Problem Summary You’re given a sorted array of integers and a target value. Your task is to find two numbers such that their sum equals the target and return their 1-based indices. ⚠️ Constraint: The array is already sorted, which opens the door to an optimized approach. 🧠 My Approach: Two Pointers Instead of using a HashMap, I leveraged the sorted property: Start one pointer at the beginning Another at the end Calculate the sum: If sum is too small → move left pointer forward If sum is too large → move right pointer backward If equal → solution found 🎯 This avoids extra space and keeps the solution super efficient. ⚙️ Complexity Analysis ⏱ Time: O(n) 💾 Space: O(1) Minimal memory, maximum efficiency 💡 🔥 Key Learning Always look for hidden constraints (like sorted input!) Two Pointer technique can replace HashMaps in many cases Clean logic often beats complex code ✅ Solution accepted with excellent runtime & memory performance Another fundamental pattern locked in 🔐 On to Day 50 — halfway milestone loading… 🚀🔥 #100DaysOfCode #LeetCode #Java #TwoPointers #Arrays #ProblemSolving #DSA #CodingJourney
To view or add a comment, sign in
-
-
LeetCode POTD #3013 - Divide an Array Into Subarrays With Minimum Cost II (02 February 2026) This one looks messy at first glance, but the trick is how you frame it. The first subarray is forced to start at index 0. So the real decision is where the last subarray starts. Fix the starting index of the last subarray at i. Now the constraint i(k-1) - i1 <= dist forces the remaining k-2 subarrays to start inside the window: [i - dist, i - 1] At that point, the problem becomes clean: From a sliding window of length dist, continuously maintain the smallest k-2 values. To do this efficiently: -> Use two ordered sets -> One keeps the k-2 smallest elements -> The other holds the rest -> Maintain the sum while the window slides Total cost for each i: nums[0] + nums[i] + sum_of_k-2_smallest Minimum across all valid i is the answer. Key takeaway: Hard problems usually aren’t about complex code -> they’re about choosing the right perspective. Time Complexity -> O(n log n) Space Complexity -> O(n) #LeetCode #POTD #HardProblems #DataStructures #SlidingWindow #Java #ProblemSolving
To view or add a comment, sign in
-
-
Hello Everyone, Day 14 / #100DaysOfCode LeetCode 3454 — Separate Squares II (Hard) This problem was on a completely different level. Unlike Separate Squares I, overlapping areas here must be counted only once, which immediately rules out simple area accumulation or binary search tricks. Approach: Scan Line + Segment Tree (Adapted from the editorial and inspired by LeetCode 850 — Rectangle Area II) Core idea: - Sweep a horizontal scan line from bottom to top - Convert each square into two events: - Bottom edge → +1 coverage - Top edge → -1 coverage - Maintain active horizontal coverage using a segment tree with lazy propagation - At any vertical slice: - covered area = width × height - Width is the total x-length where coverage > 0 What the segment tree tracks: - Coverage count for each x-interval - Total covered length when count > 0 Using this, we compute the total covered area. Then, during the same scan, we locate the smallest y such that: area_below(y) = totalArea / 2 Since coverage stays constant between two scan events, the exact y can be computed analytically inside that interval. Complexity: - Time: O(n log n) - Space: O(n) Honest takeaway: I couldn’t crack this one independently and relied heavily on the editorial. Problems like this genuinely feel Extra Hard — combining geometry, sweep-line algorithms, discretization, and segment trees in one go. LeetCode has definitely raised the bar. #LeetCode #HardProblems #DSA #Java
To view or add a comment, sign in
-
-
🚀 Day 67 of #100DaysOfCode Today’s problem focused on 2D Prefix Sum optimization — Range Sum Query 2D – Immutable (NumMatrix) 📊 At first glance, this problem looks like repeated matrix traversal, but the real win comes from preprocessing smartly. 📌 Problem Summary You’re given a 2D matrix and multiple queries asking for the sum of elements inside a sub-rectangle. Brute force would be too slow for repeated queries. 🧠 My Approach: Prefix Sum (Row-wise) Precompute prefix sums for each row For every query, calculate the sum in O(rows) time using prefix subtraction Avoid recalculating sums for every query This transforms repeated heavy computation into a fast query process ⚡ ⚙️ Time & Space Complexity Preprocessing: O(rows × cols) Each Query: O(rows) Space: O(rows × cols) 🔥 Key Learning Prefix sums are not limited to 1D arrays— they scale beautifully to 2D problems and are extremely powerful for range queries. Another solid step forward in mastering optimization techniques 💪 On to Day 68 🚀 #Day67 #100DaysOfCode #Java #LeetCode #PrefixSum #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🔥 Day 309 – Daily DSA Challenge! 🔥 Problem: 🔁 Permutations II Given an array nums that may contain duplicate numbers, return all unique permutations in any order. 💡 Key Insights: 🔹 This is a backtracking problem with an extra twist — duplicates. 🔹 Sorting the array upfront is the key to handling duplicates cleanly. 🔹 Use a used[] boolean array to track which elements are already in the current permutation. 🔹 The golden rule to skip duplicates 👇 👉 If the current number is the same as the previous one and the previous one is not used, skip it. 🔹 This ensures we only generate unique permutations. ⚡ Optimized Plan: ✅ Sort the input array ✅ Use backtracking to build permutations ✅ Track used elements with a boolean array ✅ Add permutation to result when its size equals nums.length ✅ Skip duplicates using: if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; ✅ Backtrack after each recursive call ✅ Time Complexity: O(n! × n) (due to copying permutations) ✅ Space Complexity: O(n) (recursion stack + used array) 💬 Challenge for you: 1️⃣ Why does the condition !used[i - 1] matter for avoiding duplicates? 2️⃣ How would this solution change if all numbers were unique? 3️⃣ Can you generate permutations iteratively instead of using recursion? #DSA #Day309 #LeetCode #Permutations #Backtracking #Recursion #Java #ProblemSolving #KeepCoding #100DaysOfCode
To view or add a comment, sign in
-
-
📘 Day 74 – Decode String Solved the Decode String problem — a classic stack-based challenge that focuses on string parsing and handling nested patterns. 🧩 Problem Overview Given an encoded string with repetition counts and brackets, decode it to produce the final expanded string. 🎯 Goal Correctly handle nested brackets, multi-digit numbers, and maintain order while decoding. 💡 Key Insight Using stacks helps track repetition counts and previously built strings, making nested decoding manageable. 🛠️ Approach Use stacks for counts and strings Build substrings incrementally Decode on closing brackets and merge results 🧠 Concepts Practiced Stack String manipulation Nested structure handling ⏱️ Time Complexity: O(N) 📦 Space Complexity: O(N) Showing up every day compounds learning 🌱 #Day74 #DSA #Stack #Java #ProblemSolving #Consistency
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