Day 43 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to find the Longest Common Prefix (LCP) among a list of strings. This is a popular problem that helps strengthen string manipulation and comparison logic. What the program does: • Takes a list of strings as input • Finds the common starting characters shared by all strings • Returns the longest common prefix • Handles edge cases like empty lists and single strings How the logic works: • If the list is empty, return an empty string • Sort the list of strings • Compare only the first and last strings (they will have the maximum difference) • Iterate character by character • Add matching characters to the prefix • Stop when characters don’t match • Return the final prefix Example: Input: ["flower", "flow", "flight"] Output: "fl" Another example: Input: ["dog", "racecar", "car"] Output: "" (No common prefix) Another example: Input: ["apple", "apricot", "april"] Output: "ap" Why this approach works well: – Sorting reduces comparisons to just two strings – Efficient and easy to implement – Time Complexity: O(n log n + m) Key learnings from Day 43: – String comparison techniques – Using sorting to simplify problems – Handling edge cases effectively – Writing optimized and clean logic #100DaysOfCode #Day43 #Python #PythonProgramming #Strings #Algorithms #ProblemSolving #CodingPractice #DataStructures #InterviewPrep #LearnByDoing #DeveloperGrowth #ProgrammingJourney #ComputerScience #BTech #CSE #AIandML #VITBhopal #TechJourney
Python Longest Common Prefix Algorithm
More Relevant Posts
-
Day 47 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to find a peak element in an array. A peak element is an element that is greater than or equal to its neighbors. What the program does: • Takes an array as input • Finds any peak element in the array • Handles edge cases (first and last elements) • Returns the peak value How the logic works: • If the array is empty → return None • If it has only one element → return that element • Check the first element: – If it is greater than or equal to the next element → it's a peak • Check the last element: – If it is greater than or equal to the previous element → it's a peak • Traverse the array from index 1 to n-2: – If an element is greater than or equal to both neighbors → return it • If no peak is found (rare case), return None Example: Input: [1, 3, 20, 4, 1, 0] Output: 20 Another example: Input: [1, 2, 3, 4, 5] Output: 5 Another example: Input: [5, 4, 3, 2, 1] Output: 5 Why this approach works: – Checks boundary conditions properly – Works for increasing and decreasing arrays – Time Complexity: O(n) Key learnings from Day 47: – Handling edge cases in arrays – Comparing neighboring elements – Writing clean traversal logic – Strengthening problem-solving skills #100DaysOfCode #Day47 #Python #PythonProgramming #Arrays #Algorithms #ProblemSolving #CodingPractice #DataStructures #InterviewPrep #LearnByDoing #DeveloperGrowth #ProgrammingJourney #ComputerScience #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Day 49 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to find the Equilibrium Index of an array. An equilibrium index is an index where the sum of elements on the left is equal to the sum of elements on the right. What the program does: • Takes an array as input • Finds an index where left sum = right sum • Returns the index if found • Returns -1 if no such index exists How the logic works: • Calculate the total sum of the array • Initialize left_sum = 0 • Traverse the array using enumerate() • For each element: – Right sum = total_sum - left_sum - current element – If left_sum == right_sum, return the index • Add the current element to left_sum • If no equilibrium index is found, return -1 Example: Input: [-7, 1, 5, 2, -4, 3, 0] Output: 3(Left sum = Right sum = 1) Another example: Input: [1, 2, 3] Output: -1 (No equilibrium index) Another example: Input: [1, 0, -1] Output: 1 Why this approach is efficient: – Uses prefix sum concept – Avoids nested loops – Time Complexity: O(n) Key learnings from Day 49: – Understanding prefix sums – Optimizing from brute force to O(n) – Working with running totals – Strengthening array problem-solving #100DaysOfCode #Day49 #Python #PythonProgramming #Arrays #PrefixSum #Algorithms #DataStructures #ProblemSolving #CodingPractice #InterviewPrep #LearnByDoing #ProgrammingJourney #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
Day 46 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to move all zeros in an array to the end while maintaining the order of non-zero elements. This is a common problem that helps in understanding the two-pointer technique and in-place array manipulation. What the program does: • Takes an array as input • Moves all zero elements to the end • Maintains the relative order of non-zero elements • Performs the operation in-place (no extra space) How the logic works: • Initialize a pointer non_zero_ptr to track the position of the next non-zero element • Traverse the array from left to right • If the current element is non-zero: – Place it at non_zero_ptr position – Increment non_zero_ptr • After placing all non-zero elements, fill the remaining positions with zeros • Return the modified array Example: Input: [0, 1, 0, 3, 12] [0, 0, 1, 0, 3, 0, 0, 12, 0] [1, 2, 3, 4, 5] Output: [1, 3, 12, 0, 0] [1, 3, 12, 0, 0, 0, 0, 0, 0] [1, 2, 3, 4, 5] Why this approach is efficient: – Uses two-pointer technique – No extra space required (in-place) – Time Complexity: O(n) Key learnings from Day 46: – Understanding two-pointer approach – Performing in-place array operations – Maintaining order while modifying arrays – Writing optimized and clean code #100DaysOfCode #Day46 #Python #PythonProgramming #TwoPointers #Arrays #Algorithms #DataStructures #ProblemSolving #CodingPractice #InterviewPrep #LearnByDoing #ProgrammingJourney #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 7 – LeetCode Journey Today’s problem: String to Integer (atoi) This one really tested my understanding of edge cases and string parsing. Not just coding, but thinking like a machine step-by-step 👇 ✅ Ignored leading whitespaces ✅ Handled positive & negative signs ✅ Extracted numbers until non-digit appears ✅ Managed overflow within 32-bit integer range At first, it looked simple… but the edge cases made it interesting 😅 💡 Key Learning: Writing code is one thing, but handling all possible inputs correctly is what truly matters in real-world problems. Slowly getting better at breaking down problems and building clean logic 💻🔥 On to Day 8… 🚀 #Day7 #LeetCode #CodingJourney #Python #ProblemSolving #Consistency #LearningEveryday
To view or add a comment, sign in
-
-
✅ Day 92 of 100 Days LeetCode Challenge Problem: 🔹 #2011 – Final Value of Variable After Performing Operations 🔗 https://lnkd.in/gX-JQNUJ Learning Journey: 🔹 Today’s problem was about evaluating a sequence of increment and decrement operations. 🔹 I initialized a variable ans = 0 to track the value. 🔹 Used a hashmap to map each operation to its effect: • "++X" and "X++" → +1 • "--X" and "X--" → -1 🔹 Iterated through the operations and updated ans accordingly. 🔹 Returned the final computed value. Concepts Used: 🔹 HashMap / Dictionary 🔹 String Matching 🔹 Simple Simulation Key Insight: 🔹 Instead of using multiple condition checks, mapping operations to values simplifies logic and improves readability. Complexity: 🔹 Time: O(n) 🔹 Space: O(1) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
🚀 Day 82 – Strengthening Python Foundations 🐍 Today’s focus was on revisiting and revising the basics of Python, right up to comprehensions. Reinforcement of fundamentals is not just repetition — it’s about building clarity, confidence, and precision for advanced problem‑solving. 🔹 Core Syntax Refreshed – Variables, operators, and expressions, ensuring fluency in the language’s building blocks. 🔹 Control Flow Mastery – Conditionals and loops revisited, sharpening logical thinking and structured problem‑solving. 🔹 Functions & Scope – Re‑examined how modular code works, reinforcing the importance of reusability and clarity. 🔹 Data Structures – Lists, tuples, sets, and dictionaries revised with practical examples, strengthening understanding of storage and retrieval. 🔹 Comprehensions – Explored list, set, and dictionary comprehensions, appreciating how they transform verbose loops into elegant, Pythonic one‑liners. 🌱 Reflection – Revisiting basics is like polishing the foundation stones of a building. Each concept feels sharper, cleaner, and more intuitive, preparing me for deeper explorations in algorithms, problem‑solving, and real‑world applications. ⚡ Day 82 was about consolidation — turning knowledge into confidence, and confidence into readiness for the next leap forward. #Day82 #PythonLearning #CodingJourney #100DaysOfCode #LearnInPublic #10000Coders
To view or add a comment, sign in
-
🐍 Day 8 of Learning Python — and things are getting real! Today's lab was all about writing code that doesn't break (or at least fails gracefully 😄). Here's what I worked through: ✅ Exception Handling — try / except / else / finally • Caught ZeroDivisionError, FileNotFoundError, ValueError, and TypeError • Used `raise` to throw custom error messages • Built my own exception class: TooSmallError 🎉 ✅ Standard library deep dive: • math — calculated circle areas, factorials, GCD, and compound interest • random — shuffled lists, simulated 1000 coin flips, generated reproducible sequences with seed() • datetime — parsed date strings, added time deltas, sorted ISO dates, and printed 5-day schedules ✅ Introspection with dir() and help() The biggest lesson today? Real-life programs don't always get perfect input. Learning to handle errors gracefully is just as important as writing the happy path. Day by day, the pieces are coming together. 💪 #Python #100DaysOfCode #LearningToCode #PythonProgramming #CodingJourney #Day8
To view or add a comment, sign in
-
💭 Day 6 with Python… it finally felt useful. Until now, I was learning concepts… Conditions, loops, functions… all great. But today, something changed. 👉 I learned about lists. At first, it looked simple: A collection of values in one place. But then I realized… This is how real-world data is handled. Names. Numbers. Marks. Tasks. Everything can be stored, accessed, and managed easily. 💡 Instead of writing separate variables like: name1, name2, name3… I could simply do: 👉 names = ["A", "B", "C"] Cleaner. Smarter. Scalable. So I tried something small 👇 🚀 Mini use-case: I created a list of numbers ✔ Found the largest number ✔ Calculated the sum ✔ Even filtered values And suddenly… It didn’t feel like practice anymore. It felt like solving real problems. 🐍 That’s when it clicked: Python isn’t just for coding exercises… It’s for handling real data in real situations. ✨ From concepts → to practical thinking This journey is slowly becoming meaningful. #Python #CodingJourney #Day6 #Lists #DataHandling #LearnToCode #ProgrammingLife #TechSkills #Growth 🚀
To view or add a comment, sign in
-
Day 6 of my Python learning journey: Focusing on writing code that's not just functional, but also dependable. Highlights from today: - Warmed up by practicing iterators and generators. - Solved the "First Non-Repeating Character" problem using a clean two-pass frequency approach with O(n) complexity. - Merged two sorted arrays efficiently through the two-pointer technique (O(n + m))—avoiding any redundant sorting. - Developed a FastAPI endpoint for the above problem, complete with schema validation. Observations: Initially, I attempted a one-pass solution for the non-repeating character problem, but it ended up feeling convoluted. Switching to a two-pass strategy made the solution much more straightforward and maintainable. Current focus areas: - Maintaining input order integrity. - Performing input validation early on. - Keeping logic as simple as possible. - Thoroughly testing edge cases beforehand. Major takeaway: Define inputs/outputs upfront → validate data early → then prioritize optimization. Starting to grasp how even minor design decisions can significantly impact code quality. GitHub link: https://lnkd.in/gGPw8_js #Python #FastAPI #ProblemSolving #SoftwareEngineering #CleanCode #LearningInPublic #OOP #Testing
To view or add a comment, sign in
-
-
🚀 Day 16 Task – Python Mini Challenge Today’s task was a simple yet powerful exercise to strengthen my looping and conditional logic skills. 🔹 Task: Given a list of numbers, calculate the sum of even and odd numbers separately. 🔹 What I implemented: ✔️ Method 1: Stored even & odd numbers in separate lists and used sum() ✔️ Method 2: Calculated sums directly using variables (more optimized approach) 🔹 Key takeaway: There’s always more than one way to solve a problem. Writing multiple approaches helps in understanding efficiency and clean coding practices. 🔹 What I learned deeply: Using loops effectively Applying conditional logic (if-else) Writing optimized solutions instead of relying only on extra space github link : https://lnkd.in/g4iZcnGt 📌 Completed the task and tested it with different inputs successfully. Building consistency, one problem at a time 💪🚀 #Python #100DaysOfCode #Coding #ProblemSolving #DeveloperJourney #LearnInPublic Codegnan BhanuTeja Garikapati
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