Day 20 of my Python learning journey Today I worked on a problem that completely changed how I look at arrays. At first, it looked like a normal question… But the solution came from a linked list concept. Problem: Find the Duplicate Number (O(1) Space) You are given an array of size n + 1 containing numbers from 1 to n. There is only one duplicate number, but it can appear multiple times. Find the duplicate without modifying the array and using constant space. Example: arr = [1, 3, 4, 2, 2] Output: 2 What I tried first: Using a set → works but uses extra space Sorting → modifies the array Both were not allowed. What I learned today: We can treat the array like a linked list. Each index → node Value → next pointer This creates a cycle, and the duplicate number is where the cycle starts. Optimized approach: Floyd’s Cycle Detection Slow pointer moves 1 step Fast pointer moves 2 steps Step 1: Find the meeting point inside the cycle Step 2: Find the starting point of the cycle (duplicate) Code: def findDuplicate(arr): # Step 1: Detect cycle (meeting point) slow = arr[0] fast = arr[0] while True: slow = arr[slow] fast = arr[arr[fast]] if slow == fast: break # Step 2: Find cycle start (duplicate) slow = arr[0] while slow != fast: slow = arr[slow] fast = arr[fast] return slow # Example arr = [1, 3, 4, 2, 2] print(findDuplicate(arr)) Problems I faced while solving this: I could not understand how an array can behave like a linked list The idea of cycle detection in arrays felt confusing I kept going back to sorting and hashing methods What I finally understood: This problem is not about arrays… It’s about recognizing hidden patterns. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do fast and slow pointers always meet inside a cycle? Today’s realization: Sometimes the solution is not in the data structure you see… but in the one you don’t see at first. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
Finding Duplicate in Array with O(1) Space
More Relevant Posts
-
Day 18 of my Python learning journey Today I tried another good problem based on the Two Pointer technique. Problem: Merge Sorted Array Given two sorted arrays, merge them into one sorted array. Example: arr1 = [1, 3, 5] arr2 = [2, 4, 6] Output: [1, 2, 3, 4, 5, 6] What I understood: Since both arrays are already sorted, we do not need to sort again. We can compare elements from both arrays and place the smaller one first. Better approach (Two Pointer): One pointer for arr1 One pointer for arr2 Compare both values Add the smaller value to the result Code I wrote: arr1 = [1, 3, 5] arr2 = [2, 4, 6] i = 0 j = 0 result = [] while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 while i < len(arr1): result.append(arr1[i]) i += 1 while j < len(arr2): result.append(arr2[j]) j += 1 print(result) Problems I faced while coding this: At first I thought I had to combine both arrays and then sort them. I was confused about why two pointers are enough. I also forgot to handle the remaining elements after one array finishes. What I finally understood: Because both arrays are sorted, we can merge them in one pass. This saves extra sorting work and makes the solution efficient. Time and Space Complexity: Time Complexity: O(n + m) Space Complexity: O(n + m) Question: What will be the output for: arr1 = [1, 2, 7] arr2 = [3, 4] Today’s realization: Sometimes the best solution is not creating something new, but combining what is already ordered. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Day 17 of my Python learning journey Today I tried another interesting problem using the Two Pointer technique. Problem: Valid Palindrome Given a string, check if it can become a palindrome after removing at most one character. Example: s = "abca" Output: True Because removing 'c' makes it "aba" which is a palindrome. What I understood: We need to check if the string is almost a palindrome, allowing one mistake. Better approach (Two Pointer): Start one pointer from left Start one pointer from right If characters match → move both pointers If mismatch → try skipping one character (either left or right) Code I wrote: def is_palindrome(s, left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True s = "abca" left = 0 right = len(s) - 1 while left < right: if s[left] != s[right]: if is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1): print(True) else: print(False) break left += 1 right -= 1 else: print(True) Problems I faced while coding this: At first I tried removing every character and checking, which was inefficient. I was confused about which character to remove when mismatch happens. Writing a helper function for checking palindrome took some time to understand. What I finally understood: At the first mismatch, we only need to try two cases: skip left character skip right character If any one works, the string is valid. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: What will be the output for: s = "abc" Today’s realization: Sometimes solving a problem is about allowing one controlled mistake. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Day 11 of Python Learning: Loops and Patterns in Python Today I practiced loops in Python and learned how to create patterns using nested loops. This helps improve logic building and problem-solving skills. 🔹 What are Patterns? Patterns are shapes or number/star designs created using loops. They are great for understanding loop control and nested loops. 🔸 Using For Loop for i in range(5): print("*") 🔸 Star Pattern Example for i in range(1, 6): print("*" * i) Output: * ** 🔸 Number Pattern Example for i in range(1, 6): for j in range(1, i + 1): print(j, end=" ") print() 💡 Key Learning: Nested loops are useful when one loop runs inside another loop, especially for patterns and matrix-style problems. 🧪 Practice Task: ✔ Print reverse star pattern ✔ Print square pattern using stars ✔ Print number triangle pattern ✔ Try same patterns using while loop 🎯 Interview Question: What is a nested loop in Python? Answer: A nested loop is a loop inside another loop. It is used when repeated iterations are needed within each cycle of the outer loop. 📌 Day 11 completed — logic building step by step! #Python #Learning #CodingJourney #Day11 #Programming #SDET #100DaysOfCode Masai #dailyleaning #masaiverse
To view or add a comment, sign in
-
Day 11 of my Python learning journey Today I tried solving the Two Sum problem using the Two Pointer technique. Before this, I was only solving Two Sum using a dictionary. But today I learned another approach that works when the array is sorted. Problem: Two Sum (Two Pointer Approach) Given a sorted array and a target value, find two numbers whose sum equals the target. Example: nums = [1, 2, 4, 6, 10] target = 8 Output: [2, 6] Because 2 + 6 = 8. What is the Two Pointer technique? Two pointers means using two positions in the array: one pointer starts from the left side one pointer starts from the right side Then we move them based on the sum. How it works: • If the sum is too small, move the left pointer forward • If the sum is too large, move the right pointer backward • If the sum equals the target, we found the answer Code: nums = [1, 2, 4, 6, 10] target = 8 left = 0 right = len(nums) - 1 while left < right: s = nums[left] + nums[right] if s == target: print(nums[left], nums[right]) break elif s < target: left += 1 else: right -= 1 Problems I faced while coding this: At first I did not understand why the array needs to be sorted. I was confused about when to move the left pointer and when to move the right pointer. I also tried using this method on an unsorted array and it did not work. What I finally understood: The Two Pointer technique works well when the array is sorted because it lets us adjust the sum efficiently without checking every pair. This reduces the time complexity compared to nested loops. Question: Would this approach still work if the array was not sorted? #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Day 16 of my Python learning journey Today I tried another interesting problem using the Two Pointer technique. Problem: Squares of a Sorted Array Given a sorted array, return a new array of the squares of each number, also sorted. Example: arr = [-4, -1, 0, 3, 10] Output: [0, 1, 9, 16, 100] What I understood: Even though the array is sorted, squaring negative numbers can break the order. So we cannot directly square and sort. Better approach (Two Pointer): Left pointer at start Right pointer at end Compare squares of both ends Place the larger square at the end of result array Code I wrote: arr = [-4, -1, 0, 3, 10] n = len(arr) result = [0] * n left = 0 right = n - 1 pos = n - 1 while left <= right: if abs(arr[left]) > abs(arr[right]): result[pos] = arr[left] * arr[left] left += 1 else: result[pos] = arr[right] * arr[right] right -= 1 pos -= 1 print(result) Problems I faced while coding this: At first I tried squaring and sorting, but it increased time complexity. I was confused about why we compare absolute values. The idea of filling the result array from the end was not clear initially. Managing three pointers (left, right, pos) felt tricky. What I finally understood: The largest square will always come from either end of the array. So we place it at the end and move inward. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(n) Question: Why do we fill the result array from the end instead of the beginning? Today’s realization: Sometimes the trick is not in solving directly, but in thinking from the result side. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Day 16 of Python Learning: Polymorphism in Python Today I learned about Polymorphism in Python — an important Object-Oriented Programming (OOP) concept where the same method name can behave differently for different objects. 🔹 What is Polymorphism? Polymorphism means "many forms." It allows one interface or method name to perform different actions based on the object. 🔸 Method Overriding Example class Animal: def sound(self): print("Animal makes sound") class Dog(Animal): def sound(self): print("Dog barks") class Cat(Animal): def sound(self): print("Cat meows") dog = Dog() cat = Cat() dog.sound() cat.sound() 🔸 Built-in Polymorphism Example print(len("Python")) print(len([1, 2, 3, 4])) 💡 Key Learning: The same method can behave differently depending on which object is calling it. 🧪 Practice Task: ✔ Create Shape class ✔ Create Circle and Rectangle classes ✔ Add area() method in both classes ✔ Call same method with different outputs 🎯 Interview Question: What is the difference between inheritance and polymorphism? Answer: Inheritance is used to reuse code from parent class, while polymorphism allows the same method name to perform different behaviors. 📌 Day 16 completed — understanding smarter OOP concepts! #Python #Learning #CodingJourney #Day16 #Programming #SDET #100DaysOfCode Masai #dailylearning #masaiverse
To view or add a comment, sign in
-
Day 15 of my Python learning journey: Today I tried a problem with a very interesting name. Problem: Container With Most Water The name itself made me curious. You are given an array where each element represents the height of a vertical line. You have to find two lines such that they form a container that can hold the maximum amount of water. Example: arr = [1,8,6,2,5,4,8,3,7] Output: 49 What I understood: The amount of water depends on: width (distance between two lines) height (minimum of the two lines) Water = width × min(height) Better approach (Two Pointer): Start one pointer from the left Start one pointer from the right Then: • Calculate area • Move the pointer with smaller height Code I wrote: arr = [1,8,6,2,5,4,8,3,7] left = 0 right = len(arr) - 1 max_area = 0 while left < right: width = right - left height = min(arr[left], arr[right]) area = width * height if area > max_area: max_area = area if arr[left] < arr[right]: left += 1 else: right -= 1 print(max_area) Problems I faced while coding this: At first I tried checking all pairs, which was too slow. I did not understand why we move the pointer with smaller height. It felt wrong to ignore some pairs, but the logic still worked. What I finally understood: Moving the smaller height pointer helps us try to find a better height while reducing width. This avoids unnecessary comparisons and makes the solution efficient. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do we always move the pointer with the smaller height? Today’s realization: Sometimes the best solution is not checking everything, but skipping the right things. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Day 25 of my Python learning journey Today I solved one of the most important sliding window problems. Problem: Longest Repeating Character Replacement Given a string s and an integer k, you can replace at most k characters. Find the length of the longest substring that can be made of the same character. Example: s = "AABABBA" k = 1 Output: 4 Because we can make "AABA" or "ABBA" → length = 4 What I tried first: Generate all substrings Count frequency each time Time Complexity → O(n²) ❌ Better approach: Sliding Window + Frequency Map Expand window using right Track max frequency inside window If window becomes invalid → shrink from left Code I wrote: s = "AABABBA" k = 1 count = {} left = 0 max_freq = 0 max_len = 0 for right in range(len(s)): count[s[right]] = count.get(s[right], 0) + 1 max_freq = max(max_freq, count[s[right]]) # condition: window size - max_freq > k if (right - left + 1) - max_freq > k: count[s[left]] -= 1 left += 1 max_len = max(max_len, right - left + 1) print(max_len) Problems I faced: I didn’t understand why we track only max_freq Confused about the condition (window size - max_freq > k) Thought we need to check all characters every time What I finally understood: We don’t need all frequencies… 👉 Only the most frequent character matters Time & Space Complexity: Time: O(n) Space: O(1) (since only 26 characters) Question: Why do we not decrease max_freq when shrinking the window? Today’s realization: Optimization is not about tracking everything… it’s about tracking the right thing #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Day 13 of Python Learning: Exception Handling in Python Today I learned how to handle errors in Python using exception handling. This helps programs run smoothly even when unexpected issues occur. 🔹 What is Exception Handling? Exception handling is used to catch errors and prevent the program from crashing. 🔸 Basic Example try: num = 10 / 0 except: print("Error occurred") 🔸 Handling Specific Error try: number = int("abc") except ValueError: print("Invalid input") 🔸 Using Finally Block try: print("Start") except: print("Error") finally: print("This always runs") 🔸 Using Else Block try: print(10 / 2) except: print("Error") else: print("No error found") 💡 Key Learning: Using try-except makes programs more reliable and user-friendly. 🧪 Practice Task: ✔ Handle divide by zero error ✔ Handle invalid number input ✔ Use finally block in one program ✔ Create a safe calculator using try-except 🎯 Interview Question: What is the purpose of finally block in Python? Answer: The finally block always executes whether an error occurs or not. It is commonly used for cleanup tasks like closing files or database connections. 📌 Day 13 completed — learning how professionals handle errors! #Python #Learning #CodingJourney #Day13 #Programming #SDET #100DaysOfCode Masai #masaiverse #dailylearning
To view or add a comment, sign in
-
🚀 Day 27 of My Python Learning Journey 🚀 Today I explored one of the most powerful concepts in Python: Polymorphism. 📌 Topics I Learned: 🔹 Advantages of Polymorphism • Improves code reusability • Makes programs more flexible • Reduces complexity • Helps in writing cleaner and scalable code 🔹 Important Terminologies in Python Polymorphism • Method Overriding • Operator Overloading • Duck Typing • Magic Methods 🔹 Duck Typing Philosophy in Python “If it walks like a duck and talks like a duck, then it is a duck.” 🦆 Python does not care about the object type, it only cares whether the required method or behavior is present. 🔹 Operator Overloading Python allows us to redefine the behavior of operators for user-defined objects. Example: + operator can perform different tasks: • Addition for numbers • Concatenation for strings and lists 🔹 Method Overriding A child class can redefine the method of the parent class with its own implementation. 🔹 Magic Methods Used for Operator Overloading • add() → + • sub() → - • mul() → * • truediv() → / • lt() → < • gt() → > • eq() → == 🔹 Error Associated with + Operator Trying to add incompatible data types gives an error. Example: 5 + "Python" Output: TypeError: unsupported operand type(s) for +: 'int' and 'str' Learning polymorphism made me realize how Python gives flexibility to write smart and dynamic code. Excited to learn more every day! 💻✨ Thanks for your support G.R NARENDRA REDDY sir #Day27 #Python #Polymorphism #DuckTyping #OperatorOverloading #MethodOverriding #MagicMethods #PythonProgramming #CodingJourney #LearningPython #FutureDeveloper
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