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
Python Equilibrium Index Program #100DaysOfCode
More Relevant Posts
-
🚀 Day 65 of My Python & DSA Journey Today’s problem was Word Pattern (290) — a great exercise in understanding mapping and relationships between data. 🔍 Problem Solved: Given a pattern and a string, determine if the string follows the same pattern with a one-to-one mapping (bijection) between characters and words. 💡 Approach Used: • Split the string into words • Use two hashmaps (dictionaries): • One for character → word • One for word → character • Ensure consistency in both mappings while iterating ⚡ Key Learnings: • Concept of bijection (one-to-one mapping) • Using hashmaps for efficient lookups • Handling edge cases like unequal lengths • Writing clean validation logic 📊 Complexity Analysis: ✅ Time Complexity: O(n) We traverse the pattern and words once ✅ Space Complexity: O(n) For storing mappings 🎯 Why This Works? Using two dictionaries ensures no duplicates or conflicts, maintaining a strict one-to-one relationship. Another step closer to mastering problem-solving patterns! Under the Guidance of: Rudra Sravan kumar and Manoj Kumar Reddy Parlapalli #Day65 #Python #LeetCode #DSA #Algorithms #CodingJourney #100DaysOfCode #10000Coders 🚀
To view or add a comment, sign in
-
-
Day 22 of my DSA journey Today I worked on the Sliding Window technique. It is a useful optimization approach for problems involving subarrays or substrings. Instead of recalculating values repeatedly, it helps reuse previous computations and reduces time complexity. Problem: Maximum Sum Subarray of Size K Given an array of integers and a number k, find the maximum sum of any contiguous subarray of size k. Brute Force Approach: Check all possible subarrays of size k and calculate their sums. Time Complexity: O(n²) Optimized Approach (Sliding Window): Calculate the sum of the first window of size k Slide the window by one element at a time Add the next element and remove the previous element from the sum Track the maximum sum Python Code: def max_sum_subarray(arr, k): window_sum = sum(arr[:k]) max_sum = window_sum for i in range(k, len(arr)): window_sum += arr[i] window_sum -= arr[i-k] max_sum = max(max_sum, window_sum) return max_sum arr = [2, 1, 5, 1, 3, 2] k = 3 print(max_sum_subarray(arr, k)) Time Complexity: O(n) Space Complexity: O(1) Learning: Sliding Window significantly improves performance in problems related to subarrays and substrings. I will practice more variations like variable window size and string-based problems next. #DSA #CodingJourney #SlidingWindow #Python #100DaysOfCode
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
-
-
Today's topic: recursion. A function that calls itself. Sounds simple, right? Here are two ways to add up a list of numbers: Without recursion — honest, reliable, easy to follow: python def suma(lista): suma = 0 for i in range(0, len(lista)): suma = suma + lista[i] return suma print(suma([6,3,4,2,10])) # 25 With recursion — elegant, almost poetic... and a little terrifying: python def suma(lista): if len(lista) == 1: return lista[0] else: return lista[0] + suma(lista[1:]) print(suma([6,3,4,2,10])) # 25 Same result. Two completely different roads to get there. The recursive version looks more "pro" — but if you forget to define when it stops, the function calls itself forever. Literally. Forever. 💀 So yes, it's getting challenging. And yes, recursion feels more elegant to write. But I'm not ready to fully trust something that could loop into oblivion if I blink wrong. Lesson of the day: simple is not the same as bad. And documenting the moments that confuse you? That's part of learning too. #Python #LearningToCode #DaysOfCode #PythonProgramming #CodingJourney #Recursion #BeginnerCoder #TechLearning #CodeNewbie #LinkedInLearning
To view or add a comment, sign in
-
-
Week 4 of #100DaysOfCode — done! 🎉 Last week I learned how to build classes. This week I learned how to make them talk to each other. Topics covered: 🧹 Inheritance → Superclass, subclass, base class — and what they actually mean → How Python finds attributes (spoiler: it walks up the chain) → Overriding methods — and extending them with super() → isinstance, issubclass, type — when to use which → Multiple inheritance + MRO (Method Resolution Order) 🏗️ Abstract Classes & Interfaces → ABC + @abstractmethod — enforcing a contract on subclasses → Duck typing — "if it has a speak() method, it speaks" → Subclassing built-ins (list, dict, iterator) → Mixins — plugging in behaviour without full inheritance I’ve structured my learning into notes and practical examples to better understand the concepts : https://lnkd.in/epaBymnJ #100DaysOfCode #Python #OOP #LearningInPublic #Programming
To view or add a comment, sign in
-
This week I didn't just write code. I understood what's happening inside it. Here's a recursive function I built 👇 It calculates hotel earnings for N days at ₹5000/day — no loops allowed, only recursion. Watch how Python actually executes it step by step 🎥 What I covered this week: → 🔁 Recursion — functions calling themselves → 📁 File I/O — reading & writing files with Python → 🌐 Internet fundamentals — TCP/IP, HTTP, DNS, REST APIs (Phase 4 done!) Still learning. Still showing up. That's the only formula I know. 💪 💻 Visualization tool: staying.fun 🐍 Language: Python #Python #LearningInPublic #DataAnalytics #Recursion #BBA #100DaysOfCode
To view or add a comment, sign in
-
Weekly Challenge 14: Nearest Neighbor For Week 14 of my Python challenge, I decided to practice some real-life optimization by combining my Master's degree homework with my weekly coding goal. I implemented the Nearest Neighbor Heuristic to solve the Traveling Salesperson Problem (TSP). This is a classic "Greedy" algorithm. The logic is simple but powerful: 1.- Start at a location. 2.- Look around and go to the closest unvisited point. 3.- Repeat until all points are visited. 4.- Return home. It might not always find the perfect global minimum, but it finds an incredibly efficient route in $O(n^2)$ time, making it practical for real-world logistics and routing problems. I used NumPy for the vector math and Matplotlib to visualize the exact path the algorithm took. Full source code on my GitHub: https://lnkd.in/g6RqgJDp #Python #OperationsResearch #Optimization #Algorithms #DataScience #TSP #GreedyAlgorithms #CodingChallenge #MastersDegree
To view or add a comment, sign in
-
🚀 Solved: Group Anagrams Problem (LeetCode) Today I worked on an interesting problem — grouping anagrams efficiently using Python. 💡 Approach: I used a hashmap (dictionary) where: The key is the sorted version of each word The value is a list of words (anagrams) matching that key Example: "eat", "tea", and "ate" → all become "aet" after sorting → grouped together 🧠 Key Insight: Sorting each string gives a unique identifier for all its anagrams. ⚙️ Time Complexity: Sorting each word takes O(k log k) For n words → O(n * k log k) 📦 Space Complexity: O(n * k) for storing grouped anagrams ✅ Result: Accepted ✔️ Runtime: 5 ms (faster than ~99% submissions) 📈 Growth & Consistency: Improving step by step by solving problems daily and focusing on writing clean and optimized code. Small consistent efforts are helping me build stronger problem-solving skills and deeper understanding of DSA. 🔁 Staying consistent is the real game changer! #Python #DSA #LeetCode #Coding #ProblemSolving #Consistency #Growth #LearningJourney
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 10/365: Building a List from User Input & Finding Basic Stats 🔢📥 Today I wrote a Python program that takes numbers from the user, stores them in a list, and then calculates some basic statistics: sum, average, minimum, and maximum. What the code does step by step: First, I ask the user how many elements they want to enter and store that in n. I create an empty list l and a variable total to keep track of the sum. Using a for loop, I take n inputs from the user: Each number is added to the list using append(). At the same time, I keep adding each number to total to calculate the sum. After the loop: I print the full list. I print the sum using the total variable. Then I calculate the average as total / n and print it. To find the minimum and maximum: I start by assuming both min and max are the first element of the list. I loop through the list and update min if I find a smaller value. Similarly, I update max if I find a larger value. In the end, I print the minimum and maximum numbers in the list. What I learned from this exercise: How to take multiple inputs from a user and store them in a list. How to maintain a running sum while taking inputs. How to manually compute average, minimum, and maximum without using built‑in functions like sum(), min(), or max(). How loops and variables can work together to build simple but useful statistics — a basic idea used a lot in data analysis. Day 10 done ✅ 355 more to go. If you have ideas like extending this to find median, mode, or standard deviation, send them to me — I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #LogicBuilding #Lists #UserInput #CodingJourney #LearnInPublic #AspiringDeveloper
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