Finding Duplicate in Array with O(1) Space

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

  • diagram

To view or add a comment, sign in

Explore content categories