Python Array Duplicate Checker with Hashing

Day 45 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to check if an array contains duplicates within a given distance k. This problem is widely asked in interviews and helps in understanding hashing and efficient lookups. What the program does: • Takes an array and an integer k as input • Checks if any duplicate elements exist within distance k • Returns True if such duplicates exist • Otherwise returns False How the logic works: • A dictionary (num_indices) is used to store the last seen index of each number • Traverse the array using enumerate() • For each element: – If it already exists in the dictionary – Check the distance between indices • If the difference is ≤ k, return True • Otherwise, update the index of the current element • If no such pair is found, return False Example: Input: nums = [1, 2, 3, 1], k = 3 Output: True (duplicate 1 found within distance 3) Another example: Input: nums = [1, 2, 3, 4, 5], k = 2 Output: False Another example: Input: nums = [1, 0, 1, 1], k = 1 Output: True Why this approach is efficient: – Uses hashing for constant-time lookup – Time Complexity: O(n) – Space Complexity: O(n) Key learnings from Day 45: – Using dictionaries for fast lookups – Understanding index-based conditions – Applying hashing in real problems – Writing optimized solutions for interviews #100DaysOfCode #Day45 #Python #PythonProgramming #Hashing #SlidingWindow #DataStructures #Algorithms #ProblemSolving #CodingPractice #InterviewPrep #LearnByDoing #ProgrammingJourney #DeveloperGrowth #BTech #CSE #AIandML #VITBhopal #TechJourney

  • text

To view or add a comment, sign in

Explore content categories