🧠 LEETCODE CONSISTENCY SERIES 🚀 Day 1️⃣1️⃣ of 365 Days 🔁 📘 Topic: Strings 🧩 Problem: Longest Common Prefix (LeetCode #14) ⏱ Time Taken: ~15 minutes 🔹 Approach: Sorting + Character Comparison 🧠 After sorting the array of strings, only the first and last strings need to be compared. Any common prefix shared by all strings must also be common between these two. 🧩 Step-by-Step Algorithm 🔍 🧱 Step 1: Initialization / Setup Sort the list of strings lexicographically. This groups similar prefixes together. 🧵 Step 2: Starting State / Base Case Store the first and last strings from the sorted list. Initialize an empty string prefix to store the result. 🔁 Step 3: Main Loop / Traversal Iterate character-by-character up to the minimum length of the first and last strings. ⚖️ Step 4: Key Logic / Condition Check If characters at the same index match, add them to prefix. Stop the loop as soon as a mismatch is found. 🎯 Step 5: Termination Condition Loop ends on the first mismatch or when one string ends. 🏁 Step 6: Return Result Return the accumulated prefix. 🧠 Why This Works 💡 Sorting ensures the maximum possible difference appears between first and last strings. If these two share a prefix, all middle strings must share it too. Avoids unnecessary comparisons with every string. ⏱ Time Complexity ⌛ Best Case: O(n log n) Average Case: O(n log n) Worst Case: O(n log n) (Sorting dominates the complexity) 💾 Space Complexity 📦 O(1) (Ignoring input sorting space) Only a few variables are used for comparison. 🚀 What I Learned Today 📚 Sorting can simplify string comparison problems. Comparing just two extreme elements can be enough. Clean logic often beats brute force. 📌 Next Goal 🎯 Explore vertical scanning and Trie-based solutions for this problem. Consistency > Motivation 💪 🔗 GitHub: https://lnkd.in/dRGB_B8Z #DSA #LeetCode #Python #ProblemSolving #365DaysOfCode #CodingJourney 🚀
LeetCode Day 1: Longest Common Prefix (Sorting + Character Comparison)
More Relevant Posts
-
LeetCode Daily Challenge – Minimum Cost to Convert String 🔍 Problem Summary We are given two strings source and target. We can convert one character to another using some given rules, each with a cost. Our goal is to find the minimum total cost to convert source into target. If it’s not possible, return -1. 💡 Pattern Used Graph + Shortest Path (Dijkstra) Characters (a–z) are nodes Conversion rules are weighted edges Find the minimum cost path between characters 🛠️ Approach Build a graph from original → changed with costs Use Dijkstra to find shortest paths between all characters Store results in a 26 × 26 cost matrix For each index in source: Add the cost to convert source[i] → target[i] If conversion is impossible, return -1 ⏱️ Time & Space Complexity Time Complexity Dijkstra runs 26 times Each run: O(E log V) Since V = 26, total time is very small 👉 Overall: O(26 × E log 26) ≈ O(E) Space Complexity Cost matrix: 26 × 26 Graph storage 👉 Overall: O(26² + E) 🧠 Tricks & Tips Always precompute shortest paths for character problems Use ord(char) - ord('a') to map characters to indices Avoid iterating directly over defaultdict.keys() while running Dijkstra Skip Dijkstra updates if current distance is already larger (heap optimization) ✅ Key Takeaway When a problem involves transformations + costs, 👉 Think of it as a graph problem 👉 Shortest path algorithms save the day Happy coding 🚀 #LeetCode #DailyChallenge #Graphs #Dijkstra #Python
To view or add a comment, sign in
-
-
Day 6 of #200DaysOfCode! 🚀 Sticking with the Linked List theme, today I tackled one of the most essential problems in the data structure's repertoire: "Merge Two Sorted Lists" (LeetCode 21). If yesterday was about math on lists, today was about structure. The Challenge: Given two sorted linked lists, merge them into one single sorted list. Think of it like shuffling two decks of cards that are already sorted, or zipping a zipper. The Logic (The Zipper Technique): I used an iterative approach with Two Pointers (i for list1, j for list2) and a "Dummy Node" to build the result. Comparison: I compare the values at the head of both lists (i.val vs j.val). Selection: I pick the smaller value, add it to my new list, and move that specific pointer forward. The Loop: I keep doing this until one of the lists runs dry. The Cleanup: Once one list is empty, I simply append the remaining elements of the other list to the end (since they are already sorted!). The Result: Another 0 ms runtime, beating 100.00% of Python submissions! ⚡ It is a simple algorithm, but it is the exact same logic used in the "Merge" step of Merge Sort, making it a powerful pattern to master. Day 6 down. The streak is alive and well! 🔥 Do you prefer solving this Iteratively (like I did) or Recursively? The recursive solution is elegant but scary for large lists! 👇 #200DaysOfCode #Python #LeetCode #LinkedList #Algorithms #MergeSort #TwoPointers #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
Day 7 of #200DaysOfCode! 🚀 One week down! Today, I took a break from complex data structures to parse some ancient history: "Roman to Integer" (LeetCode 13). 🏛️ At first glance, this seems like simple addition. You just sum up the symbols, right? III = 1 + 1 + 1 = 3 XV = 10 + 5 = 15 But the "Subtraction Rule" throws a wrench in the works. If a smaller symbol appears before a larger one (like IV or IX), it subtracts instead of adds. The Logic (The Lookahead Technique): Instead of complicated string parsing or multiple passes, I used a clean linear scan with a simple rule: Map the Values: I used a Python Dictionary (Hash Map) to store the values ('I': 1, 'V': 5, etc.) for instant lookups. Iterate & Compare: I looped through the string and simply peeked at the next character. * If Current < Next: It means we are in a subtraction case (like the I in IV). I subtract the current value from the total. Otherwise: I simply add the current value. Example: For MCMXCIV (1994): C (100) < M (1000) → Subtract 100 X (10) < C (100) → Subtract 10 I (1) < V (5) → Subtract 1 This logic handles every edge case in a single pass O(N). The result was a flawless 0 ms runtime, beating 100.00% of Python submissions! 7 days in, and the streak is strong. 🧱 Have you tried the reverse problem (Integer to Roman)? I hear the logic is quite different! 👇 #200DaysOfCode #Python #LeetCode #Algorithms #HashMap #Logic #ProblemSolving #CodingChallenge #DeveloperJourney
To view or add a comment, sign in
-
-
Day 4 of #200DaysOfCode! 🚀 After tackling "3Sum" yesterday, I decided to circle back to the problem that started it all for many of us: "Two Sum" (LeetCode 1). While this is often the first problem developers solve, revisiting it with a focus on optimization is always valuable. The Strategy: Space vs. Time Yesterday, for 3Sum, I used sorting and pointers to save space. Today, for Two Sum, I used a Hash Map (Dictionary) to maximize speed. The Logic (One-Pass Hash Map): Instead of using a nested loop to find a pair (which would be a slow O(N^2)), I utilized a dictionary to "remember" the numbers I've seen so far. Iterate through the array. Calculate the complement: diff = target - nums[i]. Check if this diff already exists in our dictionary. If yes, we found our pair! Return the indices immediately. If no, store the current number and its index in the dictionary for future lookups. This approach trades a bit of memory O(N) for a massive gain in speed, bringing the time complexity down to a linear O(N). The Result: My Python solution hit a perfect 0 ms runtime, beating 100.00% of submissions. ⚡ It’s fascinating how different data structures (Hash Maps vs. Pointers) solve similar "Sum" problems in completely different ways. Day 4 down. The foundation is solid. 🧱 Which pattern do you prefer implementing: The "Two Pointer" dance or the "Hash Map" lookup? 👇 #200DaysOfCode #Python #LeetCode #TwoSum #Algorithms #HashMap #DataStructures #ProblemSolving #DeveloperJourney #Optimization
To view or add a comment, sign in
-
-
🚀 Day 8/30 | LeetCode Problem: Sort Colors (75) Problem: Given an array nums containing only 0s, 1s, and 2s, sort the array in-place so that colors are ordered as: 🔴 0 → ⚪ 1 → 🔵 2 Without using the built-in sort function. 🧠 Approach: Dutch National Flag Algorithm We use three pointers: a → position for 0 (left) b → position for 2 (right) c → current index Logic: If nums[c] == 0 → swap with a, move both forward If nums[c] == 2 → swap with b, move b backward If nums[c] == 1 → just move c This sorts the array in one pass. ⏱️ Complexity Time: O(n) Space: O(1) (in-place) 🧾 Python Code class Solution: def sortColors(self, nums): a = 0 # left pointer (0s) b = len(nums) - 1 # right pointer (2s) c = 0 # current index while c <= b: if nums[c] == 0: nums[a], nums[c] = nums[c], nums[a] a += 1 c += 1 elif nums[c] == 2: nums[b], nums[c] = nums[c], nums[b] b -= 1 else: c += 1 ✅ Result Accepted ✅ Runtime: 0 ms (Beats 100%) In-place & optimal solution 🎯 Takeaway Understanding pointer-based algorithms helps solve array problems efficiently without extra space . 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day8 #Python #Arrays #TwoPointers #DSA #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗫(𝗧𝘄𝗶𝘁𝘁𝗲𝗿) 𝗷𝘂𝘀𝘁 𝗼𝗽𝗲𝗻-𝘀𝗼𝘂𝗿𝗰𝗲𝗱 𝘁𝗵𝗲 𝗮𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺 𝗯𝗲𝗵𝗶𝗻𝗱 𝘁𝗵𝗲 𝗙𝗼𝗿 𝗬𝗼𝘂 𝗳𝗲𝗲𝗱. few things that really really stood out: • It is built around 𝘅𝗔𝗜’𝘀 𝗚𝗿𝗼𝗸 𝘁𝗿𝗮𝗻𝘀𝗳𝗼𝗿𝗺𝗲𝗿, moving away from hand crafted ranking rules • The system was refactored from 6 languages down to just Rust and Python, a huge win for simplicity and long-term maintainability • 𝗛𝗼𝗺𝗲𝗠𝗶𝘅𝗲𝗿 acts as the brain, orchestrating and scoring candidate posts • 𝗧𝗵𝘂𝗻𝗱𝗲𝗿 focuses on fast retrieval of in-network (people you follow) content • 𝗣𝗵𝗼𝗲𝗻𝗶𝘅 job is to find and rank posts the user doesn’t already follow and predict which ones the user is most likely to engage with. It is rare to see a production scale recommendation system opened up like this. For those who want to dig in: 🔗 https://lnkd.in/d8UU2vyx
To view or add a comment, sign in
-
-
🚀 Here’s today’s LeetCode practice question I worked on 🐍 Longest Balanced Substring — Simple O(n²) Brute Force Approach (Python) Worked on a problem where we need to find the longest substring in which all distinct characters appear with equal frequency. Instead of over-optimizing, I chose a constraint-aware brute force strategy since n ≤ 1000 — making an O(n²) solution practical and efficient. 🔍 Key Idea A substring is balanced when all character frequencies are equal → min(freq.values()) == max(freq.values()) ⚙️ Approach • Try every possible substring using two loops • Maintain a frequency dictionary incrementally • Check balance using min/max frequency • Track the maximum valid length found ⏱️ Complexity Time: O(n²) Space: O(1) (bounded by alphabet size) 💡 Takeaway: When constraints are small, a clean brute force solution can be more reliable and readable than complex optimizations. Always design based on limits — not assumptions. PYTHON code: class Solution(object): def longestBalanced(self, s): res = 0 for i in range(len(s)): freq = {} for j in range(i, len(s)): freq[s[j]] = freq.get(s[j], 0) + 1 if min(freq.values()) == max(freq.values()): res = max(res, j - i + 1) return res #Python #Algorithms #DataStructures #CodingPractice #ProblemSolving #LeetCode #BruteForce #TechLearning
To view or add a comment, sign in
-
-
Day 88 of #100DaysOfLeetCode Today’s problem looked extremely simple — but the trick was in understanding how cost is defined. 🟢 Divide an Array Into Subarrays With Minimum Cost I (LeetCode 3010 — Easy) You are given an array nums. Cost of a subarray = its first element Divide the array into 3 disjoint contiguous subarrays Minimize the total cost 🧠 Key Observation If we divide the array into 3 contiguous parts: Let the first elements of those parts be: nums[0] nums[i] nums[j] The total cost becomes: nums[0] + nums[i] + nums[j] Since the first subarray must start at index 0, the first cost is fixed → nums[0] Now we just need to choose the two smallest possible starting elements from the rest of the array. 💡 Strategy Keep nums[0] fixed Sort the remaining elements Pick the smallest two Add them to nums[0] 🛠 Final Logic first = nums[0] nums[1:] = sorted(nums[1:]) return first + nums[1] + nums[2] ⏱ Complexity Sorting: O(n log n) Space: O(1) (if in-place) Since we only need two smallest values, this could also be optimized to O(n) using a linear scan. 🎯 What I Learned Always simplify the cost formula Translate problem into mathematical expression Many “array division” problems reduce to selecting minimum elements Don’t overthink Easy problems — pattern recognition matters ✅ Day 88 Summary ✔ Greedy insight ✔ Cost modeling ✔ Subarray partition logic ✔ Clean and minimal implementation On to Day 89 🚀 #100DaysOfLeetCode #Day88 #Greedy #Arrays #ProblemSolving #DSA #Python #CodingJourney #AdityaCodes
To view or add a comment, sign in
-
-
In this video, I’m demonstrating a finished project: a professional-grade Google Maps data extractor built entirely with Pure Python 🐍. This isn't a tutorial, but a showcase of a production-ready tool designed for scale and efficiency. By leveraging Selenium and BeautifulSoup4, I’ve created a stable pipeline that navigates, extracts, and structures lead data directly into spreadsheets. This tool was designed to solve a real-world demand: automating the transition from raw map data to a clean, actionable database for sales teams. https://lnkd.in/dWEyKy_N
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