Day 14 of DSA 🎯 How Slow & Fast Pointers Can Be Used in Numbers We usually think of slow & fast pointers in linked lists. But did you know we can use the same concept in numbers too? 🤯 📍 Problem: Happy Number (LeetCode 202) A number is happy if we replace it by the sum of the squares of its digits repeatedly, and eventually reach 1. If it loops endlessly in a cycle that doesn’t include 1, it’s not happy. ✅ Key Idea Treat the process as a sequence. If we end up in a cycle (not reaching 1), slow & fast pointers will eventually meet. 📌 Example n = 19 19 → 82 → 68 → 100 → 1 ( Reaches 1 → Happy Number ✅ ) n = 2 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (Cycle) ( Never reaches 1 → Not Happy ❌ ) Python Code class Solution: def fun(self, n: int) -> int: sum_n = 0 while n > 0: d = n % 10 total += d * d n //= 10 return sum_n def isHappy(self, n: int) -> bool: slow, fast = n, n while fast != 1: slow = self.fun(slow) fast = self.fun(self.fun(fast)) if slow == fast: # cycle detected return False return True 🚀 Why Does It Work? The sequence of sums is always within a limited range. So either it reaches 1 (happy) or enters a cycle (not happy). Slow pointer moves 1 step, fast pointer moves 2 steps. If there’s a cycle, they must meet. 💡 Key Takeaway Slow & fast pointers are not just for linked lists. They are powerful for detecting cycles in sequences, arrays, and even numbers! That’s it for Day 14! 🚀 Every problem solved today is a step closer to becoming the best version of me. #DSA #100DaysOfCode #LeetCode #HappyNumber #TwoPointers #LearningInPublic
Detecting Happy Numbers with Slow & Fast Pointers
More Relevant Posts
-
🚀 Day 50 of My Coding Journey Today, I explored powerful NumPy operations — sum() and prod() — and learned how combining them can solve interesting problems efficiently. 🔍 What I learned: sum(axis=0) → adds elements column-wise prod() → multiplies elements together By combining both, we can transform and reduce arrays in a single flow 💡 Problem Insight: Given a 2D array, 👉 First, compute the column-wise sum 👉 Then, find the product of that result 📌 Example: Input: 2 2 1 2 3 4 Step 1: Sum along axis 0 → [4, 6] Step 2: Product → 4 × 6 = 24 ✨ Key Takeaway: Understanding how axes work in NumPy makes complex operations simple and efficient. 💻 Code Snippet: import numpy as np n, m = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] my_array = np.array(arr) result = np.prod(np.sum(my_array, axis=0)) print(result) 🔥 Day 50 done! Staying consistent and learning something new every day. #Day50 #Python #NumPy #CodingJourney #LearningEveryday
To view or add a comment, sign in
-
-
Day 15/30 🔹 Problem: Check if a year is a leap year 🔹 What I focused on today: Understanding how multiple conditions work together 🔹 My Thinking Process: A year is divisible by 4 → leap year But if divisible by 100 → NOT a leap year Exception: if divisible by 400 → leap year 🔹 Inputs I used: Year 🔹 Code: year = int(input("Enter a year: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print("Leap Year") else: print("Not a Leap Year") 🔹 Example: Year = 2024 → Leap Year Year = 1900 → Not a Leap Year Year = 2000 → Leap Year 🔹 Key Takeaway: Combining conditions correctly is important to avoid logical mistakes, even in simple problems #Day15 #Python #30DaysOfCode #LearningInPublic #DataAnalytics #ProblemSolving
To view or add a comment, sign in
-
💻 Solved a great problem today: Count Increasing Subarrays 🚀 Given an array, the task was to count all strictly increasing subarrays of size ≥ 2. 🔍 Approach I used: Broke the array into continuous increasing segments For each segment of length k, calculated subarrays using the formula: 👉 k(k-1)/2 Summed all results to get the final answer ⚡ Time Complexity: O(n) 📦 Space Complexity: O(n) 💡 This problem helped me understand how breaking a problem into patterns can simplify complex logic. Here’s my Python solution 👇 class Solution: def countIncreasing(self, arr): list2 = [] list2.append(arr[0]) list3 = [] for i in range(1, len(arr)): if arr[i-1] < arr[i] and arr[i] > 2: list2.append(arr[i]) else: list3.append(list2) list2 = [] list2.append(arr[i]) list3.append(list2) ans = 0 for i in list3: if len(i) > 1: ans += (len(i) * (len(i) - 1)) // 2 return ans 🔥 Always learning, always improving. #python #dsa #coding #problemSolving #programming #developers #learning
To view or add a comment, sign in
-
-
Most people quit DSA before this point… I didn’t. Just crossed 100 problems solved on LeetCode 💻 Not going to sugarcoat it — this wasn’t smooth. Got stuck on “easy” problems, revisited basics multiple times, and had days where nothing clicked. But here’s what changed: • Focused on consistency over motivation • Repeated problems until patterns made sense • Started thinking in approaches, not just solutions Current progress: → 100+ problems solved → Moving from Easy → Medium → Building stronger fundamentals in Data Structures & Algorithms (DSA) → Recently earned a Pandas badge 🐼 Still a long way to go — this is just the base. Next target: better speed, deeper problem-solving, and more Medium/Hard questions. If you’re starting out or stuck — keep going. It compounds. What was the toughest phase in your DSA journey? LeetCode profile link -- https://lnkd.in/gU9-x_qz #LeetCode #DSA #ProblemSolving #CodingJourney #Python #SoftwareEngineering #TechCareers #100DaysOfCode #LearnInPublic #Consistency
To view or add a comment, sign in
-
-
🔥 Day 8/100 of My LeetCode Challenge — 0 ms (100%) 🔥 Hook: Most people fail this “easy” problem because they ignore one tiny detail — can you spot it? 💭 Problem: Add 1 to a number represented as an array of digits. Sounds simple, right? But here’s the catch 👇 👉 What if the last digit is 9? 👉 What if ALL digits are 9? Example: [9,9,9] → [1,0,0,0] 💥 🧠 What I learned today: Always think about edge cases Simple problems can hide tricky logic Traversing backwards can simplify carry problems ⚡ My Approach: Start from the end If digit < 9 → add 1 and return If digit == 9 → make it 0 and continue If all become 0 → add 1 at front 💻 Result: ✅ Runtime: 0 ms (100%) ✅ Clean & optimized solution 📈 Consistency Check Day 8 complete. No excuses. No breaks. Small wins daily → Big results later 🚀 #LeetCode #Day8 #CodingJourney #Python #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Hello dudes and dudettes!! 🚀 Day 11/150 — Cracked LeetCode 274: H-Index Today’s problem was less about coding… and more about thinking smart 😄 At first glance, it looks like just another array problem. But once I dug in, I realized it’s actually about measuring impact — not just numbers. 🔍 What’s the Problem About? You’re given an array where each number represents how many times a research paper was cited. Now the twist: 👉 You need to find the H-Index Which basically means: A researcher has an H-Index of h if they have h papers with at least h citations each. 🧠 The “Aha!” Moment Initially, it feels confusing… like, “Where do I even start?” But everything clicks when you: 👉 Sort the array in descending order Suddenly, the problem becomes super clean. Now it’s just about checking: “Do I have 1 paper with ≥1 citation?” “Do I have 2 papers with ≥2 citations?” “Do I have 3 papers with ≥3 citations?” …and so on. The moment this condition fails — boom, you stop. That’s your answer. 📊 Quick Example Input: [3, 0, 6, 1, 5] After sorting: [6, 5, 3, 1, 0] Now checking step-by-step: 1 paper → valid ✅ 2 papers → valid ✅ 3 papers → valid ✅ 4 papers → not valid ❌ 🎯 Final Answer: 3 💡 What Made This Problem Interesting? It’s not about checking everything — it’s about knowing when to stop A simple sort can completely change how you see the problem It teaches you to think in terms of thresholds and consistency, not just values 😎 My Takeaway This problem is a perfect reminder that: “Sometimes the smartest solution isn’t more work… it’s better perspective.” 🔥 One more step forward in the journey. Let’s keep building. #LeetCode #Algorithms #ProblemSolving #CodingJourney #100DaysOfCode #Python #LearningInPublic
To view or add a comment, sign in
-
-
Hello dudes and dudettes!! 🚀 Day 19/150 — Solved LeetCode 58: Length of Last Word Today’s problem looked super simple at first… but taught me a great lesson about handling edge cases carefully 😄 🧠 What’s the Problem About? You’re given a string that contains words separated by spaces. Your task is to find the length of the last word. Sounds easy, right? Well… not always 👇 💡 The Catch The string might contain: Extra spaces at the beginning Extra spaces at the end Multiple spaces between words So it’s not just about “finding the last word” — it’s about finding the last valid word. 🔥 Example Input: " hello world " At first glance, it looks messy 😵 But the actual last word is: 👉 "world" 👉 Length = 5 🧠 The Thought Process Instead of trying to split everything immediately, I started thinking: Why not scan from the end? Because: The last word is always near the end We can skip spaces quickly Then just count characters until we hit a space ⚙️ Approach That Worked Ignore trailing spaces Start from the end of the string Count characters until a space appears That count is your answer Simple, efficient, and clean. 😎 Why This Problem Is Interesting It’s not about complexity — it’s about precision It shows how small edge cases can break simple logic It encourages thinking in reverse (which is surprisingly powerful) 💡 What I Learned Always consider edge cases like extra spaces Sometimes scanning backward is smarter than forward Even easy problems can sharpen your attention to detail 🎯 Key Takeaway “Simple problems aren’t always trivial — they test how carefully you think.” 🔥 Another step forward — improving not just coding skills, but problem-solving mindset. #LeetCode #Algorithms #ProblemSolving #CodingJourney #100DaysOfCode #Python #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 3 of #14DaysOfPython 🐍 Today’s focus: Loops (Iteration Mastery) — where automation really begins. 💡 Easy way to understand loops: 🔹 Why loops? 👉 When you need to repeat a task multiple times instead of writing code again and again 💡 Core Concepts (Logic First): 🔹 for loop vs while loop for → when you know how many times to run while → when condition decides 🔹 range() variations range(n) → 0 to n-1 range(start, end) range(start, end, step) 🔹 Loop control break → stop loop immediately continue → skip current step pass → do nothing (placeholder) 🔹 Infinite loop ⚠️ 👉 Happens when condition never becomes false 🔹 Iteration patterns 👉 Numbers, strings, lists — everything can be looped 🧠 Problems I practiced: Sum of digits Reverse a number Factorial Count occurrences ✨ Key takeaway: Loops are not about syntax — they are about thinking in repetition and patterns. Day 3 done ✅ Moving to Day 4 💪 #Python #HackerRank #CodingJourney #LearningInPublic #ProblemSolving #DeveloperJourney #100DaysOfCode#codegnan
To view or add a comment, sign in
-
-
✅ Day 90 of 100 Days LeetCode Challenge Problem: 🔹 #476 – Number Complement 🔗 https://lnkd.in/gzE6gM7d Learning Journey: 🔹 Today’s problem focused on finding the complement of a number by flipping its binary bits. 🔹 I first converted the integer to its binary representation using bin(num)[2:]. 🔹 Then, I created a helper function to flip each bit: • '0' → '1' • '1' → '0' 🔹 After generating the flipped binary string, I converted it back to an integer using int(..., 2). 🔹 Returned the final complemented value. Concepts Used: 🔹 Binary Representation 🔹 Bit Manipulation 🔹 String Traversal 🔹 Base Conversion Key Insight: 🔹 The complement operation is essentially a bitwise NOT, but only within the significant bits of the number (ignoring leading zeros). 🔹 Converting to binary simplifies the flipping logic for beginners. Complexity: 🔹 Time: O(log n) 🔹 Space: O(log n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
🚀 Mastering the art of loops! 🔄 Discover how loops help your code execute repetitive tasks efficiently. Essentially, loops are like a magical chant that tells your program to keep doing something until a certain condition is met. For developers, mastering loops is crucial for automating tasks and iterating over data structures with ease. Here's the breakdown: 1️⃣ Initialize a counter variable 2️⃣ Set the condition for the loop 3️⃣ Define the action to perform in each iteration Sample code using a "for" loop in Python: ``` for i in range(5): print("Hello, World!") ``` 🌟 Pro Tip: Use loops to reduce redundancy in your code and boost efficiency. 💡 ⚠️ Common Mistake: Forgetting to update the counter variable in the loop, leading to an infinite loop! 🔄 🌟 What's your favorite use case for loops in your projects? Let's discuss! 💬 #Coding101 #LearnToCode #TechTips #CodeNewbie #PythonProgramming #DeveloperCommunity #LoopLogic #CodeEfficiency #ProDevSkills 🌐 View my full portfolio and more dev resources at tharindunipun.lk
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