Day 7 of 365 Days of code 🤌 Qn 1):Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Explanation: Use two different pointers, one is going to be a slow pointer and another one will be a fast pointer that moves twice the number of nodes of the slow pointer in a single iteration. If both the pointers meet at a same node, then the linked list consists of a cycle. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
Detecting Cycles in Linked Lists with Two Pointers
More Relevant Posts
-
Day 35 of 365 days of code So far, so good Qn 1) Online stock span approach: decreasing monotonic stack Inside the constructor(__init__ block): initialize an empty stack we are going to use the stack to store the prices and the span Inside the function block(next): 1) set span=1 2) while the stack is not empty and the price at the top of the stack is less than the price: i) span+=stack.pop() 3) push the price and the span, as a tuple inside the stack. 4) return span. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
To view or add a comment, sign in
-
-
🚀 Day 6/30 | LeetCode Problem: Move Zeroes (283) Problem: Given an array nums, move all 0s to the end of the array while maintaining the relative order of non-zero elements. The operation must be done in-place. Approach: Traverse the array once Store all non-zero elements in one list Store all zero elements in another list Combine both lists and update the original array This approach keeps the order intact and is easy to understand. Time Complexity: O(n) Space Complexity: O(n) Python Code: class Solution(object): def moveZeroes(self, nums): a = [] b = [] for i in nums: if i == 0: a.append(i) else: b.append(i) nums[:] = b + a Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Takeaway: Maintaining order while modifying arrays is a common requirement in real-world problems. 📌 Accepted ✅ | All test cases passed 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day6 #Python #Arrays #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
Day 18/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 219 – Contains Duplicate II (Easy) 🧠 Approach: 1. Traverse the array while storing each element’s last index in a dictionary. 2. If the same element appears again and the index difference is ≤ k, return True. 3. If no such pair exists, return False. 💻 Solution: class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: d = {} for i,num in enumerate(nums): if num in d and i-d[num]<=k: return True d[num]=i return False ⏱ Time | Space: O(n) | O(n) 📌 Key Takeaway: Tracking the last seen index of elements allows us to efficiently detect nearby duplicates in a single pass. #leetcode #dsa #python #problemSolving
To view or add a comment, sign in
-
-
🚀 Day 7/30 | LeetCode Problem: First Unique Character in a String (387) Problem: Given a string s, find the first non-repeating character and return its index. If it doesn't exist, return -1. Approach: Use a dictionary to count occurrences of each character Traverse the string a second time to find the first character with count 1 Return its index Time Complexity: O(n) → Two passes over the string Space Complexity: O(1) → Dictionary holds at most 26 letters (for lowercase English letters) Python Code: class Solution: def firstUniqChar(self, s): a = {} for i in s: if i in a: a[i] += 1 else: a[i] = 1 for i in range(len(s)): if a[s[i]] == 1: return i return -1 Example: Input: "leetcode" Output: 0 → 'l' is the first unique character Input: "loveleetcode" Output: 2 → 'v' is the first unique character Takeaway: Counting occurrences is a common technique for string problems and can be applied to many scenarios like finding duplicates, frequency analysis, etc. 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day7 #Python #Strings #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
Recently, I was working on a problem that required dynamically constructing a string. My initial implementation was straightforward and functionally correct. At first glance, it seemed perfectly acceptable. However, upon reviewing the logic more carefully, I revisited how Python handles strings internally. Since strings in Python are immutable, each concatenation inside a loop creates a new string object. This means that with every iteration, memory is reallocated and the existing content is copied over. As input size increases, this results in repeated allocations and copying — leading to unnecessary overhead and potential quadratic time complexity. While this may not be noticeable for small inputs, it becomes increasingly inefficient in production environments where code runs frequently or processes large datasets. To optimize the solution, I refactored the implementation to accumulate values in a list and join them at the end. This approach avoids repeated string creation and achieves linear time complexity, improving both performance and memory efficiency. It was a small refactor, but a meaningful one. Moments like this are a good reminder that understanding language internals — even for simple operations — can significantly impact the quality and efficiency of the code we write. #Python3 #Performance #CleanCode #SoftwareEngineering #Optimization
To view or add a comment, sign in
-
-
🚀 Day 4/30 | LeetCode Problem: Running Sum of 1D Array (1480) Problem: Given an array nums, return the running sum, where each element at index i is the sum of elements from index 0 to i. Approach: Initialize a variable to store the cumulative sum Traverse the array one by one Add each element to the cumulative sum Store the result in a new list This is a simple single-pass solution. Time Complexity: O(n) Space Complexity: O(n) Python Code: class Solution: def runningSum(self, nums): a = 0 b = [] for i in nums: a = a + i b.append(a) return b Example: Input: [1, 2, 3, 4] Output: [1, 3, 6, 10] Takeaway: Running sum is a basic form of prefix sum, which is very useful in many array problems. 📌 Accepted ✅ | All test cases passed 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day4 #Python #DSA #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode — Counting Characters & Pythonic Efficiency Hey everyone! 👋 Today was all about String Manipulation. The task was to write a function that returns the total number of characters in a given string. While it’s a simple concept, it’s a great exercise to visualize how data is traversed in memory. 👨💻 What I practiced today: ✅ String Iteration: Using a for loop to step through a string character by character. ✅ Counter Logic: Manually incrementing a variable to track the sequence length. ✅ Edge Case Handling: Ensuring the function correctly returns 0 for an empty string "". 📌 Today’s Task: ✔ Given a string s. ✔ Traverse the string and count every character. ✔ Return the final count. 🧠 Key Insight: In my solution today, I manually built a counter (O(n) time). However, in Python, the len() function is the most efficient way to do this. Unlike a manual loop, len() is O(1) (constant time) because Python stores the length of the string as an attribute in memory! ✨ Key Takeaway: Learning the manual logic behind basic tasks is essential for mastering algorithms, but knowing when to use built-in functions like len() is what makes your code professional and performant. #100DaysOfCode #Day55 #Python #CodingJourney #DSA #Strings #CleanCode #LogicBuilding #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
Weekly Challenge 2: Sum Two Numbers Optimized. Yesterday I shared a Brute Force solution for the Two Sum problem. It worked, but it is slow(O(n^2)). Today, let's optimize it using a Hash Map. The strategy, instead of using nest loops to compare wverything against everything, we use memory to our advantage. As we iterate through the list, we calculate the "complement" (Target- Current) and ask "Have I seen this number before?" A highly efficient Python implementation of the 'Two Sum' problem using a Hash Map (Dictionary). Unlike the Brute Force approach, this script solves the problem in a single pass ($O(n)$) by storing visited numbers and checking for their complement instantly. Check the code on my GitHub: https://lnkd.in/eq5cQvWT #python #Optimization #Algorithms #DataStructures #BigO
To view or add a comment, sign in
More from this author
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