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
Python Array Duplicate Checker with Hashing
More Relevant Posts
-
Day 63 of my #100DaysOfCode challenge 🚀 Today I worked on generating all permutations of a string using recursion in Python. This is a fundamental problem to understand recursion + backtracking patterns, and it's very common in coding interviews. What the program does: • Takes a string as input • Generates all possible permutations • Uses recursive approach (no built-ins like itertools) • Returns all arrangements of characters Example (Input: "abc"): Permutations:['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] Total permutations: 6 How the logic works: Recursive idea: 1. Fix one character at a time 2. Find permutations of remaining string 3. Combine fixed character with each permutation 4. Repeat until only one character is left Example breakdown: Fix 'a' → permute "bc" Fix 'b' → permute "ac" Fix 'c' → permute "ab" Why this is important: – Core concept for recursion & backtracking – Used in problems like: Anagrams Password generation Combination problems – Frequently asked in interviews – Builds strong problem-solving mindset Time Complexity: O(n!) Space Complexity: O(n!) Key Takeaways: – Recursive problem decomposition – Understanding permutations logic – Building solutions step-by-step – Avoiding built-in shortcuts for clarity #100DaysOfCode #Day63 #Python #Programming #Recursion #Backtracking #Permutations #Strings #Algorithms #DSA #CodingPractice #ProblemSolving #InterviewPrep #LearnByDoing #DeveloperJourney #Consistency #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
-
-
Earlier this week, I wrote about the developer loop - learn, practice, apply, repeat. So I put it into practice. Just staying sharp, working through DSA problems in Python. Came across max_subarray_sum. Solved it. Moved on. Then I went back to see how other people approached it… and ran into Kadane’s algorithm : ``` def max_subarray_sum(nums): max_sum = current_sum = nums[0] for num in nums[1:]: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum ``` Same problem. Cleaner logic. O(n) instead of brute force. Here's what I'm trying to say: going back to problems you’ve already solved might feel like you’re wasting time… but you’re not. It isn't. Sometimes it’s only when you revisit something with a fresh mind that you actually see better approaches you missed the first time. There’s almost always more than one way to solve a problem. Which one is "best"? That's a conversation for another day. What’s something you revisited and understood completely differently the second time? #Python #DSA #SoftwareEngineering #DeveloperLife #TechCanada
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
-
-
Day 64 of my #100DaysOfCode challenge 🚀 Today I worked on generating all combinations of a string using Python’s itertools module. This is an important concept in combinatorics and widely used in problem-solving and interviews. What the program does: • Takes a string as input • Generates all possible combinations (subsets) • Uses itertools.combinations() • Prints combinations of all lengths Example (Input: "abc"): All combinations: a b c ab ac bc abc How the logic works: Step-by-step: 1. Loop from length = 1 to n 2. Generate combinations of each length 3. Join characters into strings 4. Store and print results It systematically builds all possible subsets ✔️ Why this is important: – Core concept in combinatorics – Used in problems like: Subset generation Feature selection Probability problems – Frequently asked in interviews – Helps understand power set logic Time Complexity: O(2ⁿ) Space Complexity: O(2ⁿ) Key Takeaways: – Understanding combinations vs permutations – Using Python’s powerful itertools – Generating subsets efficiently – Clean and readable implementation #100DaysOfCode #Day64 #Python #Programming #Combinations #Itertools #Algorithms #DSA #CodingPractice #ProblemSolving #InterviewPrep #LearnByDoing #DeveloperJourney #Consistency #BTech #CSE #AIandML #VITBhopal #TechJourney
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 34 #50DaysOfCodingChallenge Extracting Digits from a File using Python Today I worked on a simple but powerful file-processing problem. Here’s a breakdown of how my code works step by step 👇 🔹 1. Function Definition I created a function: def just_digits(file_path): This allows me to reuse the logic for any file path. 🔹 2. Open the File fr = open(file_path, "r", encoding="utf-8") Opens the file in read mode Uses UTF-8 encoding to avoid errors with special characters 🔹 3. Loop Through Each Line for line in fr Reads the file line by line instead of loading everything at once 🔹 4. Split Line into Words line.split() Breaks each line into individual words using spaces 🔹 5. Clean Each Word w.strip('.,“”"') Removes punctuation like commas, periods, and quotes Helps isolate pure numeric values 🔹 6. Check for Digits if w.strip(...).isdigit() Ensures only numbers are selected Filters out all text 🔹 7. List Comprehension Magic ✨ [ ... for line in fr for w in line.split() if ... ] Combines looping + filtering into one clean line Efficient and Pythonic way to process data 🔹 8. Return Result The function returns a list of numbers (as strings) 🔹 9. Function Call print(just_digits("python.csv")) Executes the function and prints output ✅ Final Output: ['1991', '2', '2000', '3', '2008'] 🚀 Key Learnings: Handling file encoding errors (UTF-8) Using .isdigit() for filtering data Writing compact logic using list comprehension Cleaning raw text data effectively Grateful for the guidance and support from Sajay N J Sir, Chithirakrishna Mv Ma'am and Neethu Unni M Ma'am. #Python #CodingChallenge #LuminarTechnolab
To view or add a comment, sign in
-
-
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
To view or add a comment, sign in
-
-
Small confession: I’ve never really liked Python’s .title(). It seems fine at first, but the more you use it, the more little issues show up. Acronyms get mangled, edge cases slip through, and your nicely formatted text starts looking slightly off. After running into this a few times, I ended up writing a version that behaves closer to what I expect: title_case = lambda s: re.sub( r"[A-Za-z]+(?:'[A-Za-z]+)?", lambda m: ( lambda w, b: w if re.fullmatch(r"[A-Z]+(\.[A-Z]+)*\.?", b) else w if not (b.islower() or b.isupper()) else w.capitalize() )(m.group(0), m.group(0).split("'")[0]), s ) It is simple, but it handles a few things better for my use cases: • Keeps acronyms like “NASA” and “U.S.A.” intact • Leaves mixed-case words as they are • Handles basic apostrophes more cleanly It is not perfect, but it works better for the cases I run into most often. It also made me realize that built-in functions are not always the best fit. Sometimes you need something slightly different for your own context. Curious to hear, what is a built-in function you have replaced or wrapped because it did not quite do what you needed? #Python #Programming #SoftwareDevelopment #Coding #DeveloperLife #AIWithAnishArya
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